diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 1b9642e0..bd8e2619 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,19 +1,23 @@ # syntax=docker/dockerfile:1 FROM debian:bookworm-slim -RUN apt-get update && apt-get install -y \ +RUN apt-get update && apt-get install -y --no-install-recommends \ libxkbcommon0 \ ca-certificates \ ca-certificates-java \ make \ curl \ git \ - openjdk-17-jdk \ + openjdk-17-jdk-headless \ unzip \ libc++1 \ vim \ && apt-get clean autoclean +# Ensure UTF-8 encoding +ENV LANG=C.UTF-8 +ENV LC_ALL=C.UTF-8 + WORKDIR /workspace COPY . /workspace diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 93873e87..42805473 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,33 +1,85 @@ name: CI on: push: - branches: - - main + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'stl-preview-head/**' + - 'stl-preview-base/**' pull_request: - branches: - - main + branches-ignore: + - 'stl-preview-head/**' + - 'stl-preview-base/**' jobs: lint: + timeout-minutes: 15 name: lint - runs-on: ubuntu-latest - if: github.repository == 'braintrustdata/braintrust-java' + runs-on: ${{ github.repository == 'stainless-sdks/braintrust-sdk-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v3 - + - uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 8 + 21 + cache: gradle + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Run lints + run: ./scripts/lint + + build: + timeout-minutes: 15 + name: build + runs-on: ${{ github.repository == 'stainless-sdks/braintrust-sdk-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + + steps: + - uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 8 + 21 + cache: gradle + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Build SDK + run: ./scripts/build + + test: + timeout-minutes: 15 + name: test + runs-on: ${{ github.repository == 'stainless-sdks/braintrust-sdk-java' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + steps: + - uses: actions/checkout@v4 + - name: Set up Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle uses: gradle/gradle-build-action@v2 - - name: Gradle build - run: | - ./gradlew build testClasses -x test + - name: Run tests + run: ./scripts/test diff --git a/.github/workflows/publish-sonatype.yml b/.github/workflows/publish-sonatype.yml old mode 100644 new mode 100755 index e21ef37f..d914ae66 --- a/.github/workflows/publish-sonatype.yml +++ b/.github/workflows/publish-sonatype.yml @@ -14,26 +14,28 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: temurin java-version: | 8 - 17 + 21 cache: gradle - name: Set up Gradle uses: gradle/gradle-build-action@v2 - name: Publish to Sonatype - run: | - ./gradlew publish --stacktrace + run: |- + 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" --no-configuration-cache env: SONATYPE_USERNAME: ${{ secrets.BRAINTRUST_SONATYPE_USERNAME || secrets.SONATYPE_USERNAME }} SONATYPE_PASSWORD: ${{ secrets.BRAINTRUST_SONATYPE_PASSWORD || secrets.SONATYPE_PASSWORD }} - GPG_SIGNING_KEY_ID: ${{ secrets.BRAINTRUST_SONATYPE_GPG_SIGNING_KEY_ID || secrets.GPG_SIGNING_KEY_ID }} GPG_SIGNING_KEY: ${{ secrets.BRAINTRUST_SONATYPE_GPG_SIGNING_KEY || secrets.GPG_SIGNING_KEY }} GPG_SIGNING_PASSWORD: ${{ secrets.BRAINTRUST_SONATYPE_GPG_SIGNING_PASSWORD || secrets.GPG_SIGNING_PASSWORD }} \ No newline at end of file diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml old mode 100644 new mode 100755 index c0508157..d9128fbc --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -1,6 +1,8 @@ name: Release Doctor on: pull_request: + branches: + - main workflow_dispatch: jobs: @@ -10,7 +12,7 @@ jobs: if: github.repository == 'braintrustdata/braintrust-java' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Check release environment run: | @@ -18,6 +20,5 @@ jobs: env: SONATYPE_USERNAME: ${{ secrets.BRAINTRUST_SONATYPE_USERNAME || secrets.SONATYPE_USERNAME }} SONATYPE_PASSWORD: ${{ secrets.BRAINTRUST_SONATYPE_PASSWORD || secrets.SONATYPE_PASSWORD }} - GPG_SIGNING_KEY_ID: ${{ secrets.BRAINTRUST_SONATYPE_GPG_SIGNING_KEY_ID || secrets.GPG_SIGNING_KEY_ID }} GPG_SIGNING_KEY: ${{ secrets.BRAINTRUST_SONATYPE_GPG_SIGNING_KEY || secrets.GPG_SIGNING_KEY }} GPG_SIGNING_PASSWORD: ${{ secrets.BRAINTRUST_SONATYPE_GPG_SIGNING_PASSWORD || secrets.GPG_SIGNING_PASSWORD }} diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 index face920d..b1346e6d --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ +.prism.log .gradle .idea -build +.kotlin +build/ codegen.log +kls_database.db diff --git a/.release-please-manifest.json b/.release-please-manifest.json old mode 100644 new mode 100755 index 10f30916..6d78745c --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.2.0" + ".": "0.9.0" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index 423e2f9a..2e43a77b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1,4 @@ -configured_endpoints: 31 +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: dca6e2cafd0764aa5fa3e78987e8b07c diff --git a/CHANGELOG.md b/CHANGELOG.md old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 index 5e03e95a..f3b9e7e5 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2024 Braintrust + Copyright 2025 Braintrust Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 151dfe2b..8d3b176c 100644 --- a/README.md +++ b/README.md @@ -2,50 +2,84 @@ -[![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.2.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. It includes helper classes with helpful types and documentation for every request and response property. +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. -## Documentation +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). The full API of this library can be found in [api.md](api.md). - ---- + -## Getting started +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). -### Install dependencies + -#### Gradle +## Installation +### Gradle + ```kotlin -implementation("com.braintrustdata.api:braintrust-java:0.2.0") +implementation("com.braintrustdata.api:braintrust-java:0.9.0") ``` -#### Maven +### Maven ```xml - com.braintrustdata.api - braintrust-java - 0.2.0 + com.braintrustdata.api + braintrust-java + 0.9.0 ``` -### Configure the client +## Requirements + +This library requires Java 8 or later. + +## Usage + +```java +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; +import com.braintrustdata.api.models.Project; +import com.braintrustdata.api.models.ProjectCreateParams; + +// Configures using the `braintrust.apiKey` and `braintrust.baseUrl` system properties +// Or configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables +BraintrustClient client = BraintrustOkHttpClient.fromEnv(); + +ProjectCreateParams params = ProjectCreateParams.builder() + .name("foobar") + .build(); +Project project = client.projects().create(params); +``` + +## Client configuration -Use `BraintrustOkHttpClient.builder()` to configure the client. At a minimum you need to set `.apiKey()`: +Configure the client using system properties or environment variables: ```java -import com.braintrustdata.api.client.BraintrustOkHttpClient; +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; + +// Configures using the `braintrust.apiKey` and `braintrust.baseUrl` system properties +// Or configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables +BraintrustClient client = BraintrustOkHttpClient.fromEnv(); +``` + +Or manually: + +```java +import com.braintrustdata.api.client.BraintrustClient; import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; BraintrustClient client = BraintrustOkHttpClient.builder() @@ -53,205 +87,313 @@ BraintrustClient client = BraintrustOkHttpClient.builder() .build(); ``` -Alternately, set the environment with `BRAINTRUST_API_KEY`, and use `BraintrustOkHttpClient.fromEnv()` to read from the environment. +Or using a combination of the two approaches: ```java -BraintrustClient client = BraintrustOkHttpClient.fromEnv(); +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; -// Note: you can also call fromEnv() from the client builder, for example if you need to set additional properties BraintrustClient client = BraintrustOkHttpClient.builder() + // Configures using the `braintrust.apiKey` and `braintrust.baseUrl` system properties + // Or configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables .fromEnv() - // ... set properties on the builder + .apiKey("My API Key") .build(); ``` -| Property | Environment variable | Required | Default value | -| -------- | -------------------- | -------- | ------------- | -| apiKey | `BRAINTRUST_API_KEY` | true | — | +See this table for the available options: + +| Setter | System property | Environment variable | Required | Default value | +| --------- | -------------------- | --------------------- | -------- | ------------------------------ | +| `apiKey` | `braintrust.apiKey` | `BRAINTRUST_API_KEY` | false | - | +| `baseUrl` | `braintrust.baseUrl` | `BRAINTRUST_BASE_URL` | true | `"https://api.braintrust.dev"` | -Read the documentation for more configuration options. +System properties take precedence over environment variables. ---- +> [!TIP] +> Don't create more than one client in the same application. Each client has a connection pool and +> thread pools, which are more efficient to share between requests. -### Example: creating a resource +### Modifying configuration -To create a new project, first use the `ProjectCreateParams` builder to specify attributes, -then pass that to the `create` method of the `project` service. +To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service: ```java -import com.braintrustdata.api.models.Project; -import com.braintrustdata.api.models.ProjectCreateParams; +import com.braintrustdata.api.client.BraintrustClient; -ProjectCreateParams params = ProjectCreateParams.builder() - .bodyparam(true) - .build(); -Project project = client.project().create(params); +BraintrustClient clientWithOptions = client.withOptions(optionsBuilder -> { + optionsBuilder.baseUrl("https://example.com"); + optionsBuilder.maxRetries(42); +}); ``` -### Example: listing resources +The `withOptions()` method does not affect the original client or service. -The Braintrust API provides a `list` method to get a paginated list of project. -You can retrieve the first page by: +## Requests and responses -```java -import com.braintrustdata.api.models.Page; -import com.braintrustdata.api.models.Project; +To send a request to the Braintrust API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class. -ProjectListPage page = client.project().list(); -for (Project project : page.objects()) { - System.out.println(project); -} -``` +For example, `client.projects().create(...)` should be called with an instance of `ProjectCreateParams`, and it will return an instance of `Project`. -See [Pagination](#pagination) below for more information on transparently working with lists of objects without worrying about fetching each page. +## Immutability ---- +Each class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it. -## Requests +Each class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy. -### Parameters and bodies +Because each class is immutable, builder modification will _never_ affect already built class instances. -To make a request to the Braintrust API, you generally build an instance of the appropriate `Params` class. +## Asynchronous execution -In [Example: creating a resource](#example-creating-a-resource) above, we used the `ProjectCreateParams.builder()` to pass to -the `create` method of the `project` service. - -Sometimes, the API may support other properties that are not yet supported in the Java SDK types. In that case, -you can attach them using the `putAdditionalProperty` method. +The default client is synchronous. To switch to asynchronous execution, call the `async()` method: ```java +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; +import com.braintrustdata.api.models.Project; +import com.braintrustdata.api.models.ProjectCreateParams; +import java.util.concurrent.CompletableFuture; + +// Configures using the `braintrust.apiKey` and `braintrust.baseUrl` system properties +// Or configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables +BraintrustClient client = BraintrustOkHttpClient.fromEnv(); + ProjectCreateParams params = ProjectCreateParams.builder() - // ... normal properties - .putAdditionalProperty("secret_param", "4242") + .name("foobar") .build(); +CompletableFuture project = client.async().projects().create(params); ``` -## Responses +Or create an asynchronous client from the beginning: -### Response validation +```java +import com.braintrustdata.api.client.BraintrustClientAsync; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync; +import com.braintrustdata.api.models.Project; +import com.braintrustdata.api.models.ProjectCreateParams; +import java.util.concurrent.CompletableFuture; -When receiving a response, the Braintrust Java SDK will deserialize it into instances of the typed model classes. In rare cases, the API may return a response property that doesn't match the expected Java type. If you directly access the mistaken property, the SDK will throw an unchecked `BraintrustInvalidDataException` at runtime. If you would prefer to check in advance that that response is completely well-typed, call `.validate()` on the returned model. +// Configures using the `braintrust.apiKey` and `braintrust.baseUrl` system properties +// Or configures using the `BRAINTRUST_API_KEY` and `BRAINTRUST_BASE_URL` environment variables +BraintrustClientAsync client = BraintrustOkHttpClientAsync.fromEnv(); -```java -Project project = client.project().create().validate(); +ProjectCreateParams params = ProjectCreateParams.builder() + .name("foobar") + .build(); +CompletableFuture project = client.projects().create(params); ``` -### Response properties as JSON +The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s. + +## Raw responses -In rare cases, you may want to access the underlying JSON value for a response property rather than using the typed version provided by -this SDK. Each model property has a corresponding JSON version, with an underscore before the method name, which returns a `JsonField` value. +The SDK defines methods that deserialize responses into instances of Java classes. However, these methods don't provide access to the response headers, status code, or the raw response body. + +To access this data, prefix any HTTP method call on a client or service with `withRawResponse()`: ```java -JsonField field = responseObj._field(); +import com.braintrustdata.api.core.http.Headers; +import com.braintrustdata.api.core.http.HttpResponseFor; +import com.braintrustdata.api.models.Project; +import com.braintrustdata.api.models.ProjectCreateParams; -if (field.isMissing()) { - // Value was not specified in the JSON response -} else if (field.isNull()) { - // Value was provided as a literal null -} else { - // See if value was provided as a string - Optional jsonString = field.asString(); +ProjectCreateParams params = ProjectCreateParams.builder() + .name("foobar") + .build(); +HttpResponseFor project = client.projects().withRawResponse().create(params); - // If the value given by the API did not match the shape that the SDK expects - // you can deserialise into a custom type - MyClass myObj = responseObj._field().asUnknown().orElseThrow().convert(MyClass.class); -} +int statusCode = project.statusCode(); +Headers headers = project.headers(); ``` -### Additional model properties - -Sometimes, the server response may include additional properties that are not yet available in this library's types. You can access them using the model's `_additionalProperties` method: +You can still deserialize the response into an instance of a Java class if needed: ```java -JsonValue secret = project._additionalProperties().get("secret_field"); +import com.braintrustdata.api.models.Project; + +Project parsedProject = project.parse(); ``` ---- +## Error handling + +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`](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. + +- [`BraintrustRetryableException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustRetryableException.kt): Generic error indicating a failure that could be retried by the client. + +- [`BraintrustInvalidDataException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response. + +- [`BraintrustException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class. ## Pagination -For methods that return a paginated list of results, this library provides convenient ways access -the results either one page at a time, or item-by-item across all pages. +The SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages. ### Auto-pagination -To iterate through all results across all pages, you can use `autoPager`, -which automatically handles fetching more pages for you: +To iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed. -### Synchronous +When using the synchronous client, the method returns an [`Iterable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html) ```java -// As an Iterable: -ProjectListPage page = client.project().list(params); +import com.braintrustdata.api.models.Project; +import com.braintrustdata.api.models.ProjectListPage; + +ProjectListPage page = client.projects().list(); + +// Process as an Iterable for (Project project : page.autoPager()) { System.out.println(project); -}; +} -// As a Stream: -client.project().list(params).autoPager().stream() +// Process as a Stream +page.autoPager() + .stream() .limit(50) .forEach(project -> System.out.println(project)); ``` -### Asynchronous +When using the asynchronous client, the method returns an [`AsyncStreamResponse`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/AsyncStreamResponse.kt): ```java -// Using forEach, which returns CompletableFuture: -asyncClient.project().list(params).autoPager() - .forEach(project -> System.out.println(project), executor); +import com.braintrustdata.api.core.http.AsyncStreamResponse; +import com.braintrustdata.api.models.Project; +import com.braintrustdata.api.models.ProjectListPageAsync; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +CompletableFuture pageFuture = client.async().projects().list(); + +pageFuture.thenRun(page -> page.autoPager().subscribe(project -> { + System.out.println(project); +})); + +// If you need to handle errors or completion of the stream +pageFuture.thenRun(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() { + @Override + public void onNext(Project project) { + System.out.println(project); + } + + @Override + public void onComplete(Optional error) { + if (error.isPresent()) { + System.out.println("Something went wrong!"); + throw new RuntimeException(error.get()); + } else { + System.out.println("No more!"); + } + } +})); + +// Or use futures +pageFuture.thenRun(page -> page.autoPager() + .subscribe(project -> { + System.out.println(project); + }) + .onCompleteFuture() + .whenComplete((unused, error) -> { + if (error != null) { + System.out.println("Something went wrong!"); + throw new RuntimeException(error); + } else { + System.out.println("No more!"); + } + })); ``` ### Manual pagination -If none of the above helpers meet your needs, you can also manually request pages one-by-one. -A page of results has a `data()` method to fetch the list of objects, as well as top-level -`response` and other methods to fetch top-level data about the page. It also has methods -`hasNextPage`, `getNextPage`, and `getNextPageParams` methods to help with pagination. +To access individual page items and manually request the next page, use the `items()`, +`hasNextPage()`, and `nextPage()` methods: ```java -ProjectListPage page = client.project().list(params); -while (page != null) { - for (Project project : page.objects()) { +import com.braintrustdata.api.models.Project; +import com.braintrustdata.api.models.ProjectListPage; + +ProjectListPage page = client.projects().list(); +while (true) { + for (Project project : page.items()) { System.out.println(project); } - page = page.getNextPage().orElse(null); + if (!page.hasNextPage()) { + break; + } + + page = page.nextPage(); } ``` ---- +## Logging -## Error handling +The SDK uses the standard [OkHttp logging interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor). + +Enable logging by setting the `BRAINTRUST_LOG` environment variable to `info`: + +```sh +export BRAINTRUST_LOG=info +``` + +Or to `debug` for more verbose logging: + +```sh +export BRAINTRUST_LOG=debug +``` + +## ProGuard and R8 -This library throws exceptions in a single hierarchy for easy handling: +Although the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `braintrust-java-core` is published with a [configuration file](braintrust-java-core/src/main/resources/META-INF/proguard/braintrust-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage). -- **`BraintrustException`** - Base exception for all exceptions +ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary. - - **`BraintrustServiceException`** - HTTP errors with a well-formed response body we were able to parse. The exception message and the `.debuggingRequestId()` will be set by the server. +## Jackson - | 400 | BadRequestException | - | ------ | ----------------------------- | - | 401 | AuthenticationException | - | 403 | PermissionDeniedException | - | 404 | NotFoundException | - | 422 | UnprocessableEntityException | - | 429 | RateLimitException | - | 5xx | InternalServerException | - | others | UnexpectedStatusCodeException | +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. - - **`BraintrustIoException`** - I/O networking errors - - **`BraintrustInvalidDataException`** - any other exceptions on the client side, e.g.: - - We failed to serialize the request body - - We failed to parse the response body (has access to response code and body) +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 -Requests that experience certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors will all be retried by default. -You can provide a `maxRetries` on the client builder to configure this: +The SDK automatically retries 2 times by default, with a short exponential backoff between requests. + +Only the following error types are retried: + +- Connection errors (for example, due to a network connectivity problem) +- 408 Request Timeout +- 409 Conflict +- 429 Rate Limit +- 5xx Internal + +The API may also explicitly instruct the SDK to retry or not retry a request. + +To set a custom number of retries, configure the client using the `maxRetries` method: ```java +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; + BraintrustClient client = BraintrustOkHttpClient.builder() .fromEnv() .maxRetries(4) @@ -260,9 +402,25 @@ BraintrustClient client = BraintrustOkHttpClient.builder() ### Timeouts -Requests time out after 1 minute by default. You can configure this on the client builder: +Requests time out after 1 minute by default. + +To set a custom timeout, configure the method call using the `timeout` method: + +```java +import com.braintrustdata.api.models.Project; + +Project project = client.projects().create( + params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build() +); +``` + +Or configure the default for all method calls at the client level: ```java +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; +import java.time.Duration; + BraintrustClient client = BraintrustOkHttpClient.builder() .fromEnv() .timeout(Duration.ofSeconds(30)) @@ -271,23 +429,305 @@ BraintrustClient client = BraintrustOkHttpClient.builder() ### Proxies -Requests can be routed through a proxy. You can configure this on the client builder: +To route requests through a proxy, configure the client using the `proxy` method: ```java +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; +import java.net.InetSocketAddress; +import java.net.Proxy; + BraintrustClient client = BraintrustOkHttpClient.builder() .fromEnv() .proxy(new Proxy( - Type.HTTP, - new InetSocketAddress("proxy.com", 8080) + Proxy.Type.HTTP, new InetSocketAddress( + "https://example.com", 8080 + ) )) .build(); ``` -## Semantic Versioning +### HTTPS + +> [!NOTE] +> Most applications should not call these methods, and instead use the system defaults. The defaults include +> special optimizations that can be lost if the implementations are modified. + +To configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods: + +```java +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; + +BraintrustClient client = BraintrustOkHttpClient.builder() + .fromEnv() + // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa. + .sslSocketFactory(yourSSLSocketFactory) + .trustManager(yourTrustManager) + .hostnameVerifier(yourHostnameVerifier) + .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. + +### Parameters + +To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class: + +```java +import com.braintrustdata.api.core.JsonValue; +import com.braintrustdata.api.models.ProjectCreateParams; + +ProjectCreateParams params = ProjectCreateParams.builder() + .putAdditionalHeader("Secret-Header", "42") + .putAdditionalQueryParam("secret_query_param", "42") + .putAdditionalBodyProperty("secretProperty", JsonValue.from("42")) + .build(); +``` + +These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods. + +To set undocumented parameters on _nested_ headers, query params, or body classes, call the `putAdditionalProperty` method on the nested class: + +```java +import com.braintrustdata.api.core.JsonValue; +import com.braintrustdata.api.models.ProjectSettings; +import com.braintrustdata.api.models.ProjectUpdateParams; + +ProjectUpdateParams params = ProjectUpdateParams.builder() + .settings(ProjectSettings.builder() + .putAdditionalProperty("secretProperty", JsonValue.from("42")) + .build()) + .build(); +``` + +These properties can be accessed on the nested built object later using the `_additionalProperties()` method. + +To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Values.kt) object to its setter: + +```java +import com.braintrustdata.api.core.JsonValue; +import com.braintrustdata.api.models.ProjectCreateParams; + +ProjectCreateParams params = ProjectCreateParams.builder() + .name(JsonValue.from(42)) + .build(); +``` + +The most straightforward way to create a [`JsonValue`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Values.kt) is using its `from(...)` method: + +```java +import com.braintrustdata.api.core.JsonValue; +import java.util.List; +import java.util.Map; + +// 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 + ) +)); +``` + +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: + +```java +import com.braintrustdata.api.core.JsonValue; +import java.util.Map; + +Map additionalProperties = client.projects().create(params)._additionalProperties(); +JsonValue secretPropertyValue = additionalProperties.get("secretProperty"); + +String result = secretPropertyValue.accept(new JsonValue.Visitor<>() { + @Override + public String visitNull() { + return "It's null!"; + } + + @Override + public String visitBoolean(boolean value) { + return "It's a boolean!"; + } + + @Override + public String visitNumber(Number value) { + return "It's a number!"; + } + + // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject` + // The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden +}); +``` + +To access a property's raw JSON value, which may be undocumented, call its `_` prefixed method: + +```java +import com.braintrustdata.api.core.JsonField; +import java.util.Optional; + +JsonField name = client.projects().create(params)._name(); + +if (name.isMissing()) { + // The property is absent from the JSON response +} else if (name.isNull()) { + // The property was set to literal null +} else { + // Check if value was provided as a string + // Other methods include `asNumber()`, `asBoolean()`, etc. + Optional jsonString = name.asString(); + + // Try to deserialize into a custom type + MyClass myObject = name.asUnknown().orElseThrow().convert(MyClass.class); +} +``` + +### Response validation + +In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else. + +By default, the SDK will not throw an exception in this case. It will throw [`BraintrustInvalidDataException`](braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustInvalidDataException.kt) only if you directly access the property. + +If you would prefer to check that the response is completely well-typed upfront, then either call `validate()`: + +```java +import com.braintrustdata.api.models.Project; + +Project project = client.projects().create(params).validate(); +``` + +Or configure the method call to validate the response using the `responseValidation` method: + +```java +import com.braintrustdata.api.models.Project; + +Project project = client.projects().create( + params, RequestOptions.builder().responseValidation(true).build() +); +``` + +Or configure the default for all method calls at the client level: + +```java +import com.braintrustdata.api.client.BraintrustClient; +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient; + +BraintrustClient client = BraintrustOkHttpClient.builder() + .fromEnv() + .responseValidation(true) + .build(); +``` + +## FAQ + +### Why don't you use plain `enum` classes? + +Java `enum` classes are not trivially [forwards compatible](https://www.stainless.com/blog/making-java-enums-forwards-compatible). Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value. + +### Why do you represent fields using `JsonField` instead of just plain `T`? + +Using `JsonField` enables a few features: + +- Allowing usage of [undocumented API functionality](#undocumented-api-functionality) +- Lazily [validating the API response against the expected shape](#response-validation) +- Representing absent vs explicitly null values + +### Why don't you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)? + +It is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don't want to introduce a breaking change every time we add a field to a class. + +### Why don't you use checked exceptions? + +Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason. + +Checked exceptions: + +- Are verbose to handle +- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error +- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function) +- Don't play well with lambdas (also due to the function coloring problem) + +## Semantic versioning This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: -1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals)_. +1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ 2. Changes that we do not expect to impact the vast majority of users in practice. We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..a7f4f3b4 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,27 @@ +# Security Policy + +## Reporting Security Issues + +This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. + +To report a security issue, please contact the Stainless team at security@stainless.com. + +## Responsible Disclosure + +We appreciate the efforts of security researchers and individuals who help us maintain the security of +SDKs we generate. If you believe you have found a security vulnerability, please adhere to responsible +disclosure practices by allowing us a reasonable amount of time to investigate and address the issue +before making any information public. + +## Reporting Non-SDK Related Security Issues + +If you encounter security issues that are not directly related to SDKs but pertain to the services +or products provided by Braintrust, please follow the respective company's security reporting guidelines. + +### Braintrust Terms and Policies + +Please contact info@braintrustdata.com for any questions or concerns regarding the security of our services. + +--- + +Thank you for helping us keep the SDKs and systems they interact with secure. diff --git a/bin/check-release-environment b/bin/check-release-environment old mode 100644 new mode 100755 index 63417e3d..3a6a7b4a --- a/bin/check-release-environment +++ b/bin/check-release-environment @@ -3,24 +3,24 @@ errors=() if [ -z "${SONATYPE_USERNAME}" ]; then - errors+=("The BRAINTRUST_SONATYPE_USERNAME secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The SONATYPE_USERNAME secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi if [ -z "${SONATYPE_PASSWORD}" ]; then - errors+=("The BRAINTRUST_SONATYPE_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The SONATYPE_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi if [ -z "${GPG_SIGNING_KEY}" ]; then - errors+=("The BRAINTRUST_SONATYPE_GPG_SIGNING_KEY secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The GPG_SIGNING_KEY secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi if [ -z "${GPG_SIGNING_PASSWORD}" ]; then - errors+=("The BRAINTRUST_SONATYPE_GPG_SIGNING_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") + errors+=("The GPG_SIGNING_PASSWORD secret has not been set. Please set it in either this repository's secrets or your organization secrets") fi -len=${#errors[@]} +lenErrors=${#errors[@]} -if [[ len -gt 0 ]]; then +if [[ lenErrors -gt 0 ]]; then echo -e "Found the following errors in the release environment:\n" for error in "${errors[@]}"; do diff --git a/braintrust-java-client-okhttp/build.gradle.kts b/braintrust-java-client-okhttp/build.gradle.kts old mode 100644 new mode 100755 index 23aa41cc..16bbfd8e --- a/braintrust-java-client-okhttp/build.gradle.kts +++ b/braintrust-java-client-okhttp/build.gradle.kts @@ -6,10 +6,10 @@ plugins { dependencies { api(project(":braintrust-java-core")) - implementation("com.google.guava:guava:31.1-jre") - implementation("com.squareup.okhttp3:okhttp:4.10.0") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") testImplementation(kotlin("test")) - testImplementation("org.assertj:assertj-core:3.23.1") - testImplementation("org.slf4j:slf4j-simple:1.7.29") + testImplementation("org.assertj:assertj-core:3.25.3") + testImplementation("com.github.tomakehurst:wiremock-jre8:2.35.2") } 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 old mode 100644 new mode 100755 index 16291f71..e91ce488 --- 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 @@ -5,37 +5,216 @@ package com.braintrustdata.api.client.okhttp import com.braintrustdata.api.client.BraintrustClient import com.braintrustdata.api.client.BraintrustClientImpl import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.Sleeper +import com.braintrustdata.api.core.Timeout +import com.braintrustdata.api.core.http.AsyncStreamResponse +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.HttpClient +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.jsonMapper import com.fasterxml.jackson.databind.json.JsonMapper import java.net.Proxy import java.time.Clock import java.time.Duration +import java.util.Optional +import java.util.concurrent.Executor +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager +import kotlin.jvm.optionals.getOrNull +/** + * A class that allows building an instance of [BraintrustClient] with [OkHttpClient] as the + * underlying [HttpClient]. + */ class BraintrustOkHttpClient private constructor() { companion object { + /** Returns a mutable builder for constructing an instance of [BraintrustClient]. */ @JvmStatic fun builder() = Builder() + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ @JvmStatic fun fromEnv(): BraintrustClient = builder().fromEnv().build() } - class Builder { + /** A builder for [BraintrustOkHttpClient]. */ + class Builder internal constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var baseUrl: String = ClientOptions.PRODUCTION_URL - // default timeout for client is 1 minute - private var timeout: Duration = Duration.ofSeconds(60) private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + + /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ + fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) + + /** + * The socket factory used to secure HTTPS connections. + * + * If this is set, then [trustManager] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ + fun sslSocketFactory(sslSocketFactory: Optional) = + sslSocketFactory(sslSocketFactory.getOrNull()) + + /** + * The trust manager used to secure HTTPS connections. + * + * If this is set, then [sslSocketFactory] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } + + /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ + fun trustManager(trustManager: Optional) = + trustManager(trustManager.getOrNull()) + + /** + * The verifier used to confirm that response certificates apply to requested hostnames for + * HTTPS connections. + * + * If unset, then a default hostname verifier is used. + */ + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier + } + + /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ + fun hostnameVerifier(hostnameVerifier: Optional) = + hostnameVerifier(hostnameVerifier.getOrNull()) + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) } + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.braintrustdata.api.core.jsonMapper]. The default is usually sufficient + * and rarely needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + clientOptions.streamHandlerExecutor(streamHandlerExecutor) + } + + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ fun clock(clock: Clock) = apply { clientOptions.clock(clock) } + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.braintrust.dev`. + */ + fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + clientOptions.responseValidation(responseValidation) + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + + fun apiKey(apiKey: String?) = apply { clientOptions.apiKey(apiKey) } + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } + fun headers(headers: Map>) = apply { clientOptions.headers(headers) } @@ -46,38 +225,99 @@ class BraintrustOkHttpClient private constructor() { clientOptions.putHeaders(name, values) } + fun putAllHeaders(headers: Headers) = apply { clientOptions.putAllHeaders(headers) } + fun putAllHeaders(headers: Map>) = apply { clientOptions.putAllHeaders(headers) } - fun removeHeader(name: String) = apply { clientOptions.removeHeader(name) } + fun replaceHeaders(name: String, value: String) = apply { + clientOptions.replaceHeaders(name, value) + } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun replaceHeaders(name: String, values: Iterable) = apply { + clientOptions.replaceHeaders(name, values) + } - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + fun replaceAllHeaders(headers: Headers) = apply { clientOptions.replaceAllHeaders(headers) } - fun proxy(proxy: Proxy) = apply { this.proxy = proxy } + fun replaceAllHeaders(headers: Map>) = apply { + clientOptions.replaceAllHeaders(headers) + } - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) + fun removeHeaders(name: String) = apply { clientOptions.removeHeaders(name) } + + fun removeAllHeaders(names: Set) = apply { clientOptions.removeAllHeaders(names) } + + fun queryParams(queryParams: QueryParams) = apply { clientOptions.queryParams(queryParams) } + + fun queryParams(queryParams: Map>) = apply { + clientOptions.queryParams(queryParams) + } + + fun putQueryParam(key: String, value: String) = apply { + clientOptions.putQueryParam(key, value) + } + + fun putQueryParams(key: String, values: Iterable) = apply { + clientOptions.putQueryParams(key, values) + } + + fun putAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun replaceQueryParams(key: String, value: String) = apply { + clientOptions.replaceQueryParams(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + clientOptions.replaceQueryParams(key, values) } - fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun removeQueryParams(key: String) = apply { clientOptions.removeQueryParams(key) } + fun removeAllQueryParams(keys: Set) = apply { + clientOptions.removeAllQueryParams(keys) + } + + /** + * Updates configuration using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ fun fromEnv() = apply { clientOptions.fromEnv() } - fun build(): BraintrustClient { - return BraintrustClientImpl( + /** + * Returns an immutable instance of [BraintrustClient]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): BraintrustClient = + BraintrustClientImpl( clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) - .timeout(timeout) + .timeout(clientOptions.timeout()) .proxy(proxy) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) .build() ) .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 old mode 100644 new mode 100755 index 307fb329..ae462cb7 --- 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 @@ -5,37 +5,216 @@ package com.braintrustdata.api.client.okhttp import com.braintrustdata.api.client.BraintrustClientAsync import com.braintrustdata.api.client.BraintrustClientAsyncImpl import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.Sleeper +import com.braintrustdata.api.core.Timeout +import com.braintrustdata.api.core.http.AsyncStreamResponse +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.HttpClient +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.jsonMapper import com.fasterxml.jackson.databind.json.JsonMapper import java.net.Proxy import java.time.Clock import java.time.Duration +import java.util.Optional +import java.util.concurrent.Executor +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager +import kotlin.jvm.optionals.getOrNull +/** + * A class that allows building an instance of [BraintrustClientAsync] with [OkHttpClient] as the + * underlying [HttpClient]. + */ class BraintrustOkHttpClientAsync private constructor() { companion object { + /** Returns a mutable builder for constructing an instance of [BraintrustClientAsync]. */ @JvmStatic fun builder() = Builder() + /** + * Returns a client configured using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ @JvmStatic fun fromEnv(): BraintrustClientAsync = builder().fromEnv().build() } - class Builder { + /** A builder for [BraintrustOkHttpClientAsync]. */ + class Builder internal constructor() { private var clientOptions: ClientOptions.Builder = ClientOptions.builder() - private var baseUrl: String = ClientOptions.PRODUCTION_URL - // default timeout for client is 1 minute - private var timeout: Duration = Duration.ofSeconds(60) private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null - fun baseUrl(baseUrl: String) = apply { - clientOptions.baseUrl(baseUrl) - this.baseUrl = baseUrl + fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } + + /** Alias for calling [Builder.proxy] with `proxy.orElse(null)`. */ + fun proxy(proxy: Optional) = proxy(proxy.getOrNull()) + + /** + * The socket factory used to secure HTTPS connections. + * + * If this is set, then [trustManager] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + /** Alias for calling [Builder.sslSocketFactory] with `sslSocketFactory.orElse(null)`. */ + fun sslSocketFactory(sslSocketFactory: Optional) = + sslSocketFactory(sslSocketFactory.getOrNull()) + + /** + * The trust manager used to secure HTTPS connections. + * + * If this is set, then [sslSocketFactory] must also be set. + * + * If unset, then the system default is used. Most applications should not call this method, + * and instead use the system default. The default include special optimizations that can be + * lost if the implementation is modified. + */ + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } + + /** Alias for calling [Builder.trustManager] with `trustManager.orElse(null)`. */ + fun trustManager(trustManager: Optional) = + trustManager(trustManager.getOrNull()) + + /** + * The verifier used to confirm that response certificates apply to requested hostnames for + * HTTPS connections. + * + * If unset, then a default hostname verifier is used. + */ + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier + } + + /** Alias for calling [Builder.hostnameVerifier] with `hostnameVerifier.orElse(null)`. */ + fun hostnameVerifier(hostnameVerifier: Optional) = + hostnameVerifier(hostnameVerifier.getOrNull()) + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + clientOptions.checkJacksonVersionCompatibility(checkJacksonVersionCompatibility) } + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.braintrustdata.api.core.jsonMapper]. The default is usually sufficient + * and rarely needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { clientOptions.jsonMapper(jsonMapper) } + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + clientOptions.streamHandlerExecutor(streamHandlerExecutor) + } + + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { clientOptions.sleeper(sleeper) } + + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ fun clock(clock: Clock) = apply { clientOptions.clock(clock) } + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.braintrust.dev`. + */ + fun baseUrl(baseUrl: String?) = apply { clientOptions.baseUrl(baseUrl) } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + clientOptions.responseValidation(responseValidation) + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { clientOptions.timeout(timeout) } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = apply { clientOptions.timeout(timeout) } + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + + fun apiKey(apiKey: String?) = apply { clientOptions.apiKey(apiKey) } + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + fun headers(headers: Headers) = apply { clientOptions.headers(headers) } + fun headers(headers: Map>) = apply { clientOptions.headers(headers) } @@ -46,38 +225,99 @@ class BraintrustOkHttpClientAsync private constructor() { clientOptions.putHeaders(name, values) } + fun putAllHeaders(headers: Headers) = apply { clientOptions.putAllHeaders(headers) } + fun putAllHeaders(headers: Map>) = apply { clientOptions.putAllHeaders(headers) } - fun removeHeader(name: String) = apply { clientOptions.removeHeader(name) } + fun replaceHeaders(name: String, value: String) = apply { + clientOptions.replaceHeaders(name, value) + } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun replaceHeaders(name: String, values: Iterable) = apply { + clientOptions.replaceHeaders(name, values) + } - fun maxRetries(maxRetries: Int) = apply { clientOptions.maxRetries(maxRetries) } + fun replaceAllHeaders(headers: Headers) = apply { clientOptions.replaceAllHeaders(headers) } - fun proxy(proxy: Proxy) = apply { this.proxy = proxy } + fun replaceAllHeaders(headers: Map>) = apply { + clientOptions.replaceAllHeaders(headers) + } - fun responseValidation(responseValidation: Boolean) = apply { - clientOptions.responseValidation(responseValidation) + fun removeHeaders(name: String) = apply { clientOptions.removeHeaders(name) } + + fun removeAllHeaders(names: Set) = apply { clientOptions.removeAllHeaders(names) } + + fun queryParams(queryParams: QueryParams) = apply { clientOptions.queryParams(queryParams) } + + fun queryParams(queryParams: Map>) = apply { + clientOptions.queryParams(queryParams) + } + + fun putQueryParam(key: String, value: String) = apply { + clientOptions.putQueryParam(key, value) + } + + fun putQueryParams(key: String, values: Iterable) = apply { + clientOptions.putQueryParams(key, values) + } + + fun putAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + clientOptions.putAllQueryParams(queryParams) + } + + fun replaceQueryParams(key: String, value: String) = apply { + clientOptions.replaceQueryParams(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + clientOptions.replaceQueryParams(key, values) } - fun apiKey(apiKey: String) = apply { clientOptions.apiKey(apiKey) } + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + clientOptions.replaceAllQueryParams(queryParams) + } + + fun removeQueryParams(key: String) = apply { clientOptions.removeQueryParams(key) } + fun removeAllQueryParams(keys: Set) = apply { + clientOptions.removeAllQueryParams(keys) + } + + /** + * Updates configuration using system properties and environment variables. + * + * @see ClientOptions.Builder.fromEnv + */ fun fromEnv() = apply { clientOptions.fromEnv() } - fun build(): BraintrustClientAsync { - return BraintrustClientAsyncImpl( + /** + * Returns an immutable instance of [BraintrustClientAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): BraintrustClientAsync = + BraintrustClientAsyncImpl( clientOptions .httpClient( OkHttpClient.builder() - .baseUrl(baseUrl) - .timeout(timeout) + .timeout(clientOptions.timeout()) .proxy(proxy) + .sslSocketFactory(sslSocketFactory) + .trustManager(trustManager) + .hostnameVerifier(hostnameVerifier) .build() ) .build() ) - } } } diff --git a/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClient.kt b/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClient.kt old mode 100644 new mode 100755 index 45605ded..2ffdf3d7 --- a/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClient.kt +++ b/braintrust-java-client-okhttp/src/main/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClient.kt @@ -1,23 +1,25 @@ package com.braintrustdata.api.client.okhttp import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.Timeout +import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.HttpClient import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest import com.braintrustdata.api.core.http.HttpRequestBody import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.errors.BraintrustIoException -import com.google.common.collect.ListMultimap -import com.google.common.collect.MultimapBuilder import java.io.IOException import java.io.InputStream import java.net.Proxy import java.time.Duration +import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.SSLSocketFactory +import javax.net.ssl.X509TrustManager import okhttp3.Call import okhttp3.Callback -import okhttp3.Headers -import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType @@ -25,28 +27,14 @@ import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response +import okhttp3.logging.HttpLoggingInterceptor import okio.BufferedSink class OkHttpClient -private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val baseUrl: HttpUrl) : - HttpClient { - - private fun getClient(requestOptions: RequestOptions): okhttp3.OkHttpClient { - val timeout = requestOptions.timeout ?: return okHttpClient - return okHttpClient - .newBuilder() - .connectTimeout(timeout) - .readTimeout(timeout) - .writeTimeout(timeout) - .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30)) - .build() - } +private constructor(@JvmSynthetic internal val okHttpClient: okhttp3.OkHttpClient) : HttpClient { - override fun execute( - request: HttpRequest, - requestOptions: RequestOptions, - ): HttpResponse { - val call = getClient(requestOptions).newCall(request.toRequest()) + override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { + val call = newCall(request, requestOptions) return try { call.execute().toResponse() @@ -63,10 +51,7 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val ): CompletableFuture { val future = CompletableFuture() - request.body?.run { future.whenComplete { _, _ -> close() } } - - val call = getClient(requestOptions).newCall(request.toRequest()) - + val call = newCall(request, requestOptions) call.enqueue( object : Callback { override fun onResponse(call: Call, response: Response) { @@ -79,6 +64,13 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val } ) + future.whenComplete { _, e -> + if (e is CancellationException) { + call.cancel() + } + request.body?.close() + } + return future } @@ -88,46 +80,93 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val okHttpClient.cache?.close() } - private fun HttpRequest.toRequest(): Request { + private fun newCall(request: HttpRequest, requestOptions: RequestOptions): Call { + val clientBuilder = okHttpClient.newBuilder() + + val logLevel = + when (System.getenv("BRAINTRUST_LOG")?.lowercase()) { + "info" -> HttpLoggingInterceptor.Level.BASIC + "debug" -> HttpLoggingInterceptor.Level.BODY + else -> null + } + if (logLevel != null) { + clientBuilder.addNetworkInterceptor( + HttpLoggingInterceptor().setLevel(logLevel).apply { redactHeader("Authorization") } + ) + } + + requestOptions.timeout?.let { + clientBuilder + .connectTimeout(it.connect()) + .readTimeout(it.read()) + .writeTimeout(it.write()) + .callTimeout(it.request()) + } + + val client = clientBuilder.build() + return client.newCall(request.toRequest(client)) + } + + private fun HttpRequest.toRequest(client: okhttp3.OkHttpClient): Request { var body: RequestBody? = body?.toRequestBody() - // OkHttpClient always requires a request body for PUT and POST methods - if (body == null && (method == HttpMethod.PUT || method == HttpMethod.POST)) { + if (body == null && requiresBody(method)) { body = "".toRequestBody() } val builder = Request.Builder().url(toUrl()).method(method.name, body) - headers.forEach(builder::header) + headers.names().forEach { name -> + headers.values(name).forEach { builder.addHeader(name, it) } + } + + if ( + !headers.names().contains("X-Stainless-Read-Timeout") && client.readTimeoutMillis != 0 + ) { + builder.addHeader( + "X-Stainless-Read-Timeout", + Duration.ofMillis(client.readTimeoutMillis.toLong()).seconds.toString(), + ) + } + if (!headers.names().contains("X-Stainless-Timeout") && client.callTimeoutMillis != 0) { + builder.addHeader( + "X-Stainless-Timeout", + Duration.ofMillis(client.callTimeoutMillis.toLong()).seconds.toString(), + ) + } return builder.build() } - private fun HttpRequest.toUrl(): String { - url?.let { - return it + /** `OkHttpClient` always requires a request body for some methods. */ + private fun requiresBody(method: HttpMethod): Boolean = + when (method) { + HttpMethod.POST, + HttpMethod.PUT, + HttpMethod.PATCH -> true + else -> false } - val builder = baseUrl.newBuilder() + private fun HttpRequest.toUrl(): String { + val builder = baseUrl.toHttpUrl().newBuilder() pathSegments.forEach(builder::addPathSegment) - queryParams.forEach(builder::addQueryParameter) + queryParams.keys().forEach { key -> + queryParams.values(key).forEach { builder.addQueryParameter(key, it) } + } return builder.toString() } private fun HttpRequestBody.toRequestBody(): RequestBody { val mediaType = contentType()?.toMediaType() + val length = contentLength() return object : RequestBody() { - override fun contentType(): MediaType? { - return mediaType - } + override fun contentType(): MediaType? = mediaType - override fun isOneShot(): Boolean { - return !repeatable() - } + override fun contentLength(): Long = length - override fun writeTo(sink: BufferedSink) { - writeTo(sink.outputStream()) - } + override fun isOneShot(): Boolean = !repeatable() + + override fun writeTo(sink: BufferedSink) = writeTo(sink.outputStream()) } } @@ -135,63 +174,79 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val val headers = headers.toHeaders() return object : HttpResponse { - override fun statusCode(): Int { - return code - } + override fun statusCode(): Int = code - override fun headers(): ListMultimap { - return headers - } + override fun headers(): Headers = headers - override fun body(): InputStream { - return body!!.byteStream() - } + override fun body(): InputStream = body!!.byteStream() - override fun close() { - body!!.close() - } + override fun close() = body!!.close() } } - private fun Headers.toHeaders(): ListMultimap { - val headers = - MultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER) - .arrayListValues() - .build() - - forEach { pair -> headers.put(pair.first, pair.second) } - - return headers + private fun okhttp3.Headers.toHeaders(): Headers { + val headersBuilder = Headers.builder() + forEach { (name, value) -> headersBuilder.put(name, value) } + return headersBuilder.build() } companion object { @JvmStatic fun builder() = Builder() } - class Builder { + class Builder internal constructor() { - private var baseUrl: HttpUrl? = null - // default timeout is 1 minute - private var timeout: Duration = Duration.ofSeconds(60) + private var timeout: Timeout = Timeout.default() private var proxy: Proxy? = null + private var sslSocketFactory: SSLSocketFactory? = null + private var trustManager: X509TrustManager? = null + private var hostnameVerifier: HostnameVerifier? = null - fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl.toHttpUrl() } + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) fun proxy(proxy: Proxy?) = apply { this.proxy = proxy } - fun build(): OkHttpClient { - return OkHttpClient( + fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply { + this.sslSocketFactory = sslSocketFactory + } + + fun trustManager(trustManager: X509TrustManager?) = apply { + this.trustManager = trustManager + } + + fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply { + this.hostnameVerifier = hostnameVerifier + } + + fun build(): OkHttpClient = + OkHttpClient( okhttp3.OkHttpClient.Builder() - .connectTimeout(timeout) - .readTimeout(timeout) - .writeTimeout(timeout) - .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30)) + .connectTimeout(timeout.connect()) + .readTimeout(timeout.read()) + .writeTimeout(timeout.write()) + .callTimeout(timeout.request()) .proxy(proxy) - .build(), - checkNotNull(baseUrl) { "`baseUrl` is required but was not set" }, + .apply { + val sslSocketFactory = sslSocketFactory + val trustManager = trustManager + if (sslSocketFactory != null && trustManager != null) { + sslSocketFactory(sslSocketFactory, trustManager) + } else { + check((sslSocketFactory != null) == (trustManager != null)) { + "Both or none of `sslSocketFactory` and `trustManager` must be set, but only one was set" + } + } + + hostnameVerifier?.let(::hostnameVerifier) + } + .build() + .apply { + // We usually make all our requests to the same host so it makes sense to + // raise the per-host limit to the overall limit. + dispatcher.maxRequestsPerHost = dispatcher.maxRequests + } ) - } } } diff --git a/braintrust-java-client-okhttp/src/test/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClientTest.kt b/braintrust-java-client-okhttp/src/test/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClientTest.kt new file mode 100644 index 00000000..ed9f0458 --- /dev/null +++ b/braintrust-java-client-okhttp/src/test/kotlin/com/braintrustdata/api/client/okhttp/OkHttpClientTest.kt @@ -0,0 +1,44 @@ +package com.braintrustdata.api.client.okhttp + +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.github.tomakehurst.wiremock.client.WireMock.* +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo +import com.github.tomakehurst.wiremock.junit5.WireMockTest +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.parallel.ResourceLock + +@WireMockTest +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class OkHttpClientTest { + + private lateinit var baseUrl: String + private lateinit var httpClient: OkHttpClient + + @BeforeEach + fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { + baseUrl = wmRuntimeInfo.httpBaseUrl + httpClient = OkHttpClient.builder().build() + } + + @Test + fun executeAsync_whenFutureCancelled_cancelsUnderlyingCall() { + stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) + val responseFuture = + httpClient.executeAsync( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build() + ) + val call = httpClient.okHttpClient.dispatcher.runningCalls().single() + + responseFuture.cancel(false) + + // Should have cancelled the underlying call + assertThat(call.isCanceled()).isTrue() + } +} diff --git a/braintrust-java-core/build.gradle.kts b/braintrust-java-core/build.gradle.kts old mode 100644 new mode 100755 index 9e92de7e..0e09ef31 --- a/braintrust-java-core/build.gradle.kts +++ b/braintrust-java-core/build.gradle.kts @@ -3,24 +3,39 @@ 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.14.1") - api("com.fasterxml.jackson.core:jackson-databind:2.14.1") - api("com.google.guava:guava:31.1-jre") + 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.14.1") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.14.1") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.1") - implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.1") - implementation("org.apache.httpcomponents.core5:httpcore5:5.2.1") - implementation("org.apache.httpcomponents.client5:httpclient5:5.2.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") testImplementation(kotlin("test")) testImplementation(project(":braintrust-java-client-okhttp")) - testImplementation("com.github.tomakehurst:wiremock-jre8:2.33.2") - testImplementation("org.assertj:assertj-core:3.23.1") - testImplementation("org.assertj:assertj-guava:3.5.0") - testImplementation("org.slf4j:slf4j-simple:1.7.29") - testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.1") - testImplementation("org.junit.jupiter:junit-jupiter-params:5.9.1") + testImplementation("com.github.tomakehurst:wiremock-jre8:2.35.2") + 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/client/BraintrustClient.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClient.kt old mode 100644 new mode 100755 index 22359153..7881923e --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClient.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClient.kt @@ -1,21 +1,162 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.client -import com.braintrustdata.api.models.* -import com.braintrustdata.api.services.blocking.* +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.services.blocking.AclService +import com.braintrustdata.api.services.blocking.AiSecretService +import com.braintrustdata.api.services.blocking.ApiKeyService +import com.braintrustdata.api.services.blocking.DatasetService +import com.braintrustdata.api.services.blocking.EnvVarService +import com.braintrustdata.api.services.blocking.EvalService +import com.braintrustdata.api.services.blocking.ExperimentService +import com.braintrustdata.api.services.blocking.FunctionService +import com.braintrustdata.api.services.blocking.GroupService +import com.braintrustdata.api.services.blocking.OrganizationService +import com.braintrustdata.api.services.blocking.ProjectScoreService +import com.braintrustdata.api.services.blocking.ProjectService +import com.braintrustdata.api.services.blocking.ProjectTagService +import com.braintrustdata.api.services.blocking.PromptService +import com.braintrustdata.api.services.blocking.RoleService +import com.braintrustdata.api.services.blocking.SpanIframeService +import com.braintrustdata.api.services.blocking.TopLevelService +import com.braintrustdata.api.services.blocking.UserService +import com.braintrustdata.api.services.blocking.ViewService +import java.util.function.Consumer +/** + * A client for interacting with the Braintrust REST API synchronously. You can also switch to + * asynchronous execution via the [async] method. + * + * This client performs best when you create a single instance and reuse it for all interactions + * with the REST API. This is because each client holds its own connection pool and thread pools. + * Reusing connections and threads reduces latency and saves memory. The client also handles rate + * limiting per client. This means that creating and using multiple instances at the same time will + * not respect rate limits. + * + * The threads and connections that are held will be released automatically if they remain idle. But + * if you are writing an application that needs to aggressively release unused resources, then you + * may call [close]. + */ interface BraintrustClient { + /** + * Returns a version of this client that uses asynchronous execution. + * + * The returned client shares its resources, like its connection pool and thread pools, with + * this client. + */ fun async(): BraintrustClientAsync + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BraintrustClient + fun topLevel(): TopLevelService - fun project(): ProjectService + fun projects(): ProjectService + + fun experiments(): ExperimentService + + fun datasets(): DatasetService + + fun prompts(): PromptService + + fun roles(): RoleService + + fun groups(): GroupService + + fun acls(): AclService + + fun users(): UserService + + fun projectScores(): ProjectScoreService + + fun projectTags(): ProjectTagService + + fun spanIframes(): SpanIframeService + + fun functions(): FunctionService + + fun views(): ViewService + + fun organizations(): OrganizationService + + fun apiKeys(): ApiKeyService + + fun aiSecrets(): AiSecretService + + fun envVars(): EnvVarService + + fun evals(): EvalService + + /** + * Closes this client, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because the client is long-lived and + * usually should not be synchronously closed via try-with-resources. + * + * It's also usually not necessary to call this method at all. the default HTTP client + * automatically releases threads and connections if they remain idle, but if you are writing an + * application that needs to aggressively release unused resources, then you may call this + * method. + */ + fun close() + + /** A view of [BraintrustClient] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BraintrustClient.WithRawResponse + + fun topLevel(): TopLevelService.WithRawResponse + + fun projects(): ProjectService.WithRawResponse + + fun experiments(): ExperimentService.WithRawResponse + + fun datasets(): DatasetService.WithRawResponse + + fun prompts(): PromptService.WithRawResponse + + fun roles(): RoleService.WithRawResponse + + fun groups(): GroupService.WithRawResponse + + fun acls(): AclService.WithRawResponse + + fun users(): UserService.WithRawResponse + + fun projectScores(): ProjectScoreService.WithRawResponse + + fun projectTags(): ProjectTagService.WithRawResponse + + fun spanIframes(): SpanIframeService.WithRawResponse + + fun functions(): FunctionService.WithRawResponse + + fun views(): ViewService.WithRawResponse + + fun organizations(): OrganizationService.WithRawResponse + + fun apiKeys(): ApiKeyService.WithRawResponse + + fun aiSecrets(): AiSecretService.WithRawResponse - fun experiment(): ExperimentService + fun envVars(): EnvVarService.WithRawResponse - fun dataset(): DatasetService + fun evals(): EvalService.WithRawResponse + } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsync.kt old mode 100644 new mode 100755 index 726e3a61..c6edb032 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsync.kt @@ -1,21 +1,166 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.client -import com.braintrustdata.api.models.* -import com.braintrustdata.api.services.async.* +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.services.async.AclServiceAsync +import com.braintrustdata.api.services.async.AiSecretServiceAsync +import com.braintrustdata.api.services.async.ApiKeyServiceAsync +import com.braintrustdata.api.services.async.DatasetServiceAsync +import com.braintrustdata.api.services.async.EnvVarServiceAsync +import com.braintrustdata.api.services.async.EvalServiceAsync +import com.braintrustdata.api.services.async.ExperimentServiceAsync +import com.braintrustdata.api.services.async.FunctionServiceAsync +import com.braintrustdata.api.services.async.GroupServiceAsync +import com.braintrustdata.api.services.async.OrganizationServiceAsync +import com.braintrustdata.api.services.async.ProjectScoreServiceAsync +import com.braintrustdata.api.services.async.ProjectServiceAsync +import com.braintrustdata.api.services.async.ProjectTagServiceAsync +import com.braintrustdata.api.services.async.PromptServiceAsync +import com.braintrustdata.api.services.async.RoleServiceAsync +import com.braintrustdata.api.services.async.SpanIframeServiceAsync +import com.braintrustdata.api.services.async.TopLevelServiceAsync +import com.braintrustdata.api.services.async.UserServiceAsync +import com.braintrustdata.api.services.async.ViewServiceAsync +import java.util.function.Consumer +/** + * A client for interacting with the Braintrust REST API asynchronously. You can also switch to + * synchronous execution via the [sync] method. + * + * This client performs best when you create a single instance and reuse it for all interactions + * with the REST API. This is because each client holds its own connection pool and thread pools. + * Reusing connections and threads reduces latency and saves memory. The client also handles rate + * limiting per client. This means that creating and using multiple instances at the same time will + * not respect rate limits. + * + * The threads and connections that are held will be released automatically if they remain idle. But + * if you are writing an application that needs to aggressively release unused resources, then you + * may call [close]. + */ interface BraintrustClientAsync { + /** + * Returns a version of this client that uses synchronous execution. + * + * The returned client shares its resources, like its connection pool and thread pools, with + * this client. + */ fun sync(): BraintrustClient + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): BraintrustClientAsync + fun topLevel(): TopLevelServiceAsync - fun project(): ProjectServiceAsync + fun projects(): ProjectServiceAsync + + fun experiments(): ExperimentServiceAsync + + fun datasets(): DatasetServiceAsync + + fun prompts(): PromptServiceAsync + + fun roles(): RoleServiceAsync + + fun groups(): GroupServiceAsync + + fun acls(): AclServiceAsync + + fun users(): UserServiceAsync + + fun projectScores(): ProjectScoreServiceAsync + + fun projectTags(): ProjectTagServiceAsync + + fun spanIframes(): SpanIframeServiceAsync + + fun functions(): FunctionServiceAsync + + fun views(): ViewServiceAsync + + fun organizations(): OrganizationServiceAsync + + fun apiKeys(): ApiKeyServiceAsync + + fun aiSecrets(): AiSecretServiceAsync + + fun envVars(): EnvVarServiceAsync + + fun evals(): EvalServiceAsync + + /** + * Closes this client, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because the client is long-lived and + * usually should not be synchronously closed via try-with-resources. + * + * It's also usually not necessary to call this method at all. the default HTTP client + * automatically releases threads and connections if they remain idle, but if you are writing an + * application that needs to aggressively release unused resources, then you may call this + * method. + */ + fun close() + + /** + * A view of [BraintrustClientAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): BraintrustClientAsync.WithRawResponse + + fun topLevel(): TopLevelServiceAsync.WithRawResponse + + fun projects(): ProjectServiceAsync.WithRawResponse + + fun experiments(): ExperimentServiceAsync.WithRawResponse + + fun datasets(): DatasetServiceAsync.WithRawResponse + + fun prompts(): PromptServiceAsync.WithRawResponse + + fun roles(): RoleServiceAsync.WithRawResponse + + fun groups(): GroupServiceAsync.WithRawResponse + + fun acls(): AclServiceAsync.WithRawResponse + + fun users(): UserServiceAsync.WithRawResponse + + fun projectScores(): ProjectScoreServiceAsync.WithRawResponse + + fun projectTags(): ProjectTagServiceAsync.WithRawResponse + + fun spanIframes(): SpanIframeServiceAsync.WithRawResponse + + fun functions(): FunctionServiceAsync.WithRawResponse + + fun views(): ViewServiceAsync.WithRawResponse + + fun organizations(): OrganizationServiceAsync.WithRawResponse + + fun apiKeys(): ApiKeyServiceAsync.WithRawResponse + + fun aiSecrets(): AiSecretServiceAsync.WithRawResponse - fun experiment(): ExperimentServiceAsync + fun envVars(): EnvVarServiceAsync.WithRawResponse - fun dataset(): DatasetServiceAsync + fun evals(): EvalServiceAsync.WithRawResponse + } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt old mode 100644 new mode 100755 index d2d9f655..2d94732b --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientAsyncImpl.kt @@ -3,38 +3,299 @@ package com.braintrustdata.api.client import com.braintrustdata.api.core.ClientOptions -import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError -import com.braintrustdata.api.models.* -import com.braintrustdata.api.services.async.* -import com.braintrustdata.api.services.errorHandler +import com.braintrustdata.api.core.getPackageVersion +import com.braintrustdata.api.services.async.AclServiceAsync +import com.braintrustdata.api.services.async.AclServiceAsyncImpl +import com.braintrustdata.api.services.async.AiSecretServiceAsync +import com.braintrustdata.api.services.async.AiSecretServiceAsyncImpl +import com.braintrustdata.api.services.async.ApiKeyServiceAsync +import com.braintrustdata.api.services.async.ApiKeyServiceAsyncImpl +import com.braintrustdata.api.services.async.DatasetServiceAsync +import com.braintrustdata.api.services.async.DatasetServiceAsyncImpl +import com.braintrustdata.api.services.async.EnvVarServiceAsync +import com.braintrustdata.api.services.async.EnvVarServiceAsyncImpl +import com.braintrustdata.api.services.async.EvalServiceAsync +import com.braintrustdata.api.services.async.EvalServiceAsyncImpl +import com.braintrustdata.api.services.async.ExperimentServiceAsync +import com.braintrustdata.api.services.async.ExperimentServiceAsyncImpl +import com.braintrustdata.api.services.async.FunctionServiceAsync +import com.braintrustdata.api.services.async.FunctionServiceAsyncImpl +import com.braintrustdata.api.services.async.GroupServiceAsync +import com.braintrustdata.api.services.async.GroupServiceAsyncImpl +import com.braintrustdata.api.services.async.OrganizationServiceAsync +import com.braintrustdata.api.services.async.OrganizationServiceAsyncImpl +import com.braintrustdata.api.services.async.ProjectScoreServiceAsync +import com.braintrustdata.api.services.async.ProjectScoreServiceAsyncImpl +import com.braintrustdata.api.services.async.ProjectServiceAsync +import com.braintrustdata.api.services.async.ProjectServiceAsyncImpl +import com.braintrustdata.api.services.async.ProjectTagServiceAsync +import com.braintrustdata.api.services.async.ProjectTagServiceAsyncImpl +import com.braintrustdata.api.services.async.PromptServiceAsync +import com.braintrustdata.api.services.async.PromptServiceAsyncImpl +import com.braintrustdata.api.services.async.RoleServiceAsync +import com.braintrustdata.api.services.async.RoleServiceAsyncImpl +import com.braintrustdata.api.services.async.SpanIframeServiceAsync +import com.braintrustdata.api.services.async.SpanIframeServiceAsyncImpl +import com.braintrustdata.api.services.async.TopLevelServiceAsync +import com.braintrustdata.api.services.async.TopLevelServiceAsyncImpl +import com.braintrustdata.api.services.async.UserServiceAsync +import com.braintrustdata.api.services.async.UserServiceAsyncImpl +import com.braintrustdata.api.services.async.ViewServiceAsync +import com.braintrustdata.api.services.async.ViewServiceAsyncImpl +import java.util.function.Consumer -class BraintrustClientAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : BraintrustClientAsync { +class BraintrustClientAsyncImpl(private val clientOptions: ClientOptions) : BraintrustClientAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val clientOptionsWithUserAgent = + if (clientOptions.headers.names().contains("User-Agent")) clientOptions + else + clientOptions + .toBuilder() + .putHeader("User-Agent", "${javaClass.simpleName}/Java ${getPackageVersion()}") + .build() + // Pass the original clientOptions so that this client sets its own User-Agent. private val sync: BraintrustClient by lazy { BraintrustClientImpl(clientOptions) } - private val topLevel: TopLevelServiceAsync by lazy { TopLevelServiceAsyncImpl(clientOptions) } + private val withRawResponse: BraintrustClientAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val topLevel: TopLevelServiceAsync by lazy { + TopLevelServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val projects: ProjectServiceAsync by lazy { + ProjectServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val experiments: ExperimentServiceAsync by lazy { + ExperimentServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val datasets: DatasetServiceAsync by lazy { + DatasetServiceAsyncImpl(clientOptionsWithUserAgent) + } - private val project: ProjectServiceAsync by lazy { ProjectServiceAsyncImpl(clientOptions) } + private val prompts: PromptServiceAsync by lazy { + PromptServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val roles: RoleServiceAsync by lazy { RoleServiceAsyncImpl(clientOptionsWithUserAgent) } - private val experiment: ExperimentServiceAsync by lazy { - ExperimentServiceAsyncImpl(clientOptions) + private val groups: GroupServiceAsync by lazy { + GroupServiceAsyncImpl(clientOptionsWithUserAgent) } - private val dataset: DatasetServiceAsync by lazy { DatasetServiceAsyncImpl(clientOptions) } + private val acls: AclServiceAsync by lazy { AclServiceAsyncImpl(clientOptionsWithUserAgent) } + + private val users: UserServiceAsync by lazy { UserServiceAsyncImpl(clientOptionsWithUserAgent) } + + private val projectScores: ProjectScoreServiceAsync by lazy { + ProjectScoreServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val projectTags: ProjectTagServiceAsync by lazy { + ProjectTagServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val spanIframes: SpanIframeServiceAsync by lazy { + SpanIframeServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val functions: FunctionServiceAsync by lazy { + FunctionServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val views: ViewServiceAsync by lazy { ViewServiceAsyncImpl(clientOptionsWithUserAgent) } + + private val organizations: OrganizationServiceAsync by lazy { + OrganizationServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val apiKeys: ApiKeyServiceAsync by lazy { + ApiKeyServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val aiSecrets: AiSecretServiceAsync by lazy { + AiSecretServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val envVars: EnvVarServiceAsync by lazy { + EnvVarServiceAsyncImpl(clientOptionsWithUserAgent) + } + + private val evals: EvalServiceAsync by lazy { EvalServiceAsyncImpl(clientOptionsWithUserAgent) } override fun sync(): BraintrustClient = sync + override fun withRawResponse(): BraintrustClientAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): BraintrustClientAsync = + BraintrustClientAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun topLevel(): TopLevelServiceAsync = topLevel - override fun project(): ProjectServiceAsync = project + override fun projects(): ProjectServiceAsync = projects + + override fun experiments(): ExperimentServiceAsync = experiments + + override fun datasets(): DatasetServiceAsync = datasets + + override fun prompts(): PromptServiceAsync = prompts + + override fun roles(): RoleServiceAsync = roles + + override fun groups(): GroupServiceAsync = groups + + override fun acls(): AclServiceAsync = acls + + override fun users(): UserServiceAsync = users + + override fun projectScores(): ProjectScoreServiceAsync = projectScores + + override fun projectTags(): ProjectTagServiceAsync = projectTags + + override fun spanIframes(): SpanIframeServiceAsync = spanIframes + + override fun functions(): FunctionServiceAsync = functions + + override fun views(): ViewServiceAsync = views + + override fun organizations(): OrganizationServiceAsync = organizations - override fun experiment(): ExperimentServiceAsync = experiment + override fun apiKeys(): ApiKeyServiceAsync = apiKeys - override fun dataset(): DatasetServiceAsync = dataset + override fun aiSecrets(): AiSecretServiceAsync = aiSecrets + + override fun envVars(): EnvVarServiceAsync = envVars + + override fun evals(): EvalServiceAsync = evals + + override fun close() = clientOptions.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BraintrustClientAsync.WithRawResponse { + + private val topLevel: TopLevelServiceAsync.WithRawResponse by lazy { + TopLevelServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val projects: ProjectServiceAsync.WithRawResponse by lazy { + ProjectServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val experiments: ExperimentServiceAsync.WithRawResponse by lazy { + ExperimentServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val datasets: DatasetServiceAsync.WithRawResponse by lazy { + DatasetServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val prompts: PromptServiceAsync.WithRawResponse by lazy { + PromptServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val roles: RoleServiceAsync.WithRawResponse by lazy { + RoleServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val groups: GroupServiceAsync.WithRawResponse by lazy { + GroupServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val acls: AclServiceAsync.WithRawResponse by lazy { + AclServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val users: UserServiceAsync.WithRawResponse by lazy { + UserServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val projectScores: ProjectScoreServiceAsync.WithRawResponse by lazy { + ProjectScoreServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val projectTags: ProjectTagServiceAsync.WithRawResponse by lazy { + ProjectTagServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val spanIframes: SpanIframeServiceAsync.WithRawResponse by lazy { + SpanIframeServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val functions: FunctionServiceAsync.WithRawResponse by lazy { + FunctionServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val views: ViewServiceAsync.WithRawResponse by lazy { + ViewServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val organizations: OrganizationServiceAsync.WithRawResponse by lazy { + OrganizationServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val apiKeys: ApiKeyServiceAsync.WithRawResponse by lazy { + ApiKeyServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val aiSecrets: AiSecretServiceAsync.WithRawResponse by lazy { + AiSecretServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val envVars: EnvVarServiceAsync.WithRawResponse by lazy { + EnvVarServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + private val evals: EvalServiceAsync.WithRawResponse by lazy { + EvalServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): BraintrustClientAsync.WithRawResponse = + BraintrustClientAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun topLevel(): TopLevelServiceAsync.WithRawResponse = topLevel + + override fun projects(): ProjectServiceAsync.WithRawResponse = projects + + override fun experiments(): ExperimentServiceAsync.WithRawResponse = experiments + + override fun datasets(): DatasetServiceAsync.WithRawResponse = datasets + + override fun prompts(): PromptServiceAsync.WithRawResponse = prompts + + override fun roles(): RoleServiceAsync.WithRawResponse = roles + + override fun groups(): GroupServiceAsync.WithRawResponse = groups + + override fun acls(): AclServiceAsync.WithRawResponse = acls + + override fun users(): UserServiceAsync.WithRawResponse = users + + override fun projectScores(): ProjectScoreServiceAsync.WithRawResponse = projectScores + + override fun projectTags(): ProjectTagServiceAsync.WithRawResponse = projectTags + + override fun spanIframes(): SpanIframeServiceAsync.WithRawResponse = spanIframes + + override fun functions(): FunctionServiceAsync.WithRawResponse = functions + + override fun views(): ViewServiceAsync.WithRawResponse = views + + override fun organizations(): OrganizationServiceAsync.WithRawResponse = organizations + + override fun apiKeys(): ApiKeyServiceAsync.WithRawResponse = apiKeys + + override fun aiSecrets(): AiSecretServiceAsync.WithRawResponse = aiSecrets + + override fun envVars(): EnvVarServiceAsync.WithRawResponse = envVars + + override fun evals(): EvalServiceAsync.WithRawResponse = evals + } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt old mode 100644 new mode 100755 index aa93668c..c205ae48 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/client/BraintrustClientImpl.kt @@ -3,36 +3,287 @@ package com.braintrustdata.api.client import com.braintrustdata.api.core.ClientOptions -import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError -import com.braintrustdata.api.models.* -import com.braintrustdata.api.services.blocking.* -import com.braintrustdata.api.services.errorHandler +import com.braintrustdata.api.core.getPackageVersion +import com.braintrustdata.api.services.blocking.AclService +import com.braintrustdata.api.services.blocking.AclServiceImpl +import com.braintrustdata.api.services.blocking.AiSecretService +import com.braintrustdata.api.services.blocking.AiSecretServiceImpl +import com.braintrustdata.api.services.blocking.ApiKeyService +import com.braintrustdata.api.services.blocking.ApiKeyServiceImpl +import com.braintrustdata.api.services.blocking.DatasetService +import com.braintrustdata.api.services.blocking.DatasetServiceImpl +import com.braintrustdata.api.services.blocking.EnvVarService +import com.braintrustdata.api.services.blocking.EnvVarServiceImpl +import com.braintrustdata.api.services.blocking.EvalService +import com.braintrustdata.api.services.blocking.EvalServiceImpl +import com.braintrustdata.api.services.blocking.ExperimentService +import com.braintrustdata.api.services.blocking.ExperimentServiceImpl +import com.braintrustdata.api.services.blocking.FunctionService +import com.braintrustdata.api.services.blocking.FunctionServiceImpl +import com.braintrustdata.api.services.blocking.GroupService +import com.braintrustdata.api.services.blocking.GroupServiceImpl +import com.braintrustdata.api.services.blocking.OrganizationService +import com.braintrustdata.api.services.blocking.OrganizationServiceImpl +import com.braintrustdata.api.services.blocking.ProjectScoreService +import com.braintrustdata.api.services.blocking.ProjectScoreServiceImpl +import com.braintrustdata.api.services.blocking.ProjectService +import com.braintrustdata.api.services.blocking.ProjectServiceImpl +import com.braintrustdata.api.services.blocking.ProjectTagService +import com.braintrustdata.api.services.blocking.ProjectTagServiceImpl +import com.braintrustdata.api.services.blocking.PromptService +import com.braintrustdata.api.services.blocking.PromptServiceImpl +import com.braintrustdata.api.services.blocking.RoleService +import com.braintrustdata.api.services.blocking.RoleServiceImpl +import com.braintrustdata.api.services.blocking.SpanIframeService +import com.braintrustdata.api.services.blocking.SpanIframeServiceImpl +import com.braintrustdata.api.services.blocking.TopLevelService +import com.braintrustdata.api.services.blocking.TopLevelServiceImpl +import com.braintrustdata.api.services.blocking.UserService +import com.braintrustdata.api.services.blocking.UserServiceImpl +import com.braintrustdata.api.services.blocking.ViewService +import com.braintrustdata.api.services.blocking.ViewServiceImpl +import java.util.function.Consumer -class BraintrustClientImpl -constructor( - private val clientOptions: ClientOptions, -) : BraintrustClient { +class BraintrustClientImpl(private val clientOptions: ClientOptions) : BraintrustClient { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val clientOptionsWithUserAgent = + if (clientOptions.headers.names().contains("User-Agent")) clientOptions + else + clientOptions + .toBuilder() + .putHeader("User-Agent", "${javaClass.simpleName}/Java ${getPackageVersion()}") + .build() + // Pass the original clientOptions so that this client sets its own User-Agent. private val async: BraintrustClientAsync by lazy { BraintrustClientAsyncImpl(clientOptions) } - private val topLevel: TopLevelService by lazy { TopLevelServiceImpl(clientOptions) } + private val withRawResponse: BraintrustClient.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } - private val project: ProjectService by lazy { ProjectServiceImpl(clientOptions) } + private val topLevel: TopLevelService by lazy { + TopLevelServiceImpl(clientOptionsWithUserAgent) + } - private val experiment: ExperimentService by lazy { ExperimentServiceImpl(clientOptions) } + private val projects: ProjectService by lazy { ProjectServiceImpl(clientOptionsWithUserAgent) } - private val dataset: DatasetService by lazy { DatasetServiceImpl(clientOptions) } + private val experiments: ExperimentService by lazy { + ExperimentServiceImpl(clientOptionsWithUserAgent) + } + + private val datasets: DatasetService by lazy { DatasetServiceImpl(clientOptionsWithUserAgent) } + + private val prompts: PromptService by lazy { PromptServiceImpl(clientOptionsWithUserAgent) } + + private val roles: RoleService by lazy { RoleServiceImpl(clientOptionsWithUserAgent) } + + private val groups: GroupService by lazy { GroupServiceImpl(clientOptionsWithUserAgent) } + + private val acls: AclService by lazy { AclServiceImpl(clientOptionsWithUserAgent) } + + private val users: UserService by lazy { UserServiceImpl(clientOptionsWithUserAgent) } + + private val projectScores: ProjectScoreService by lazy { + ProjectScoreServiceImpl(clientOptionsWithUserAgent) + } + + private val projectTags: ProjectTagService by lazy { + ProjectTagServiceImpl(clientOptionsWithUserAgent) + } + + private val spanIframes: SpanIframeService by lazy { + SpanIframeServiceImpl(clientOptionsWithUserAgent) + } + + private val functions: FunctionService by lazy { + FunctionServiceImpl(clientOptionsWithUserAgent) + } + + private val views: ViewService by lazy { ViewServiceImpl(clientOptionsWithUserAgent) } + + private val organizations: OrganizationService by lazy { + OrganizationServiceImpl(clientOptionsWithUserAgent) + } + + private val apiKeys: ApiKeyService by lazy { ApiKeyServiceImpl(clientOptionsWithUserAgent) } + + private val aiSecrets: AiSecretService by lazy { + AiSecretServiceImpl(clientOptionsWithUserAgent) + } + + private val envVars: EnvVarService by lazy { EnvVarServiceImpl(clientOptionsWithUserAgent) } + + private val evals: EvalService by lazy { EvalServiceImpl(clientOptionsWithUserAgent) } override fun async(): BraintrustClientAsync = async + override fun withRawResponse(): BraintrustClient.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): BraintrustClient = + BraintrustClientImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun topLevel(): TopLevelService = topLevel - override fun project(): ProjectService = project + override fun projects(): ProjectService = projects + + override fun experiments(): ExperimentService = experiments + + override fun datasets(): DatasetService = datasets + + override fun prompts(): PromptService = prompts + + override fun roles(): RoleService = roles + + override fun groups(): GroupService = groups + + override fun acls(): AclService = acls + + override fun users(): UserService = users + + override fun projectScores(): ProjectScoreService = projectScores + + override fun projectTags(): ProjectTagService = projectTags + + override fun spanIframes(): SpanIframeService = spanIframes + + override fun functions(): FunctionService = functions + + override fun views(): ViewService = views + + override fun organizations(): OrganizationService = organizations + + override fun apiKeys(): ApiKeyService = apiKeys + + override fun aiSecrets(): AiSecretService = aiSecrets + + override fun envVars(): EnvVarService = envVars + + override fun evals(): EvalService = evals + + override fun close() = clientOptions.close() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + BraintrustClient.WithRawResponse { + + private val topLevel: TopLevelService.WithRawResponse by lazy { + TopLevelServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val projects: ProjectService.WithRawResponse by lazy { + ProjectServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val experiments: ExperimentService.WithRawResponse by lazy { + ExperimentServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val datasets: DatasetService.WithRawResponse by lazy { + DatasetServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val prompts: PromptService.WithRawResponse by lazy { + PromptServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val roles: RoleService.WithRawResponse by lazy { + RoleServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val groups: GroupService.WithRawResponse by lazy { + GroupServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val acls: AclService.WithRawResponse by lazy { + AclServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val users: UserService.WithRawResponse by lazy { + UserServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val projectScores: ProjectScoreService.WithRawResponse by lazy { + ProjectScoreServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val projectTags: ProjectTagService.WithRawResponse by lazy { + ProjectTagServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val spanIframes: SpanIframeService.WithRawResponse by lazy { + SpanIframeServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val functions: FunctionService.WithRawResponse by lazy { + FunctionServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val views: ViewService.WithRawResponse by lazy { + ViewServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val organizations: OrganizationService.WithRawResponse by lazy { + OrganizationServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val apiKeys: ApiKeyService.WithRawResponse by lazy { + ApiKeyServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val aiSecrets: AiSecretService.WithRawResponse by lazy { + AiSecretServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val envVars: EnvVarService.WithRawResponse by lazy { + EnvVarServiceImpl.WithRawResponseImpl(clientOptions) + } + + private val evals: EvalService.WithRawResponse by lazy { + EvalServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): BraintrustClient.WithRawResponse = + BraintrustClientImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun topLevel(): TopLevelService.WithRawResponse = topLevel + + override fun projects(): ProjectService.WithRawResponse = projects + + override fun experiments(): ExperimentService.WithRawResponse = experiments + + override fun datasets(): DatasetService.WithRawResponse = datasets + + override fun prompts(): PromptService.WithRawResponse = prompts + + override fun roles(): RoleService.WithRawResponse = roles + + override fun groups(): GroupService.WithRawResponse = groups + + override fun acls(): AclService.WithRawResponse = acls + + override fun users(): UserService.WithRawResponse = users + + override fun projectScores(): ProjectScoreService.WithRawResponse = projectScores + + override fun projectTags(): ProjectTagService.WithRawResponse = projectTags + + override fun spanIframes(): SpanIframeService.WithRawResponse = spanIframes + + override fun functions(): FunctionService.WithRawResponse = functions + + override fun views(): ViewService.WithRawResponse = views + + override fun organizations(): OrganizationService.WithRawResponse = organizations + + override fun apiKeys(): ApiKeyService.WithRawResponse = apiKeys + + override fun aiSecrets(): AiSecretService.WithRawResponse = aiSecrets - override fun experiment(): ExperimentService = experiment + override fun envVars(): EnvVarService.WithRawResponse = envVars - override fun dataset(): DatasetService = dataset + override fun evals(): EvalService.WithRawResponse = evals + } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/AutoPager.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/AutoPager.kt new file mode 100644 index 00000000..d208a9f8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/AutoPager.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class AutoPager private constructor(private val firstPage: Page) : Iterable { + + companion object { + + fun from(firstPage: Page): AutoPager = AutoPager(firstPage) + } + + override fun iterator(): Iterator = + generateSequence(firstPage) { if (it.hasNextPage()) it.nextPage() else null } + .flatMap { it.items() } + .iterator() + + fun stream(): Stream = StreamSupport.stream(spliterator(), false) +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/AutoPagerAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/AutoPagerAsync.kt new file mode 100644 index 00000000..7ff270b1 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/AutoPagerAsync.kt @@ -0,0 +1,88 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +import com.braintrustdata.api.core.http.AsyncStreamResponse +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionException +import java.util.concurrent.Executor +import java.util.concurrent.atomic.AtomicReference + +class AutoPagerAsync +private constructor(private val firstPage: PageAsync, private val defaultExecutor: Executor) : + AsyncStreamResponse { + + companion object { + + fun from(firstPage: PageAsync, defaultExecutor: Executor): AutoPagerAsync = + AutoPagerAsync(firstPage, defaultExecutor) + } + + private val onCompleteFuture = CompletableFuture() + private val state = AtomicReference(State.NEW) + + override fun subscribe(handler: AsyncStreamResponse.Handler): AsyncStreamResponse = + subscribe(handler, defaultExecutor) + + override fun subscribe( + handler: AsyncStreamResponse.Handler, + executor: Executor, + ): AsyncStreamResponse = apply { + // TODO(JDK): Use `compareAndExchange` once targeting JDK 9. + check(state.compareAndSet(State.NEW, State.SUBSCRIBED)) { + if (state.get() == State.SUBSCRIBED) "Cannot subscribe more than once" + else "Cannot subscribe after the response is closed" + } + + fun PageAsync.handle(): CompletableFuture { + if (state.get() == State.CLOSED) { + return CompletableFuture.completedFuture(null) + } + + items().forEach { handler.onNext(it) } + return if (hasNextPage()) nextPage().thenCompose { it.handle() } + else CompletableFuture.completedFuture(null) + } + + executor.execute { + firstPage.handle().whenComplete { _, error -> + val actualError = + if (error is CompletionException && error.cause != null) error.cause else error + try { + handler.onComplete(Optional.ofNullable(actualError)) + } finally { + try { + if (actualError == null) { + onCompleteFuture.complete(null) + } else { + onCompleteFuture.completeExceptionally(actualError) + } + } finally { + close() + } + } + } + } + } + + override fun onCompleteFuture(): CompletableFuture = onCompleteFuture + + override fun close() { + val previousState = state.getAndSet(State.CLOSED) + if (previousState == State.CLOSED) { + return + } + + // When the stream is closed, we should always consider it closed. If it closed due + // to an error, then we will have already completed the future earlier, and this + // will be a no-op. + onCompleteFuture.complete(null) + } +} + +private enum class State { + NEW, + SUBSCRIBED, + CLOSED, +} diff --git a/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 old mode 100644 new mode 100755 index a38e39bd..3ebb507f --- 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 @@ -18,7 +17,7 @@ abstract class BaseDeserializer(type: KClass) : override fun createContextual( context: DeserializationContext, - property: BeanProperty? + property: BeanProperty?, ): JsonDeserializer { return this } @@ -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/BaseSerializer.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/BaseSerializer.kt old mode 100644 new mode 100755 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 new file mode 100644 index 00000000..254bc88e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Check.kt @@ -0,0 +1,96 @@ +@file:JvmName("Check") + +package com.braintrustdata.api.core + +import com.fasterxml.jackson.core.Version +import com.fasterxml.jackson.core.util.VersionUtil + +fun checkRequired(name: String, condition: Boolean) = + check(condition) { "`$name` is required, but was not set" } + +fun checkRequired(name: String, value: T?): T = + checkNotNull(value) { "`$name` is required, but was not set" } + +@JvmSynthetic +internal fun checkKnown(name: String, value: JsonField): T = + value.asKnown().orElseThrow { + IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") + } + +@JvmSynthetic +internal fun checkKnown(name: String, value: MultipartField): T = + value.value.asKnown().orElseThrow { + IllegalStateException("`$name` is not a known type: ${value.javaClass.simpleName}") + } + +@JvmSynthetic +internal fun checkLength(name: String, value: String, length: Int): String = + value.also { + check(it.length == length) { "`$name` must have length $length, but was ${it.length}" } + } + +@JvmSynthetic +internal fun checkMinLength(name: String, value: String, minLength: Int): String = + value.also { + check(it.length >= minLength) { + if (minLength == 1) "`$name` must be non-empty, but was empty" + else "`$name` must have at least length $minLength, but was ${it.length}" + } + } + +@JvmSynthetic +internal fun checkMaxLength(name: String, value: String, maxLength: Int): String = + value.also { + check(it.length <= maxLength) { + "`$name` must have at most length $maxLength, but was ${it.length}" + } + } + +@JvmSynthetic +internal fun checkJacksonVersionCompatibility() { + val incompatibleJacksonVersions = + RUNTIME_JACKSON_VERSIONS.mapNotNull { + val badVersionReason = BAD_JACKSON_VERSIONS[it.toString()] + when { + it.majorVersion != MINIMUM_JACKSON_VERSION.majorVersion -> + it to "incompatible major version" + it.minorVersion < MINIMUM_JACKSON_VERSION.minorVersion -> + it to "minor version too low" + it.minorVersion == MINIMUM_JACKSON_VERSION.minorVersion && + it.patchLevel < MINIMUM_JACKSON_VERSION.patchLevel -> + it to "patch version too low" + badVersionReason != null -> it to badVersionReason + else -> null + } + } + check(incompatibleJacksonVersions.isEmpty()) { + """ +This SDK requires a minimum Jackson version of $MINIMUM_JACKSON_VERSION, but the following incompatible Jackson versions were detected at runtime: + +${incompatibleJacksonVersions.asSequence().map { (version, incompatibilityReason) -> + "- `${version.toFullString().replace("/", ":")}` ($incompatibilityReason)" +}.joinToString("\n")} + +This can happen if you are either: +1. Directly depending on different Jackson versions +2. Depending on some library that depends on different Jackson versions, potentially transitively + +Double-check that you are depending on compatible Jackson versions. + +See https://www.github.com/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 old mode 100644 new mode 100755 index 3327c070..e77958a6 --- 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 @@ -2,110 +2,500 @@ package com.braintrustdata.api.core +import com.braintrustdata.api.core.http.AsyncStreamResponse +import com.braintrustdata.api.core.http.Headers import com.braintrustdata.api.core.http.HttpClient +import com.braintrustdata.api.core.http.PhantomReachableClosingHttpClient +import com.braintrustdata.api.core.http.QueryParams import com.braintrustdata.api.core.http.RetryingHttpClient import com.fasterxml.jackson.databind.json.JsonMapper -import com.google.common.collect.ArrayListMultimap -import com.google.common.collect.ListMultimap import java.time.Clock +import java.time.Duration +import java.util.Optional +import java.util.concurrent.Executor +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.ThreadFactory +import java.util.concurrent.atomic.AtomicLong +import kotlin.jvm.optionals.getOrNull +/** A class representing the SDK client configuration. */ class ClientOptions private constructor( + private val originalHttpClient: HttpClient, + /** + * The HTTP client to use in the SDK. + * + * Use the one published in `braintrust-java-client-okhttp` or implement your own. + * + * This class takes ownership of the client and closes it when closed. + */ @get:JvmName("httpClient") val httpClient: HttpClient, + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee that + * the SDK will work correctly when using an incompatible Jackson version. + */ + @get:JvmName("checkJacksonVersionCompatibility") val checkJacksonVersionCompatibility: Boolean, + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.braintrustdata.api.core.jsonMapper]. The default is usually sufficient and + * rarely needs to be overridden. + */ @get:JvmName("jsonMapper") val jsonMapper: JsonMapper, + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + @get:JvmName("streamHandlerExecutor") val streamHandlerExecutor: Executor, + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + @get:JvmName("sleeper") val sleeper: Sleeper, + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ @get:JvmName("clock") val clock: Clock, - @get:JvmName("baseUrl") val baseUrl: String, - @get:JvmName("apiKey") val apiKey: String, - @get:JvmName("headers") val headers: ListMultimap, + private val baseUrl: String?, + /** Headers to send with the request. */ + @get:JvmName("headers") val headers: Headers, + /** Query params to send with the request. */ + @get:JvmName("queryParams") val queryParams: QueryParams, + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ @get:JvmName("responseValidation") val responseValidation: Boolean, + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + @get:JvmName("timeout") val timeout: Timeout, + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + @get:JvmName("maxRetries") val maxRetries: Int, + private val apiKey: String?, ) { + init { + if (checkJacksonVersionCompatibility) { + checkJacksonVersionCompatibility() + } + } + + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.braintrust.dev`. + */ + fun baseUrl(): String = baseUrl ?: PRODUCTION_URL + + fun apiKey(): Optional = Optional.ofNullable(apiKey) + + fun toBuilder() = Builder().from(this) + companion object { - const val PRODUCTION_URL = "https://api.braintrustdata.com" + const val PRODUCTION_URL = "https://api.braintrust.dev" + /** + * Returns a mutable builder for constructing an instance of [ClientOptions]. + * + * The following fields are required: + * ```java + * .httpClient() + * ``` + */ @JvmStatic fun builder() = Builder() + /** + * Returns options configured using system properties and environment variables. + * + * @see Builder.fromEnv + */ @JvmStatic fun fromEnv(): ClientOptions = builder().fromEnv().build() } - class Builder { + /** A builder for [ClientOptions]. */ + class Builder internal constructor() { private var httpClient: HttpClient? = null - private var jsonMapper: JsonMapper? = null + private var checkJacksonVersionCompatibility: Boolean = true + private var jsonMapper: JsonMapper = jsonMapper() + private var streamHandlerExecutor: Executor? = null + private var sleeper: Sleeper? = null private var clock: Clock = Clock.systemUTC() - private var baseUrl: String = PRODUCTION_URL - private var headers: MutableMap> = mutableMapOf() + private var baseUrl: String? = null + private var headers: Headers.Builder = Headers.builder() + private var queryParams: QueryParams.Builder = QueryParams.builder() private var responseValidation: Boolean = false + private var timeout: Timeout = Timeout.default() private var maxRetries: Int = 2 private var apiKey: String? = null - fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + @JvmSynthetic + internal fun from(clientOptions: ClientOptions) = apply { + httpClient = clientOptions.originalHttpClient + checkJacksonVersionCompatibility = clientOptions.checkJacksonVersionCompatibility + jsonMapper = clientOptions.jsonMapper + streamHandlerExecutor = clientOptions.streamHandlerExecutor + sleeper = clientOptions.sleeper + clock = clientOptions.clock + baseUrl = clientOptions.baseUrl + headers = clientOptions.headers.toBuilder() + queryParams = clientOptions.queryParams.toBuilder() + responseValidation = clientOptions.responseValidation + timeout = clientOptions.timeout + maxRetries = clientOptions.maxRetries + apiKey = clientOptions.apiKey + } + + /** + * The HTTP client to use in the SDK. + * + * Use the one published in `braintrust-java-client-okhttp` or implement your own. + * + * This class takes ownership of the client and closes it when closed. + */ + fun httpClient(httpClient: HttpClient) = apply { + this.httpClient = PhantomReachableClosingHttpClient(httpClient) + } + + /** + * Whether to throw an exception if any of the Jackson versions detected at runtime are + * incompatible with the SDK's minimum supported Jackson version (2.13.4). + * + * Defaults to true. Use extreme caution when disabling this option. There is no guarantee + * that the SDK will work correctly when using an incompatible Jackson version. + */ + fun checkJacksonVersionCompatibility(checkJacksonVersionCompatibility: Boolean) = apply { + this.checkJacksonVersionCompatibility = checkJacksonVersionCompatibility + } + /** + * The Jackson JSON mapper to use for serializing and deserializing JSON. + * + * Defaults to [com.braintrustdata.api.core.jsonMapper]. The default is usually sufficient + * and rarely needs to be overridden. + */ fun jsonMapper(jsonMapper: JsonMapper) = apply { this.jsonMapper = jsonMapper } - fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } + /** + * The executor to use for running [AsyncStreamResponse.Handler] callbacks. + * + * Defaults to a dedicated cached thread pool. + * + * This class takes ownership of the executor and shuts it down, if possible, when closed. + */ + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = + if (streamHandlerExecutor is ExecutorService) + PhantomReachableExecutorService(streamHandlerExecutor) + else streamHandlerExecutor + } + + /** + * The interface to use for delaying execution, like during retries. + * + * This is primarily useful for using fake delays in tests. + * + * Defaults to real execution delays. + * + * This class takes ownership of the sleeper and closes it when closed. + */ + fun sleeper(sleeper: Sleeper) = apply { this.sleeper = PhantomReachableSleeper(sleeper) } + /** + * The clock to use for operations that require timing, like retries. + * + * This is primarily useful for using a fake clock in tests. + * + * Defaults to [Clock.systemUTC]. + */ fun clock(clock: Clock) = apply { this.clock = clock } + /** + * The base URL to use for every request. + * + * Defaults to the production environment: `https://api.braintrust.dev`. + */ + fun baseUrl(baseUrl: String?) = apply { this.baseUrl = baseUrl } + + /** Alias for calling [Builder.baseUrl] with `baseUrl.orElse(null)`. */ + fun baseUrl(baseUrl: Optional) = baseUrl(baseUrl.getOrNull()) + + /** + * Whether to call `validate` on every response before returning it. + * + * Defaults to false, which means the shape of the response will not be validated upfront. + * Instead, validation will only occur for the parts of the response that are accessed. + */ + fun responseValidation(responseValidation: Boolean) = apply { + this.responseValidation = responseValidation + } + + /** + * Sets the maximum time allowed for various parts of an HTTP call's lifecycle, excluding + * retries. + * + * Defaults to [Timeout.default]. + */ + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } + + /** + * Sets the maximum time allowed for a complete HTTP call, not including retries. + * + * See [Timeout.request] for more details. + * + * For fine-grained control, pass a [Timeout] object. + */ + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + /** + * The maximum number of times to retry failed requests, with a short exponential backoff + * between requests. + * + * Only the following error types are retried: + * - Connection errors (for example, due to a network connectivity problem) + * - 408 Request Timeout + * - 409 Conflict + * - 429 Rate Limit + * - 5xx Internal + * + * The API may also explicitly instruct the SDK to retry or not retry a request. + * + * Defaults to 2. + */ + fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } + + fun apiKey(apiKey: String?) = apply { this.apiKey = apiKey } + + /** Alias for calling [Builder.apiKey] with `apiKey.orElse(null)`. */ + fun apiKey(apiKey: Optional) = apiKey(apiKey.getOrNull()) + + fun headers(headers: Headers) = apply { + this.headers.clear() + putAllHeaders(headers) + } + fun headers(headers: Map>) = apply { this.headers.clear() putAllHeaders(headers) } - fun putHeader(name: String, value: String) = apply { - this.headers.getOrPut(name) { mutableListOf() }.add(value) + fun putHeader(name: String, value: String) = apply { headers.put(name, value) } + + fun putHeaders(name: String, values: Iterable) = apply { headers.put(name, values) } + + fun putAllHeaders(headers: Headers) = apply { this.headers.putAll(headers) } + + fun putAllHeaders(headers: Map>) = apply { + this.headers.putAll(headers) + } + + fun replaceHeaders(name: String, value: String) = apply { headers.replace(name, value) } + + fun replaceHeaders(name: String, values: Iterable) = apply { + headers.replace(name, values) } - fun putHeaders(name: String, values: Iterable) = apply { - this.headers.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAllHeaders(headers: Headers) = apply { this.headers.replaceAll(headers) } + + fun replaceAllHeaders(headers: Map>) = apply { + this.headers.replaceAll(headers) } - fun putAllHeaders(headers: Map>) = apply { - headers.forEach(this::putHeaders) + fun removeHeaders(name: String) = apply { headers.remove(name) } + + fun removeAllHeaders(names: Set) = apply { headers.removeAll(names) } + + fun queryParams(queryParams: QueryParams) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) } - fun removeHeader(name: String) = apply { this.headers.put(name, mutableListOf()) } + fun queryParams(queryParams: Map>) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) + } - fun responseValidation(responseValidation: Boolean) = apply { - this.responseValidation = responseValidation + fun putQueryParam(key: String, value: String) = apply { queryParams.put(key, value) } + + fun putQueryParams(key: String, values: Iterable) = apply { + queryParams.put(key, values) } - fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } + fun putAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.putAll(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + this.queryParams.putAll(queryParams) + } - fun apiKey(apiKey: String) = apply { this.apiKey = apiKey } + fun replaceQueryParams(key: String, value: String) = apply { + queryParams.replace(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + queryParams.replace(key, values) + } + + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun removeQueryParams(key: String) = apply { queryParams.remove(key) } - fun fromEnv() = apply { System.getenv("BRAINTRUST_API_KEY")?.let { apiKey(it) } } + fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } + fun timeout(): Timeout = timeout + + /** + * Updates configuration using system properties and environment variables. + * + * See this table for the available options: + * + * |Setter |System property |Environment variable |Required|Default value | + * |---------|--------------------|---------------------|--------|------------------------------| + * |`apiKey` |`braintrust.apiKey` |`BRAINTRUST_API_KEY` |false |- | + * |`baseUrl`|`braintrust.baseUrl`|`BRAINTRUST_BASE_URL`|true |`"https://api.braintrust.dev"`| + * + * System properties take precedence over environment variables. + */ + fun fromEnv() = apply { + (System.getProperty("braintrust.baseUrl") ?: System.getenv("BRAINTRUST_BASE_URL")) + ?.let { baseUrl(it) } + (System.getProperty("braintrust.apiKey") ?: System.getenv("BRAINTRUST_API_KEY"))?.let { + apiKey(it) + } + } + + /** + * Returns an immutable instance of [ClientOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .httpClient() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): ClientOptions { - checkNotNull(httpClient) { "`httpClient` is required but was not set" } - checkNotNull(apiKey) { "`apiKey` is required but was not set" } + val httpClient = checkRequired("httpClient", httpClient) + val streamHandlerExecutor = + streamHandlerExecutor + ?: PhantomReachableExecutorService( + Executors.newCachedThreadPool( + object : ThreadFactory { - val headers = ArrayListMultimap.create() + private val threadFactory: ThreadFactory = + Executors.defaultThreadFactory() + private val count = AtomicLong(0) + + override fun newThread(runnable: Runnable): Thread = + threadFactory.newThread(runnable).also { + it.name = + "braintrust-stream-handler-thread-${count.getAndIncrement()}" + } + } + ) + ) + val sleeper = sleeper ?: PhantomReachableSleeper(DefaultSleeper()) + + val headers = Headers.builder() + val queryParams = QueryParams.builder() headers.put("X-Stainless-Lang", "java") headers.put("X-Stainless-Arch", getOsArch()) headers.put("X-Stainless-OS", getOsName()) headers.put("X-Stainless-OS-Version", getOsVersion()) headers.put("X-Stainless-Package-Version", getPackageVersion()) + headers.put("X-Stainless-Runtime", "JRE") headers.put("X-Stainless-Runtime-Version", getJavaVersion()) - if (!apiKey.isNullOrEmpty()) { - headers.put("Authorization", "Bearer ${apiKey}") + apiKey?.let { + if (!it.isEmpty()) { + headers.put("Authorization", "Bearer $it") + } } - this.headers.forEach(headers::replaceValues) + headers.replaceAll(this.headers.build()) + queryParams.replaceAll(this.queryParams.build()) return ClientOptions( + httpClient, RetryingHttpClient.builder() - .httpClient(httpClient!!) + .httpClient(httpClient) + .sleeper(sleeper) .clock(clock) .maxRetries(maxRetries) .build(), - jsonMapper ?: jsonMapper(), + checkJacksonVersionCompatibility, + jsonMapper, + streamHandlerExecutor, + sleeper, clock, baseUrl, - apiKey!!, - headers.toUnmodifiable(), + headers.build(), + queryParams.build(), responseValidation, + timeout, + maxRetries, + apiKey, ) } } + + /** + * Closes these client options, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because the client options are + * long-lived and usually should not be synchronously closed via try-with-resources. + * + * It's also usually not necessary to call this method at all. the default client automatically + * releases threads and connections if they remain idle, but if you are writing an application + * that needs to aggressively release unused resources, then you may call this method. + */ + fun close() { + httpClient.close() + (streamHandlerExecutor as? ExecutorService)?.shutdown() + sleeper.close() + } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/DefaultSleeper.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/DefaultSleeper.kt new file mode 100644 index 00000000..32ece057 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/DefaultSleeper.kt @@ -0,0 +1,28 @@ +package com.braintrustdata.api.core + +import java.time.Duration +import java.util.Timer +import java.util.TimerTask +import java.util.concurrent.CompletableFuture + +class DefaultSleeper : Sleeper { + + private val timer = Timer("DefaultSleeper", true) + + override fun sleep(duration: Duration) = Thread.sleep(duration.toMillis()) + + override fun sleepAsync(duration: Duration): CompletableFuture { + val future = CompletableFuture() + timer.schedule( + object : TimerTask() { + override fun run() { + future.complete(null) + } + }, + duration.toMillis(), + ) + return future + } + + override fun close() = timer.cancel() +} diff --git a/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 old mode 100644 new mode 100755 index 5b1f8ea1..c3287a6b --- 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 @@ -3,23 +3,165 @@ package com.braintrustdata.api.core import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.JsonParseException +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.MapperFeature import com.fasterxml.jackson.databind.SerializationFeature -import com.fasterxml.jackson.databind.cfg.CoercionAction.Fail -import com.fasterxml.jackson.databind.cfg.CoercionInputShape.Integer +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.cfg.CoercionAction +import com.fasterxml.jackson.databind.cfg.CoercionInputShape +import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.databind.type.LogicalType import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule -import com.fasterxml.jackson.module.kotlin.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(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() + +/** A serializer that serializes [InputStream] to bytes. */ +private object InputStreamSerializer : BaseSerializer(InputStream::class) { + + private fun readResolve(): Any = InputStreamSerializer + + override fun serialize( + value: InputStream?, + gen: JsonGenerator?, + serializers: SerializerProvider?, + ) { + if (value == null) { + gen?.writeNull() + } else { + value.use { gen?.writeBinary(it.readBytes()) } + } + } +} + +/** + * A deserializer that can deserialize [LocalDateTime] from datetimes, dates, and zoned datetimes. + */ +private class LenientLocalDateTimeDeserializer : + StdDeserializer(LocalDateTime::class.java) { + + companion object { + + private val DATE_TIME_FORMATTERS = + listOf( + DateTimeFormatter.ISO_LOCAL_DATE_TIME, + DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ISO_ZONED_DATE_TIME, + ) + } + + override fun logicalType(): LogicalType = LogicalType.DateTime + + override fun deserialize(p: JsonParser, context: DeserializationContext?): LocalDateTime { + val exceptions = mutableListOf() + + for (formatter in DATE_TIME_FORMATTERS) { + try { + val temporal = formatter.parse(p.text) + + return when { + !temporal.isSupported(ChronoField.HOUR_OF_DAY) -> + LocalDate.from(temporal).atStartOfDay() + !temporal.isSupported(ChronoField.OFFSET_SECONDS) -> + LocalDateTime.from(temporal) + else -> ZonedDateTime.from(temporal).toLocalDateTime() + } + } catch (e: DateTimeException) { + exceptions.add(e) + } + } + + 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/Page.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Page.kt new file mode 100644 index 00000000..5d5afd20 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Page.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +/** + * An interface representing a single page, with items of type [T], from a paginated endpoint + * response. + * + * Implementations of this interface are expected to request additional pages synchronously. For + * asynchronous pagination, see the [PageAsync] interface. + */ +interface Page { + + /** + * Returns whether there's another page after this one. + * + * The method generally doesn't make requests so the result depends entirely on the data in this + * page. If a significant amount of time has passed between requesting this page and calling + * this method, then the result could be stale. + */ + fun hasNextPage(): Boolean + + /** + * Returns the page after this one by making another request. + * + * @throws IllegalStateException if it's impossible to get the next page. This exception is + * avoidable by calling [hasNextPage] first. + */ + fun nextPage(): Page + + /** Returns the items in this page. */ + fun items(): List +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PageAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PageAsync.kt new file mode 100644 index 00000000..10b3b47a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PageAsync.kt @@ -0,0 +1,35 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +import java.util.concurrent.CompletableFuture + +/** + * An interface representing a single page, with items of type [T], from a paginated endpoint + * response. + * + * Implementations of this interface are expected to request additional pages asynchronously. For + * synchronous pagination, see the [Page] interface. + */ +interface PageAsync { + + /** + * Returns whether there's another page after this one. + * + * The method generally doesn't make requests so the result depends entirely on the data in this + * page. If a significant amount of time has passed between requesting this page and calling + * this method, then the result could be stale. + */ + fun hasNextPage(): Boolean + + /** + * Returns the page after this one by making another request. + * + * @throws IllegalStateException if it's impossible to get the next page. This exception is + * avoidable by calling [hasNextPage] first. + */ + fun nextPage(): CompletableFuture> + + /** Returns the items in this page. */ + fun items(): List +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Params.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Params.kt new file mode 100644 index 00000000..f98bf142 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Params.kt @@ -0,0 +1,16 @@ +package com.braintrustdata.api.core + +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams + +/** An interface representing parameters passed to a service method. */ +interface Params { + /** The full set of headers in the parameters, including both fixed and additional headers. */ + fun _headers(): Headers + + /** + * The full set of query params in the parameters, including both fixed and additional query + * params. + */ + fun _queryParams(): QueryParams +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachable.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachable.kt new file mode 100644 index 00000000..91785b1a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachable.kt @@ -0,0 +1,56 @@ +@file:JvmName("PhantomReachable") + +package com.braintrustdata.api.core + +import com.braintrustdata.api.errors.BraintrustException +import java.lang.reflect.InvocationTargetException + +/** + * Closes [closeable] when [observed] becomes only phantom reachable. + * + * This is a wrapper around a Java 9+ [java.lang.ref.Cleaner], or a no-op in older Java versions. + */ +@JvmSynthetic +internal fun closeWhenPhantomReachable(observed: Any, closeable: AutoCloseable) { + check(observed !== closeable) { + "`observed` cannot be the same object as `closeable` because it would never become phantom reachable" + } + closeWhenPhantomReachable(observed, closeable::close) +} + +/** + * Calls [close] when [observed] becomes only phantom reachable. + * + * This is a wrapper around a Java 9+ [java.lang.ref.Cleaner], or a no-op in older Java versions. + */ +@JvmSynthetic +internal fun closeWhenPhantomReachable(observed: Any, close: () -> Unit) { + closeWhenPhantomReachable?.let { it(observed, close) } +} + +private val closeWhenPhantomReachable: ((Any, () -> Unit) -> Unit)? by lazy { + try { + val cleanerClass = Class.forName("java.lang.ref.Cleaner") + val cleanerCreate = cleanerClass.getMethod("create") + val cleanerRegister = + cleanerClass.getMethod("register", Any::class.java, Runnable::class.java) + val cleanerObject = cleanerCreate.invoke(null); + + { observed, close -> + try { + cleanerRegister.invoke(cleanerObject, observed, Runnable { close() }) + } catch (e: ReflectiveOperationException) { + if (e is InvocationTargetException) { + when (val cause = e.cause) { + is RuntimeException, + is Error -> throw cause + } + } + throw BraintrustException("Unexpected reflective invocation failure", e) + } + } + } catch (e: ReflectiveOperationException) { + // We're running Java 8, which has no Cleaner. + null + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachableExecutorService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachableExecutorService.kt new file mode 100644 index 00000000..0538d523 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachableExecutorService.kt @@ -0,0 +1,58 @@ +package com.braintrustdata.api.core + +import java.util.concurrent.Callable +import java.util.concurrent.ExecutorService +import java.util.concurrent.Future +import java.util.concurrent.TimeUnit + +/** + * A delegating wrapper around an [ExecutorService] that shuts it down once it's only phantom + * reachable. + * + * This class ensures the [ExecutorService] is shut down even if the user forgets to do it. + */ +internal class PhantomReachableExecutorService(private val executorService: ExecutorService) : + ExecutorService { + init { + closeWhenPhantomReachable(this) { executorService.shutdown() } + } + + override fun execute(command: Runnable) = executorService.execute(command) + + override fun shutdown() = executorService.shutdown() + + override fun shutdownNow(): MutableList = executorService.shutdownNow() + + override fun isShutdown(): Boolean = executorService.isShutdown + + override fun isTerminated(): Boolean = executorService.isTerminated + + override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = + executorService.awaitTermination(timeout, unit) + + override fun submit(task: Callable): Future = executorService.submit(task) + + override fun submit(task: Runnable, result: T): Future = + executorService.submit(task, result) + + override fun submit(task: Runnable): Future<*> = executorService.submit(task) + + override fun invokeAll( + tasks: MutableCollection> + ): MutableList> = executorService.invokeAll(tasks) + + override fun invokeAll( + tasks: MutableCollection>, + timeout: Long, + unit: TimeUnit, + ): MutableList> = executorService.invokeAll(tasks, timeout, unit) + + override fun invokeAny(tasks: MutableCollection>): T = + executorService.invokeAny(tasks) + + override fun invokeAny( + tasks: MutableCollection>, + timeout: Long, + unit: TimeUnit, + ): T = executorService.invokeAny(tasks, timeout, unit) +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachableSleeper.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachableSleeper.kt new file mode 100644 index 00000000..8c293f53 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PhantomReachableSleeper.kt @@ -0,0 +1,23 @@ +package com.braintrustdata.api.core + +import java.time.Duration +import java.util.concurrent.CompletableFuture + +/** + * A delegating wrapper around a [Sleeper] that closes it once it's only phantom reachable. + * + * This class ensures the [Sleeper] is closed even if the user forgets to do it. + */ +internal class PhantomReachableSleeper(private val sleeper: Sleeper) : Sleeper { + + init { + closeWhenPhantomReachable(this, sleeper) + } + + override fun sleep(duration: Duration) = sleeper.sleep(duration) + + override fun sleepAsync(duration: Duration): CompletableFuture = + sleeper.sleepAsync(duration) + + override fun close() = sleeper.close() +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PrepareRequest.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PrepareRequest.kt new file mode 100644 index 00000000..e9aaadff --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/PrepareRequest.kt @@ -0,0 +1,24 @@ +@file:JvmName("PrepareRequest") + +package com.braintrustdata.api.core + +import com.braintrustdata.api.core.http.HttpRequest +import java.util.concurrent.CompletableFuture + +@JvmSynthetic +internal fun HttpRequest.prepare(clientOptions: ClientOptions, params: Params): HttpRequest = + toBuilder() + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params._queryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params._headers()) + .build() + +@JvmSynthetic +internal fun HttpRequest.prepareAsync( + clientOptions: ClientOptions, + params: Params, +): CompletableFuture = + // This async version exists to make it easier to add async specific preparation logic in the + // future. + CompletableFuture.completedFuture(prepare(clientOptions, params)) diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Properties.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Properties.kt old mode 100644 new mode 100755 index 1c59eee1..5130de1b --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Properties.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Properties.kt @@ -2,7 +2,7 @@ package com.braintrustdata.api.core -import java.util.Properties +import com.braintrustdata.api.client.BraintrustClient fun getOsArch(): String { val osArch = System.getProperty("os.arch") @@ -16,7 +16,7 @@ fun getOsArch(): String { "x86_64" -> "x64" "arm" -> "arm" "aarch64" -> "arm64" - else -> "other:${osArch}" + else -> "other:$osArch" } } @@ -30,18 +30,13 @@ fun getOsName(): String { osName.startsWith("Linux") -> "Linux" osName.startsWith("Mac OS") -> "MacOS" osName.startsWith("Windows") -> "Windows" - else -> "Other:${osName}" + else -> "Other:$osName" } } -fun getOsVersion(): String { - return System.getProperty("os.version", "unknown") -} +fun getOsVersion(): String = System.getProperty("os.version", "unknown") -fun getPackageVersion(): String { - return Properties::class.java.`package`.implementationVersion ?: "unknown" -} +fun getPackageVersion(): String = + BraintrustClient::class.java.`package`.implementationVersion ?: "unknown" -fun getJavaVersion(): String { - return System.getProperty("java.version", "unknown") -} +fun getJavaVersion(): String = System.getProperty("java.version", "unknown") diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/RequestOptions.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/RequestOptions.kt old mode 100644 new mode 100755 index 7a8c8b26..fe7c8372 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/RequestOptions.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/RequestOptions.kt @@ -2,17 +2,7 @@ package com.braintrustdata.api.core import java.time.Duration -class RequestOptions -private constructor( - val responseValidation: Boolean?, - val timeout: Duration?, -) { - fun applyDefaults(options: RequestOptions): RequestOptions { - return RequestOptions( - responseValidation = this.responseValidation ?: options.responseValidation, - timeout = this.timeout ?: options.timeout, - ) - } +class RequestOptions private constructor(val responseValidation: Boolean?, val timeout: Timeout?) { companion object { @@ -20,21 +10,37 @@ private constructor( @JvmStatic fun none() = NONE + @JvmSynthetic + internal fun from(clientOptions: ClientOptions): RequestOptions = + builder() + .responseValidation(clientOptions.responseValidation) + .timeout(clientOptions.timeout) + .build() + @JvmStatic fun builder() = Builder() } - class Builder { + fun applyDefaults(options: RequestOptions): RequestOptions = + RequestOptions( + responseValidation = responseValidation ?: options.responseValidation, + timeout = + if (options.timeout != null && timeout != null) timeout.assign(options.timeout) + else timeout ?: options.timeout, + ) + + class Builder internal constructor() { + private var responseValidation: Boolean? = null - private var timeout: Duration? = null + private var timeout: Timeout? = null fun responseValidation(responseValidation: Boolean) = apply { this.responseValidation = responseValidation } - fun timeout(timeout: Duration) = apply { this.timeout = timeout } + fun timeout(timeout: Timeout) = apply { this.timeout = timeout } - fun build(): RequestOptions { - return RequestOptions(responseValidation, timeout) - } + fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build()) + + fun build(): RequestOptions = RequestOptions(responseValidation, timeout) } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Sleeper.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Sleeper.kt new file mode 100644 index 00000000..856b4009 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Sleeper.kt @@ -0,0 +1,21 @@ +package com.braintrustdata.api.core + +import java.time.Duration +import java.util.concurrent.CompletableFuture + +/** + * An interface for delaying execution for a specified amount of time. + * + * Useful for testing and cleaning up resources. + */ +interface Sleeper : AutoCloseable { + + /** Synchronously pauses execution for the given [duration]. */ + fun sleep(duration: Duration) + + /** Asynchronously pauses execution for the given [duration]. */ + fun sleepAsync(duration: Duration): CompletableFuture + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Timeout.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Timeout.kt new file mode 100644 index 00000000..b2320ac8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/Timeout.kt @@ -0,0 +1,171 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +import java.time.Duration +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** A class containing timeouts for various processing phases of a request. */ +class Timeout +private constructor( + private val connect: Duration?, + private val read: Duration?, + private val write: Duration?, + private val request: Duration?, +) { + + /** + * The maximum time allowed to establish a connection with a host. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun connect(): Duration = connect ?: Duration.ofMinutes(1) + + /** + * The maximum time allowed between two data packets when waiting for the server’s response. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun read(): Duration = read ?: request() + + /** + * The maximum time allowed between two data packets when sending the request to the server. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun write(): Duration = write ?: request() + + /** + * The maximum time allowed for a complete HTTP call, not including retries. + * + * This includes resolving DNS, connecting, writing the request body, server processing, as well + * as reading the response body. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun request(): Duration = request ?: Duration.ofMinutes(1) + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun default() = builder().build() + + /** Returns a mutable builder for constructing an instance of [Timeout]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Timeout]. */ + class Builder internal constructor() { + + private var connect: Duration? = null + private var read: Duration? = null + private var write: Duration? = null + private var request: Duration? = null + + @JvmSynthetic + internal fun from(timeout: Timeout) = apply { + connect = timeout.connect + read = timeout.read + write = timeout.write + request = timeout.request + } + + /** + * The maximum time allowed to establish a connection with a host. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun connect(connect: Duration?) = apply { this.connect = connect } + + /** Alias for calling [Builder.connect] with `connect.orElse(null)`. */ + fun connect(connect: Optional) = connect(connect.getOrNull()) + + /** + * The maximum time allowed between two data packets when waiting for the server’s response. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun read(read: Duration?) = apply { this.read = read } + + /** Alias for calling [Builder.read] with `read.orElse(null)`. */ + fun read(read: Optional) = read(read.getOrNull()) + + /** + * The maximum time allowed between two data packets when sending the request to the server. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `request()`. + */ + fun write(write: Duration?) = apply { this.write = write } + + /** Alias for calling [Builder.write] with `write.orElse(null)`. */ + fun write(write: Optional) = write(write.getOrNull()) + + /** + * The maximum time allowed for a complete HTTP call, not including retries. + * + * This includes resolving DNS, connecting, writing the request body, server processing, as + * well as reading the response body. + * + * A value of [Duration.ZERO] means there's no timeout. + * + * Defaults to `Duration.ofMinutes(1)`. + */ + fun request(request: Duration?) = apply { this.request = request } + + /** Alias for calling [Builder.request] with `request.orElse(null)`. */ + fun request(request: Optional) = request(request.getOrNull()) + + /** + * Returns an immutable instance of [Timeout]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Timeout = Timeout(connect, read, write, request) + } + + @JvmSynthetic + internal fun assign(target: Timeout): Timeout = + target + .toBuilder() + .apply { + connect?.let(this::connect) + read?.let(this::read) + write?.let(this::write) + request?.let(this::request) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Timeout && + connect == other.connect && + read == other.read && + write == other.write && + request == other.request + } + + override fun hashCode(): Int = Objects.hash(connect, read, write, request) + + override fun toString() = + "Timeout{connect=$connect, read=$read, write=$write, request=$request}" +} diff --git a/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 old mode 100644 new mode 100755 index 46bee377..a1657ff3 --- 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 @@ -3,57 +3,113 @@ package com.braintrustdata.api.core import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.google.common.collect.ImmutableListMultimap -import com.google.common.collect.ListMultimap -import com.google.common.collect.Multimaps import java.util.Collections +import java.util.SortedMap +import java.util.concurrent.CompletableFuture +import java.util.concurrent.locks.Lock @JvmSynthetic -internal fun T?.getOrThrow(name: String): T { - if (this == null) { - throw BraintrustInvalidDataException("'${name}' is not present") - } +internal fun T?.getOrThrow(name: String): T = + this ?: throw BraintrustInvalidDataException("`${name}` is not present") - return this -} +@JvmSynthetic +internal fun List.toImmutable(): List = + if (isEmpty()) Collections.emptyList() else Collections.unmodifiableList(toList()) @JvmSynthetic -internal fun List.toUnmodifiable(): List { - if (isEmpty()) { - return Collections.emptyList() - } +internal fun Map.toImmutable(): Map = + if (isEmpty()) immutableEmptyMap() else Collections.unmodifiableMap(toMap()) - return Collections.unmodifiableList(this) -} +@JvmSynthetic internal fun immutableEmptyMap(): Map = Collections.emptyMap() + +@JvmSynthetic +internal fun , V> SortedMap.toImmutable(): SortedMap = + if (isEmpty()) Collections.emptySortedMap() + else Collections.unmodifiableSortedMap(toSortedMap(comparator())) +/** + * Returns all elements that yield the largest value for the given function, or an empty list if + * there are zero elements. + * + * This is similar to [Sequence.maxByOrNull] except it returns _all_ elements that yield the largest + * value; not just the first one. + */ @JvmSynthetic -internal fun Map.toUnmodifiable(): Map { - if (isEmpty()) { - return Collections.emptyMap() +internal fun > Sequence.allMaxBy(selector: (T) -> R): List { + var maxValue: R? = null + val maxElements = mutableListOf() + + val iterator = iterator() + while (iterator.hasNext()) { + val element = iterator.next() + val value = selector(element) + if (maxValue == null || value > maxValue) { + maxValue = value + maxElements.clear() + maxElements.add(element) + } else if (value == maxValue) { + maxElements.add(element) + } } - return Collections.unmodifiableMap(this) + return maxElements } +/** + * Returns whether [this] is equal to [other]. + * + * This differs from [Object.equals] because it also deeply equates arrays based on their contents, + * even when there are arrays directly nested within other arrays. + */ @JvmSynthetic -internal fun ListMultimap.toUnmodifiable(): ListMultimap { - if (isEmpty()) { - return ImmutableListMultimap.of() - } +internal infix fun Any?.contentEquals(other: Any?): Boolean = + arrayOf(this).contentDeepEquals(arrayOf(other)) - return Multimaps.unmodifiableListMultimap(this) -} +/** + * Returns a hash of the given sequence of [values]. + * + * This differs from [java.util.Objects.hash] because it also deeply hashes arrays based on their + * contents, even when there are arrays directly nested within other arrays. + */ +@JvmSynthetic internal fun contentHash(vararg values: Any?): Int = values.contentDeepHashCode() +/** + * Returns a [String] representation of [this]. + * + * This differs from [Object.toString] because it also deeply stringifies arrays based on their + * contents, even when there are arrays directly nested within other arrays. + */ @JvmSynthetic -internal fun ListMultimap.getRequiredHeader(header: String): String { - val value = - entries() - .stream() - .filter { entry -> entry.key.equals(header, ignoreCase = true) } - .map { entry -> entry.value } - .findFirst() - if (!value.isPresent) { - throw BraintrustInvalidDataException("Could not find $header header") +internal fun Any?.contentToString(): String { + var string = arrayOf(this).contentDeepToString() + if (string.startsWith('[')) { + string = string.substring(1) } - return value.get() + if (string.endsWith(']')) { + string = string.substring(0, string.length - 1) + } + return string +} + +internal interface Enum + +/** + * Executes the given [action] while holding the lock, returning a [CompletableFuture] with the + * result. + * + * @param action The asynchronous action to execute while holding the lock + * @return A [CompletableFuture] that completes with the result of the action + */ +@JvmSynthetic +internal fun Lock.withLockAsync(action: () -> CompletableFuture): CompletableFuture { + lock() + val future = + try { + action() + } catch (e: Throwable) { + unlock() + throw e + } + future.whenComplete { _, _ -> unlock() } + return future } diff --git a/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 old mode 100644 new mode 100755 index 8628cbb4..7f71390d --- 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 @@ -27,65 +25,145 @@ import com.fasterxml.jackson.databind.node.JsonNodeType.OBJECT import com.fasterxml.jackson.databind.node.JsonNodeType.POJO import com.fasterxml.jackson.databind.node.JsonNodeType.STRING import com.fasterxml.jackson.databind.ser.std.NullSerializer +import 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) + is KnownValue -> Optional.ofNullable(value as? Boolean) else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's numerical value, or an empty [Optional] if it + * doesn't contain a number. + * + * This method checks for both a [KnownValue] containing a number and for [JsonNumber]. + */ fun asNumber(): Optional = when (this) { is JsonNumber -> Optional.of(value) + is KnownValue -> Optional.ofNullable(value as? Number) else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's string value, or an empty [Optional] if it + * doesn't contain a string. + * + * This method checks for both a [KnownValue] containing a string and for [JsonString]. + */ fun asString(): Optional = when (this) { is JsonString -> Optional.of(value) + is KnownValue -> Optional.ofNullable(value as? String) else -> Optional.empty() } fun asStringOrThrow(): String = - when (this) { - is JsonString -> value - else -> throw BraintrustInvalidDataException("Value is not a 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) + is KnownValue -> + Optional.ofNullable( + (value as? List<*>)?.map { + try { + JsonValue.from(it) + } catch (e: IllegalArgumentException) { + // The known value is a list, but not all values are convertible to + // `JsonValue`. + return Optional.empty() + } + } + ) else -> Optional.empty() } + /** + * Returns an [Optional] containing this field's map value, or an empty [Optional] if it doesn't + * contain a map. + * + * This method checks for both a [KnownValue] containing a map and for [JsonObject]. + */ fun asObject(): Optional> = when (this) { is JsonObject -> Optional.of(values) + is KnownValue -> + Optional.ofNullable( + (value as? Map<*, *>) + ?.map { (key, value) -> + if (key !is String) { + return Optional.empty() + } + + val jsonValue = + try { + JsonValue.from(value) + } catch (e: IllegalArgumentException) { + // The known value is a map, but not all items are convertible + // to `JsonValue`. + return Optional.empty() + } + + key to jsonValue + } + ?.toMap() + ) else -> Optional.empty() } @@ -93,18 +171,24 @@ sealed class JsonField { internal fun getRequired(name: String): T = when (this) { is KnownValue -> value - is JsonMissing -> throw BraintrustInvalidDataException("'${name}' is not set") - is JsonNull -> throw BraintrustInvalidDataException("'${name}' is null") - else -> throw BraintrustInvalidDataException("'${name}' is invalid, received ${this}") + is JsonMissing -> throw BraintrustInvalidDataException("`$name` is not set") + is JsonNull -> throw BraintrustInvalidDataException("`$name` is null") + else -> throw BraintrustInvalidDataException("`$name` is invalid, received $this") } @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 - else -> throw BraintrustInvalidDataException("'${name}' is invalid, received ${this}") + is KnownValue -> Optional.of(value) + is JsonMissing, + is JsonNull -> Optional.empty() + else -> throw BraintrustInvalidDataException("`$name` is invalid, received $this") } @JvmSynthetic @@ -114,19 +198,33 @@ sealed class JsonField { is JsonValue -> this } + @JvmSynthetic internal fun accept(consume: (T) -> Unit) = asKnown().ifPresent(consume) + + /** Returns the result of calling the [visitor] method corresponding to this field's state. */ fun accept(visitor: Visitor): R = when (this) { is KnownValue -> visitor.visitKnown(value) is JsonValue -> accept(visitor as JsonValue.Visitor) } + /** + * An interface that defines how to map each possible state of a `JsonField` to a value of + * type [R]. + */ interface Visitor : JsonValue.Visitor { + fun visitKnown(value: T): R = visitDefault() } companion object { + + /** Returns a [JsonField] containing the given "known" [value]. */ @JvmStatic fun of(value: T): JsonField = KnownValue.of(value) + /** + * Returns a [JsonField] containing the given "known" [value], or [JsonNull] if [value] is + * null. + */ @JvmStatic fun ofNullable(value: T?): JsonField = when (value) { @@ -135,10 +233,16 @@ sealed class JsonField { } } - // This class is a Jackson filter that can be used to exclude missing properties from objects - // This filter should not be used directly and should instead use the @ExcludeMissing annotation + /** + * This class is a Jackson filter that can be used to exclude missing properties from objects. + * This filter should not be used directly and should instead use the @ExcludeMissing + * annotation. + */ class IsMissing { + override fun equals(other: Any?): Boolean = other is JsonMissing + + override fun hashCode(): Int = Objects.hash() } class Deserializer(private val type: JavaType? = null) : @@ -147,21 +251,22 @@ sealed class JsonField { override fun createContextual( context: DeserializationContext, property: BeanProperty?, - ): JsonDeserializer> { - return Deserializer(context.contextualType?.containedType(0)) - } + ): JsonDeserializer> = Deserializer(context.contextualType?.containedType(0)) - override fun ObjectCodec.deserialize(node: JsonNode): JsonField<*> { - return type?.let { tryDeserialize(node, type) }?.let { of(it) } + override fun ObjectCodec.deserialize(node: JsonNode): JsonField<*> = + type?.let { tryDeserialize(node, type) }?.let { of(it) } ?: JsonValue.fromJsonNode(node) - } - override fun getNullValue(context: DeserializationContext): JsonField<*> { - return JsonNull.of() - } + override fun getNullValue(context: DeserializationContext): JsonField<*> = JsonNull.of() } } +/** + * A class representing an arbitrary JSON value. + * + * It is immutable and assignable to any [JsonField], regardless of its expected type (i.e. its + * generic type argument). + */ @JsonDeserialize(using = JsonValue.Deserializer::class) sealed class JsonValue : JsonField() { @@ -169,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() @@ -180,23 +286,72 @@ 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() + fun visitBoolean(value: Boolean): R = visitDefault() + fun visitNumber(value: Number): R = visitDefault() + fun visitString(value: String): R = visitDefault() + fun visitArray(values: List): R = visitDefault() + fun visitObject(values: Map): R = visitDefault() - 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) { @@ -205,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) { @@ -226,16 +386,19 @@ sealed class JsonValue : JsonField() { } class Deserializer : BaseDeserializer(JsonValue::class) { - override fun ObjectCodec.deserialize(node: JsonNode): JsonValue { - return fromJsonNode(node) - } - override fun getNullValue(context: DeserializationContext?): JsonValue { - return JsonNull.of() - } + 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 @@ -246,52 +409,67 @@ private constructor( return true } - return other is KnownValue<*> && value == other.value + return other is KnownValue<*> && value contentEquals other.value } - override fun hashCode() = value.hashCode() + override fun hashCode() = contentHash(value) - override fun toString() = value.toString() + 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 + 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 @@ -310,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 @@ -331,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 @@ -353,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 @@ -377,10 +565,13 @@ private constructor( override fun toString() = values.toString() companion object { - @JsonCreator @JvmStatic fun of(values: List) = JsonArray(values.toUnmodifiable()) + + /** 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 @@ -401,25 +592,132 @@ private constructor( override fun toString() = values.toString() companion object { + + /** Returns a [JsonObject] containing the given [values]. */ @JsonCreator @JvmStatic - fun of(values: Map) = JsonObject(values.toUnmodifiable()) + 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, -) +@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( + /** A [JsonField] value, which will be serialized to zero or more parts. */ + @get:com.fasterxml.jackson.annotation.JsonValue @get:JvmName("value") val value: JsonField, + /** A content type for the serialized parts. */ + @get:JvmName("contentType") val contentType: String, + private val filename: String?, +) { + + companion object { + + /** + * Returns a [MultipartField] containing the given [value] as a [KnownValue]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun of(value: T?) = builder().value(value).build() + + /** + * Returns a [MultipartField] containing the given [value]. + * + * [contentType] will be set to `application/octet-stream` if [value] is binary data, or + * `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun of(value: JsonField) = builder().value(value).build() + + /** + * Returns a mutable builder for constructing an instance of [MultipartField]. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + */ + @JvmStatic fun builder() = Builder() + } + + /** Returns the filename directive that will be included in the serialized field. */ + fun filename(): Optional = Optional.ofNullable(filename) + + @JvmSynthetic + internal fun map(transform: (T) -> R): MultipartField = + builder().value(value.map(transform)).contentType(contentType).filename(filename).build() + + /** A builder for [MultipartField]. */ + class Builder internal constructor() { + + private var value: JsonField? = null + private var contentType: String? = null + private var filename: String? = null + + fun value(value: JsonField) = apply { this.value = value } + + fun value(value: T?) = value(JsonField.ofNullable(value)) + + fun contentType(contentType: String) = apply { this.contentType = contentType } + + fun filename(filename: String?) = apply { this.filename = filename } + + /** Alias for calling [Builder.filename] with `filename.orElse(null)`. */ + fun filename(filename: Optional) = filename(filename.orElse(null)) + + /** + * Returns an immutable instance of [MultipartField]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .value() + * ``` + * + * If [contentType] is unset, then it will be set to `application/octet-stream` if [value] + * is binary data, or `text/plain; charset=utf-8` otherwise. + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MultipartField { + val value = checkRequired("value", value) + return MultipartField( + value, + contentType + ?: if ( + value is KnownValue && + (value.value is InputStream || value.value is ByteArray) + ) + "application/octet-stream" + else "text/plain; charset=utf-8", + filename, + ) + } + } + + private val hashCode: Int by lazy { contentHash(value, contentType, filename) } + + override fun hashCode(): Int = hashCode + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is MultipartField<*> && + value == other.value && + contentType == other.contentType && + filename == other.filename + } + + override fun toString(): String = + "MultipartField{value=$value, contentType=$contentType, filename=$filename}" +} diff --git a/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 new file mode 100644 index 00000000..67559b98 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/ErrorHandler.kt @@ -0,0 +1,84 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:JvmName("ErrorHandler") + +package com.braintrustdata.api.core.handlers + +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.InternalServerException +import com.braintrustdata.api.errors.NotFoundException +import com.braintrustdata.api.errors.PermissionDeniedException +import com.braintrustdata.api.errors.RateLimitException +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 + +@JvmSynthetic +internal fun errorBodyHandler(jsonMapper: JsonMapper): Handler { + val handler = jsonHandler(jsonMapper) + + return object : Handler { + override fun handle(response: HttpResponse): JsonValue = + try { + handler.handle(response) + } catch (e: Exception) { + JsonMissing.of() + } + } +} + +@JvmSynthetic +internal fun errorHandler(errorBodyHandler: Handler): Handler = + object : Handler { + override fun handle(response: HttpResponse): HttpResponse = + when (val statusCode = response.statusCode()) { + in 200..299 -> response + 400 -> + throw BadRequestException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 401 -> + throw UnauthorizedException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 403 -> + throw PermissionDeniedException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 404 -> + throw NotFoundException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 422 -> + throw UnprocessableEntityException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + 429 -> + throw RateLimitException.builder() + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + in 500..599 -> + throw InternalServerException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + else -> + throw UnexpectedStatusCodeException.builder() + .statusCode(statusCode) + .headers(response.headers()) + .body(errorBodyHandler.handle(response)) + .build() + } + } diff --git a/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 new file mode 100644 index 00000000..70259a46 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/JsonHandler.kt @@ -0,0 +1,20 @@ +@file:JvmName("JsonHandler") + +package com.braintrustdata.api.core.handlers + +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 + +@JvmSynthetic +internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler = + object : Handler { + override fun handle(response: HttpResponse): T = + try { + jsonMapper.readValue(response.body(), jacksonTypeRef()) + } catch (e: Exception) { + throw BraintrustInvalidDataException("Error reading response", e) + } + } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/StringHandler.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/StringHandler.kt new file mode 100644 index 00000000..bb04609d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/handlers/StringHandler.kt @@ -0,0 +1,13 @@ +@file:JvmName("StringHandler") + +package com.braintrustdata.api.core.handlers + +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler + +@JvmSynthetic internal fun stringHandler(): Handler = StringHandlerInternal + +private object StringHandlerInternal : Handler { + override fun handle(response: HttpResponse): String = + response.body().readBytes().toString(Charsets.UTF_8) +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/AsyncStreamResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/AsyncStreamResponse.kt new file mode 100644 index 00000000..93dff9ec --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/AsyncStreamResponse.kt @@ -0,0 +1,157 @@ +package com.braintrustdata.api.core.http + +import com.braintrustdata.api.core.http.AsyncStreamResponse.Handler +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.concurrent.atomic.AtomicReference + +/** + * A class providing access to an API response as an asynchronous stream of chunks of type [T], + * where each chunk can be individually processed as soon as it arrives instead of waiting on the + * full response. + */ +interface AsyncStreamResponse { + + /** + * Registers [handler] to be called for events of this stream. + * + * [handler]'s methods will be called in the client's configured or default thread pool. + * + * @throws IllegalStateException if [subscribe] has already been called. + */ + fun subscribe(handler: Handler): AsyncStreamResponse + + /** + * Registers [handler] to be called for events of this stream. + * + * [handler]'s methods will be called in the given [executor]. + * + * @throws IllegalStateException if [subscribe] has already been called. + */ + fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse + + /** + * Returns a future that completes when a stream is fully consumed, errors, or gets closed + * early. + */ + fun onCompleteFuture(): CompletableFuture + + /** + * Closes this resource, relinquishing any underlying resources. + * + * This is purposefully not inherited from [AutoCloseable] because this response should not be + * synchronously closed via try-with-resources. + */ + fun close() + + /** A class for handling streaming events. */ + fun interface Handler { + + /** Called whenever a chunk is received. */ + fun onNext(value: T) + + /** + * Called when a stream is fully consumed, errors, or gets closed early. + * + * [onNext] will not be called once this method is called. + * + * @param error Non-empty if the stream completed due to an error. + */ + fun onComplete(error: Optional) {} + } +} + +@JvmSynthetic +internal fun CompletableFuture>.toAsync(streamHandlerExecutor: Executor) = + PhantomReachableClosingAsyncStreamResponse( + object : AsyncStreamResponse { + + private val onCompleteFuture = CompletableFuture() + private val state = AtomicReference(State.NEW) + + init { + this@toAsync.whenComplete { _, error -> + // If an error occurs from the original future, then we should resolve the + // `onCompleteFuture` even if `subscribe` has not been called. + error?.let(onCompleteFuture::completeExceptionally) + } + } + + override fun subscribe(handler: Handler): AsyncStreamResponse = + subscribe(handler, streamHandlerExecutor) + + override fun subscribe( + handler: Handler, + executor: Executor, + ): AsyncStreamResponse = apply { + // TODO(JDK): Use `compareAndExchange` once targeting JDK 9. + check(state.compareAndSet(State.NEW, State.SUBSCRIBED)) { + if (state.get() == State.SUBSCRIBED) "Cannot subscribe more than once" + else "Cannot subscribe after the response is closed" + } + + this@toAsync.whenCompleteAsync( + { streamResponse, futureError -> + if (state.get() == State.CLOSED) { + // Avoid doing any work if `close` was called before the future + // completed. + return@whenCompleteAsync + } + + if (futureError != null) { + // An error occurred before we started passing chunks to the handler. + handler.onComplete(Optional.of(futureError)) + return@whenCompleteAsync + } + + var streamError: Throwable? = null + try { + streamResponse.stream().forEach(handler::onNext) + } catch (e: Throwable) { + streamError = e + } + + try { + handler.onComplete(Optional.ofNullable(streamError)) + } finally { + try { + // Notify completion via the `onCompleteFuture` as well. This is in + // a separate `try-finally` block so that we still complete the + // future if `handler.onComplete` throws. + if (streamError == null) { + onCompleteFuture.complete(null) + } else { + onCompleteFuture.completeExceptionally(streamError) + } + } finally { + close() + } + } + }, + executor, + ) + } + + override fun onCompleteFuture(): CompletableFuture = onCompleteFuture + + override fun close() { + val previousState = state.getAndSet(State.CLOSED) + if (previousState == State.CLOSED) { + return + } + + this@toAsync.whenComplete { streamResponse, error -> streamResponse?.close() } + // When the stream is closed, we should always consider it closed. If it closed due + // to an error, then we will have already completed the future earlier, and this + // will be a no-op. + onCompleteFuture.complete(null) + } + } + ) + +private enum class State { + NEW, + SUBSCRIBED, + CLOSED, +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/BinaryResponseContent.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/BinaryResponseContent.kt deleted file mode 100644 index afdb7ff5..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/BinaryResponseContent.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.braintrustdata.api.core.http - -import java.io.Closeable -import java.io.IOException -import java.io.InputStream -import java.io.OutputStream - -interface BinaryResponseContent : Closeable { - - fun contentType(): String? - - fun body(): InputStream - - @Throws(IOException::class) fun writeTo(outputStream: OutputStream) -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/Headers.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/Headers.kt new file mode 100644 index 00000000..774088ec --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/Headers.kt @@ -0,0 +1,115 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core.http + +import com.braintrustdata.api.core.JsonArray +import com.braintrustdata.api.core.JsonBoolean +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonNull +import com.braintrustdata.api.core.JsonNumber +import com.braintrustdata.api.core.JsonObject +import com.braintrustdata.api.core.JsonString +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.toImmutable +import java.util.TreeMap + +class Headers +private constructor( + private val map: Map>, + @get:JvmName("size") val size: Int, +) { + + fun isEmpty(): Boolean = map.isEmpty() + + fun names(): Set = map.keys + + fun values(name: String): List = map[name].orEmpty() + + fun toBuilder(): Builder = Builder().putAll(map) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder internal constructor() { + + private val map: MutableMap> = + TreeMap(String.CASE_INSENSITIVE_ORDER) + private var size: Int = 0 + + fun put(name: String, value: JsonValue): Builder = apply { + when (value) { + is JsonMissing, + is JsonNull -> {} + is JsonBoolean -> put(name, value.value.toString()) + is JsonNumber -> put(name, value.value.toString()) + is JsonString -> put(name, value.value) + is JsonArray -> value.values.forEach { put(name, it) } + is JsonObject -> + value.values.forEach { (nestedName, value) -> put("$name.$nestedName", value) } + } + } + + fun put(name: String, value: String) = apply { + map.getOrPut(name) { mutableListOf() }.add(value) + size++ + } + + fun put(name: String, values: Iterable) = apply { values.forEach { put(name, it) } } + + fun putAll(headers: Map>) = apply { headers.forEach(::put) } + + fun putAll(headers: Headers) = apply { + headers.names().forEach { put(it, headers.values(it)) } + } + + fun replace(name: String, value: String) = apply { + remove(name) + put(name, value) + } + + fun replace(name: String, values: Iterable) = apply { + remove(name) + put(name, values) + } + + fun replaceAll(headers: Map>) = apply { + headers.forEach(::replace) + } + + fun replaceAll(headers: Headers) = apply { + headers.names().forEach { replace(it, headers.values(it)) } + } + + fun remove(name: String) = apply { size -= map.remove(name).orEmpty().size } + + fun removeAll(names: Set) = apply { names.forEach(::remove) } + + fun clear() = apply { + map.clear() + size = 0 + } + + fun build() = + Headers( + map.mapValuesTo(TreeMap(String.CASE_INSENSITIVE_ORDER)) { (_, values) -> + values.toImmutable() + } + .toImmutable(), + size, + ) + } + + override fun hashCode(): Int = map.hashCode() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Headers && map == other.map + } + + override fun toString(): String = "Headers{map=$map}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpClient.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpClient.kt old mode 100644 new mode 100755 index 8cfaea6b..5941bacd --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpClient.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpClient.kt @@ -1,18 +1,26 @@ package com.braintrustdata.api.core.http import com.braintrustdata.api.core.RequestOptions -import java.io.Closeable +import java.lang.AutoCloseable import java.util.concurrent.CompletableFuture -interface HttpClient : Closeable { +interface HttpClient : AutoCloseable { fun execute( request: HttpRequest, requestOptions: RequestOptions = RequestOptions.none(), ): HttpResponse + fun execute(request: HttpRequest): HttpResponse = execute(request, RequestOptions.none()) + fun executeAsync( request: HttpRequest, requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + fun executeAsync(request: HttpRequest): CompletableFuture = + executeAsync(request, RequestOptions.none()) + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpMethod.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpMethod.kt old mode 100644 new mode 100755 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequest.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequest.kt old mode 100644 new mode 100755 index f4ba383e..f3c2522c --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequest.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequest.kt @@ -1,91 +1,145 @@ package com.braintrustdata.api.core.http -import com.braintrustdata.api.core.toUnmodifiable -import com.google.common.collect.ArrayListMultimap -import com.google.common.collect.ListMultimap -import com.google.common.collect.Multimap -import com.google.common.collect.MultimapBuilder +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.toImmutable class HttpRequest private constructor( @get:JvmName("method") val method: HttpMethod, - @get:JvmName("url") val url: String?, + @get:JvmName("baseUrl") val baseUrl: String, @get:JvmName("pathSegments") val pathSegments: List, - @get:JvmName("queryParams") val queryParams: ListMultimap, - @get:JvmName("headers") val headers: ListMultimap, + @get:JvmName("headers") val headers: Headers, + @get:JvmName("queryParams") val queryParams: QueryParams, @get:JvmName("body") val body: HttpRequestBody?, ) { + fun toBuilder(): Builder = Builder().from(this) + override fun toString(): String = - "HttpRequest {method=$method, pathSegments=$pathSegments, queryParams=$queryParams, headers=$headers, body=$body}" + "HttpRequest{method=$method, baseUrl=$baseUrl, pathSegments=$pathSegments, headers=$headers, queryParams=$queryParams, body=$body}" companion object { @JvmStatic fun builder() = Builder() } - class Builder { + class Builder internal constructor() { private var method: HttpMethod? = null - private var url: String? = null - private var pathSegments: MutableList = ArrayList() - private var queryParams: ListMultimap = ArrayListMultimap.create() + private var baseUrl: String? = null + private var pathSegments: MutableList = mutableListOf() + private var headers: Headers.Builder = Headers.builder() + private var queryParams: QueryParams.Builder = QueryParams.builder() private var body: HttpRequestBody? = null - private var headers: ListMultimap = - MultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER).arrayListValues().build() + + @JvmSynthetic + internal fun from(request: HttpRequest) = apply { + method = request.method + baseUrl = request.baseUrl + pathSegments = request.pathSegments.toMutableList() + headers = request.headers.toBuilder() + queryParams = request.queryParams.toBuilder() + body = request.body + } fun method(method: HttpMethod) = apply { this.method = method } - fun url(url: String) = apply { this.url = url } + fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl } - fun addPathSegment(pathSegment: String) = apply { this.pathSegments.add(pathSegment) } + fun addPathSegment(pathSegment: String) = apply { pathSegments.add(pathSegment) } fun addPathSegments(vararg pathSegments: String) = apply { - for (pathSegment in pathSegments) { - this.pathSegments.add(pathSegment) - } + this.pathSegments.addAll(pathSegments) } - fun putQueryParam(name: String, value: String) = apply { - this.queryParams.replaceValues(name, listOf(value)) + fun headers(headers: Headers) = apply { + this.headers.clear() + putAllHeaders(headers) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.queryParams.replaceValues(name, values) + fun headers(headers: Map>) = apply { + this.headers.clear() + putAllHeaders(headers) } - fun putAllQueryParams(queryParams: Map>) = apply { - queryParams.forEach(this::putQueryParams) + fun putHeader(name: String, value: String) = apply { headers.put(name, value) } + + fun putHeaders(name: String, values: Iterable) = apply { headers.put(name, values) } + + fun putAllHeaders(headers: Headers) = apply { this.headers.putAll(headers) } + + fun putAllHeaders(headers: Map>) = apply { + this.headers.putAll(headers) } - fun putAllQueryParams(queryParams: Multimap) = apply { - queryParams.asMap().forEach(this::putQueryParams) + fun replaceHeaders(name: String, value: String) = apply { headers.replace(name, value) } + + fun replaceHeaders(name: String, values: Iterable) = apply { + headers.replace(name, values) } - fun putHeader(name: String, value: String) = apply { - this.headers.replaceValues(name, listOf(value)) + fun replaceAllHeaders(headers: Headers) = apply { this.headers.replaceAll(headers) } + + fun replaceAllHeaders(headers: Map>) = apply { + this.headers.replaceAll(headers) } - fun putHeaders(name: String, values: Iterable) = apply { - this.headers.replaceValues(name, values) + fun removeHeaders(name: String) = apply { headers.remove(name) } + + fun removeAllHeaders(names: Set) = apply { headers.removeAll(names) } + + fun queryParams(queryParams: QueryParams) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) } - fun putAllHeaders(headers: Map>) = apply { - headers.forEach(this::putHeaders) + fun queryParams(queryParams: Map>) = apply { + this.queryParams.clear() + putAllQueryParams(queryParams) } - fun putAllHeaders(headers: Multimap) = apply { - headers.asMap().forEach(this::putHeaders) + fun putQueryParam(key: String, value: String) = apply { queryParams.put(key, value) } + + fun putQueryParams(key: String, values: Iterable) = apply { + queryParams.put(key, values) } + fun putAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.putAll(queryParams) + } + + fun putAllQueryParams(queryParams: Map>) = apply { + this.queryParams.putAll(queryParams) + } + + fun replaceQueryParams(key: String, value: String) = apply { + queryParams.replace(key, value) + } + + fun replaceQueryParams(key: String, values: Iterable) = apply { + queryParams.replace(key, values) + } + + fun replaceAllQueryParams(queryParams: QueryParams) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun replaceAllQueryParams(queryParams: Map>) = apply { + this.queryParams.replaceAll(queryParams) + } + + fun removeQueryParams(key: String) = apply { queryParams.remove(key) } + + fun removeAllQueryParams(keys: Set) = apply { queryParams.removeAll(keys) } + fun body(body: HttpRequestBody) = apply { this.body = body } fun build(): HttpRequest = HttpRequest( - checkNotNull(method) { "`method` is required but was not set" }, - url, - pathSegments.toUnmodifiable(), - queryParams.toUnmodifiable(), - headers, + checkRequired("method", method), + checkRequired("baseUrl", baseUrl), + pathSegments.toImmutable(), + headers.build(), + queryParams.build(), body, ) } 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 new file mode 100644 index 00000000..2ab71012 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBodies.kt @@ -0,0 +1,130 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:JvmName("HttpRequestBodies") + +package com.braintrustdata.api.core.http + +import com.braintrustdata.api.core.MultipartField +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.InputStream +import java.io.OutputStream +import kotlin.jvm.optionals.getOrNull +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder +import org.apache.hc.core5.http.ContentType +import org.apache.hc.core5.http.HttpEntity + +@JvmSynthetic +internal inline fun json(jsonMapper: JsonMapper, value: T): HttpRequestBody = + object : HttpRequestBody { + private val bytes: ByteArray by lazy { jsonMapper.writeValueAsBytes(value) } + + override fun writeTo(outputStream: OutputStream) = outputStream.write(bytes) + + override fun contentType(): String = "application/json" + + override fun contentLength(): Long = bytes.size.toLong() + + override fun repeatable(): Boolean = true + + override fun close() {} + } + +@JvmSynthetic +internal fun multipartFormData( + jsonMapper: JsonMapper, + fields: Map>, +): HttpRequestBody = + object : HttpRequestBody { + private val entity: HttpEntity by lazy { + MultipartEntityBuilder.create() + .apply { + fields.forEach { (name, field) -> + val knownValue = field.value.asKnown().getOrNull() + val parts = + if (knownValue is InputStream) { + // Read directly from the `InputStream` instead of reading it all + // into memory due to the `jsonMapper` serialization below. + sequenceOf(name to knownValue) + } else { + val node = jsonMapper.valueToTree(field.value) + serializePart(name, node) + } + + parts.forEach { (name, bytes) -> + addBinaryBody( + name, + bytes, + ContentType.parseLenient(field.contentType), + field.filename().getOrNull(), + ) + } + } + } + .build() + } + + private fun serializePart( + name: String, + node: JsonNode, + ): Sequence> = + when (node.nodeType) { + JsonNodeType.MISSING, + JsonNodeType.NULL -> emptySequence() + JsonNodeType.BINARY -> sequenceOf(name to node.binaryValue().inputStream()) + JsonNodeType.STRING -> sequenceOf(name to node.textValue().inputStream()) + JsonNodeType.BOOLEAN -> + sequenceOf(name to node.booleanValue().toString().inputStream()) + JsonNodeType.NUMBER -> + sequenceOf(name to node.numberValue().toString().inputStream()) + JsonNodeType.ARRAY -> + sequenceOf( + name to + node + .elements() + .asSequence() + .mapNotNull { element -> + when (element.nodeType) { + JsonNodeType.MISSING, + JsonNodeType.NULL -> null + JsonNodeType.STRING -> node.textValue() + JsonNodeType.BOOLEAN -> node.booleanValue().toString() + JsonNodeType.NUMBER -> node.numberValue().toString() + null, + JsonNodeType.BINARY, + JsonNodeType.ARRAY, + JsonNodeType.OBJECT, + JsonNodeType.POJO -> + throw BraintrustInvalidDataException( + "Unexpected JsonNode type in array: ${node.nodeType}" + ) + } + } + .joinToString(",") + .inputStream() + ) + JsonNodeType.OBJECT -> + node.fields().asSequence().flatMap { (key, value) -> + serializePart("$name[$key]", value) + } + JsonNodeType.POJO, + null -> + throw BraintrustInvalidDataException( + "Unexpected JsonNode type: ${node.nodeType}" + ) + } + + private fun String.inputStream(): InputStream = toByteArray().inputStream() + + override fun writeTo(outputStream: OutputStream) = entity.writeTo(outputStream) + + override fun contentType(): String = entity.contentType + + override fun contentLength(): Long = entity.contentLength + + override fun repeatable(): Boolean = entity.isRepeatable + + override fun close() = entity.close() + } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBody.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBody.kt old mode 100644 new mode 100755 index 6250e527..ebf2b4d5 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBody.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpRequestBody.kt @@ -1,15 +1,16 @@ package com.braintrustdata.api.core.http -import java.io.Closeable -import java.io.IOException import java.io.OutputStream +import java.lang.AutoCloseable -interface HttpRequestBody : Closeable { +interface HttpRequestBody : AutoCloseable { - @Throws(IOException::class) fun writeTo(outputStream: OutputStream) + fun writeTo(outputStream: OutputStream) fun contentType(): String? + fun contentLength(): Long + /** * Determines if a request can be repeated in a meaningful way, for example before doing a * retry. @@ -19,5 +20,6 @@ interface HttpRequestBody : Closeable { */ fun repeatable(): Boolean + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ override fun close() } 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 old mode 100644 new mode 100755 index 6363509b..dbfbe2cb --- 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,17 +1,20 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.core.http -import com.google.common.collect.ListMultimap -import java.io.Closeable import java.io.InputStream -interface HttpResponse : Closeable { +interface HttpResponse : AutoCloseable { fun statusCode(): Int - fun headers(): ListMultimap + fun headers(): Headers fun body(): InputStream + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() + interface Handler { fun handle(response: HttpResponse): T diff --git a/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 new file mode 100644 index 00000000..a8b0e532 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/HttpResponseFor.kt @@ -0,0 +1,25 @@ +package com.braintrustdata.api.core.http + +import java.io.InputStream + +interface HttpResponseFor : HttpResponse { + + fun parse(): T +} + +@JvmSynthetic +internal fun HttpResponse.parseable(parse: () -> T): HttpResponseFor = + object : HttpResponseFor { + + private val parsed: T by lazy { parse() } + + override fun parse(): T = parsed + + override fun statusCode(): Int = this@parseable.statusCode() + + override fun headers(): Headers = this@parseable.headers() + + override fun body(): InputStream = this@parseable.body() + + override fun close() = this@parseable.close() + } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt new file mode 100644 index 00000000..6d826dd4 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingAsyncStreamResponse.kt @@ -0,0 +1,56 @@ +package com.braintrustdata.api.core.http + +import com.braintrustdata.api.core.closeWhenPhantomReachable +import com.braintrustdata.api.core.http.AsyncStreamResponse.Handler +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor + +/** + * A delegating wrapper around an `AsyncStreamResponse` that closes it once it's only phantom + * reachable. + * + * This class ensures the `AsyncStreamResponse` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingAsyncStreamResponse( + private val asyncStreamResponse: AsyncStreamResponse +) : AsyncStreamResponse { + + /** + * An object used for keeping `asyncStreamResponse` open while the object is still reachable. + */ + private val reachabilityTracker = Object() + + init { + closeWhenPhantomReachable(reachabilityTracker, asyncStreamResponse::close) + } + + override fun subscribe(handler: Handler): AsyncStreamResponse = apply { + asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker)) + } + + override fun subscribe(handler: Handler, executor: Executor): AsyncStreamResponse = + apply { + asyncStreamResponse.subscribe(TrackedHandler(handler, reachabilityTracker), executor) + } + + override fun onCompleteFuture(): CompletableFuture = + asyncStreamResponse.onCompleteFuture() + + override fun close() = asyncStreamResponse.close() +} + +/** + * A wrapper around a `Handler` that also references a `reachabilityTracker` object. + * + * Referencing the `reachabilityTracker` object prevents it from getting reclaimed while the handler + * is still reachable. + */ +private class TrackedHandler( + private val handler: Handler, + private val reachabilityTracker: Any, +) : Handler { + override fun onNext(value: T) = handler.onNext(value) + + override fun onComplete(error: Optional) = handler.onComplete(error) +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingHttpClient.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingHttpClient.kt new file mode 100644 index 00000000..e766e040 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingHttpClient.kt @@ -0,0 +1,26 @@ +package com.braintrustdata.api.core.http + +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.closeWhenPhantomReachable +import java.util.concurrent.CompletableFuture + +/** + * A delegating wrapper around an `HttpClient` that closes it once it's only phantom reachable. + * + * This class ensures the `HttpClient` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingHttpClient(private val httpClient: HttpClient) : HttpClient { + init { + closeWhenPhantomReachable(this, httpClient) + } + + override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse = + httpClient.execute(request, requestOptions) + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture = httpClient.executeAsync(request, requestOptions) + + override fun close() = httpClient.close() +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingStreamResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingStreamResponse.kt new file mode 100644 index 00000000..9c79ceb6 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/PhantomReachableClosingStreamResponse.kt @@ -0,0 +1,21 @@ +package com.braintrustdata.api.core.http + +import com.braintrustdata.api.core.closeWhenPhantomReachable +import java.util.stream.Stream + +/** + * A delegating wrapper around a `StreamResponse` that closes it once it's only phantom reachable. + * + * This class ensures the `StreamResponse` is closed even if the user forgets to close it. + */ +internal class PhantomReachableClosingStreamResponse( + private val streamResponse: StreamResponse +) : StreamResponse { + init { + closeWhenPhantomReachable(this, streamResponse) + } + + override fun stream(): Stream = streamResponse.stream() + + override fun close() = streamResponse.close() +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/QueryParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/QueryParams.kt new file mode 100644 index 00000000..60103d82 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/QueryParams.kt @@ -0,0 +1,129 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core.http + +import com.braintrustdata.api.core.JsonArray +import com.braintrustdata.api.core.JsonBoolean +import com.braintrustdata.api.core.JsonMissing +import com.braintrustdata.api.core.JsonNull +import com.braintrustdata.api.core.JsonNumber +import com.braintrustdata.api.core.JsonObject +import com.braintrustdata.api.core.JsonString +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.toImmutable + +class QueryParams +private constructor( + private val map: Map>, + @get:JvmName("size") val size: Int, +) { + + fun isEmpty(): Boolean = map.isEmpty() + + fun keys(): Set = map.keys + + fun values(key: String): List = map[key].orEmpty() + + fun toBuilder(): Builder = Builder().putAll(map) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder internal constructor() { + + private val map: MutableMap> = mutableMapOf() + private var size: Int = 0 + + fun put(key: String, value: JsonValue): Builder = apply { + when (value) { + is JsonMissing, + is JsonNull -> {} + is JsonBoolean -> put(key, value.value.toString()) + is JsonNumber -> put(key, value.value.toString()) + is JsonString -> put(key, value.value) + is JsonArray -> + put( + key, + value.values + .asSequence() + .mapNotNull { + when (it) { + is JsonMissing, + is JsonNull -> null + is JsonBoolean -> it.value.toString() + is JsonNumber -> it.value.toString() + is JsonString -> it.value + is JsonArray, + is JsonObject -> + throw IllegalArgumentException( + "Cannot comma separate non-primitives in query params" + ) + } + } + .joinToString(","), + ) + is JsonObject -> + value.values.forEach { (nestedKey, value) -> put("$key[$nestedKey]", value) } + } + } + + fun put(key: String, value: String) = apply { + map.getOrPut(key) { mutableListOf() }.add(value) + size++ + } + + fun put(key: String, values: Iterable) = apply { values.forEach { put(key, it) } } + + fun putAll(queryParams: Map>) = apply { + queryParams.forEach(::put) + } + + fun putAll(queryParams: QueryParams) = apply { + queryParams.keys().forEach { put(it, queryParams.values(it)) } + } + + fun replace(key: String, value: String) = apply { + remove(key) + put(key, value) + } + + fun replace(key: String, values: Iterable) = apply { + remove(key) + put(key, values) + } + + fun replaceAll(queryParams: Map>) = apply { + queryParams.forEach(::replace) + } + + fun replaceAll(queryParams: QueryParams) = apply { + queryParams.keys().forEach { replace(it, queryParams.values(it)) } + } + + fun remove(key: String) = apply { size -= map.remove(key).orEmpty().size } + + fun removeAll(keys: Set) = apply { keys.forEach(::remove) } + + fun clear() = apply { + map.clear() + size = 0 + } + + fun build() = + QueryParams(map.mapValues { (_, values) -> values.toImmutable() }.toImmutable(), size) + } + + override fun hashCode(): Int = map.hashCode() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is QueryParams && map == other.map + } + + override fun toString(): String = "QueryParams{map=$map}" +} diff --git a/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 old mode 100644 new mode 100755 index 73fa01c7..5bdca25d --- 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 @@ -1,10 +1,11 @@ -@file:JvmSynthetic - package com.braintrustdata.api.core.http +import com.braintrustdata.api.core.DefaultSleeper import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.Sleeper +import com.braintrustdata.api.core.checkRequired import com.braintrustdata.api.errors.BraintrustIoException -import com.google.common.util.concurrent.MoreExecutors +import com.braintrustdata.api.errors.BraintrustRetryableException import java.io.IOException import java.time.Clock import java.time.Duration @@ -12,8 +13,6 @@ import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.time.temporal.ChronoUnit -import java.util.Timer -import java.util.TimerTask import java.util.UUID import java.util.concurrent.CompletableFuture import java.util.concurrent.ThreadLocalRandom @@ -25,42 +24,50 @@ import kotlin.math.pow class RetryingHttpClient private constructor( private val httpClient: HttpClient, + private val sleeper: Sleeper, private val clock: Clock, private val maxRetries: Int, private val idempotencyHeader: String?, ) : HttpClient { - override fun execute( - request: HttpRequest, - requestOptions: RequestOptions, - ): HttpResponse { + override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse { if (!isRetryable(request) || maxRetries <= 0) { return httpClient.execute(request, requestOptions) } - maybeAddIdempotencyHeader(request) + var modifiedRequest = maybeAddIdempotencyHeader(request) + + // Don't send the current retry count in the headers if the caller set their own value. + val shouldSendRetryCount = + !modifiedRequest.headers.names().contains("X-Stainless-Retry-Count") var retries = 0 while (true) { + if (shouldSendRetryCount) { + modifiedRequest = setRetryCountHeader(modifiedRequest, retries) + } + val response = try { - val response = httpClient.execute(request, requestOptions) + val response = httpClient.execute(modifiedRequest, requestOptions) if (++retries > maxRetries || !shouldRetry(response)) { return response } response - } catch (t: Throwable) { - if (++retries > maxRetries || !shouldRetry(t)) { - throw t + } catch (throwable: Throwable) { + if (++retries > maxRetries || !shouldRetry(throwable)) { + throw throwable } null } - val backoffMillis = getRetryBackoffMillis(retries, response) - Thread.sleep(backoffMillis.toMillis()) + val backoffDuration = getRetryBackoffDuration(retries, response) + // All responses must be closed, so close the failed one before retrying. + response?.close() + sleeper.sleep(backoffDuration) } } @@ -72,16 +79,27 @@ private constructor( return httpClient.executeAsync(request, requestOptions) } - maybeAddIdempotencyHeader(request) + val modifiedRequest = maybeAddIdempotencyHeader(request) + + // Don't send the current retry count in the headers if the caller set their own value. + val shouldSendRetryCount = + !modifiedRequest.headers.names().contains("X-Stainless-Retry-Count") var retries = 0 - fun wrap(future: CompletableFuture): CompletableFuture { - return future + fun executeWithRetries( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture { + val requestWithRetryCount = + if (shouldSendRetryCount) setRetryCountHeader(request, retries) else request + + return httpClient + .executeAsync(requestWithRetryCount, requestOptions) .handleAsync( fun( response: HttpResponse?, - throwable: Throwable? + throwable: Throwable?, ): CompletableFuture { if (response != null) { if (++retries > maxRetries || !shouldRetry(response)) { @@ -95,41 +113,53 @@ private constructor( } } - val backoffMillis = getRetryBackoffMillis(retries, response) - return sleepAsync(backoffMillis.toMillis()).thenCompose { - wrap(httpClient.executeAsync(request, requestOptions)) + val backoffDuration = getRetryBackoffDuration(retries, response) + // All responses must be closed, so close the failed one before retrying. + response?.close() + return sleeper.sleepAsync(backoffDuration).thenCompose { + executeWithRetries(requestWithRetryCount, requestOptions) } - }, - MoreExecutors.directExecutor() - ) + } + ) { + // Run in the same thread. + it.run() + } .thenCompose(Function.identity()) } - return wrap(httpClient.executeAsync(request, requestOptions)) + return executeWithRetries(modifiedRequest, requestOptions) } override fun close() { httpClient.close() + sleeper.close() } - private fun isRetryable(request: HttpRequest): Boolean { + private fun isRetryable(request: HttpRequest): Boolean = // Some requests, such as when a request body is being streamed, cannot be retried because // the body data aren't available on subsequent attempts. - return request.body?.repeatable() ?: true - } + request.body?.repeatable() ?: true + + private fun setRetryCountHeader(request: HttpRequest, retries: Int): HttpRequest = + request.toBuilder().replaceHeaders("X-Stainless-Retry-Count", retries.toString()).build() private fun idempotencyKey(): String = "stainless-java-retry-${UUID.randomUUID()}" - private fun maybeAddIdempotencyHeader(request: HttpRequest) { - if (idempotencyHeader != null && !request.headers.containsKey(idempotencyHeader)) { - // Set a header to uniquely identify the request when retried - request.headers.put(idempotencyHeader, idempotencyKey()) + private fun maybeAddIdempotencyHeader(request: HttpRequest): HttpRequest { + if (idempotencyHeader == null || request.headers.names().contains(idempotencyHeader)) { + return request } + + return request + .toBuilder() + // Set a header to uniquely identify the request when retried. + .putHeader(idempotencyHeader, idempotencyKey()) + .build() } private fun shouldRetry(response: HttpResponse): Boolean { // Note: this is not a standard header - val shouldRetryHeader = response.headers().get("x-should-retry").getOrNull(0) + val shouldRetryHeader = response.headers().values("X-Should-Retry").getOrNull(0) val statusCode = response.statusCode() return when { @@ -149,32 +179,32 @@ private constructor( } } - private fun shouldRetry(throwable: Throwable): Boolean { - // Only retry IOException and BraintrustIoException, other exceptions are not intended to be - // retried. - return throwable is IOException || throwable is BraintrustIoException - } + private fun shouldRetry(throwable: Throwable): Boolean = + // Only retry known retryable exceptions, other exceptions are not intended to be retried. + throwable is IOException || + throwable is BraintrustIoException || + throwable is BraintrustRetryableException - 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 ?.headers() ?.let { headers -> headers - .get("Retry-After-Ms") + .values("Retry-After-Ms") .getOrNull(0) ?.toFloatOrNull() ?.times(TimeUnit.MILLISECONDS.toNanos(1)) - ?: headers.get("Retry-After").getOrNull(0)?.let { retryAfter -> + ?: headers.values("Retry-After").getOrNull(0)?.let { retryAfter -> retryAfter.toFloatOrNull()?.times(TimeUnit.SECONDS.toNanos(1)) ?: try { ChronoUnit.MILLIS.between( OffsetDateTime.now(clock), OffsetDateTime.parse( retryAfter, - DateTimeFormatter.RFC_1123_DATE_TIME - ) + DateTimeFormatter.RFC_1123_DATE_TIME, + ), ) } catch (e: DateTimeParseException) { null @@ -200,35 +230,23 @@ private constructor( return Duration.ofNanos((TimeUnit.SECONDS.toNanos(1) * backoffSeconds * jitter).toLong()) } - private fun sleepAsync(millis: Long): CompletableFuture { - val future = CompletableFuture() - TIMER.schedule( - object : TimerTask() { - override fun run() { - future.complete(null) - } - }, - millis - ) - return future - } - companion object { - private val TIMER = Timer("RetryingHttpClient", true) - @JvmStatic fun builder() = Builder() } - class Builder { + class Builder internal constructor() { private var httpClient: HttpClient? = null + private var sleeper: Sleeper? = null private var clock: Clock = Clock.systemUTC() private var maxRetries: Int = 2 private var idempotencyHeader: String? = null fun httpClient(httpClient: HttpClient) = apply { this.httpClient = httpClient } + fun sleeper(sleeper: Sleeper) = apply { this.sleeper = sleeper } + fun clock(clock: Clock) = apply { this.clock = clock } fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } @@ -237,7 +255,8 @@ private constructor( fun build(): HttpClient = RetryingHttpClient( - checkNotNull(httpClient) { "`httpClient` is required but was not set" }, + checkRequired("httpClient", httpClient), + sleeper ?: DefaultSleeper(), clock, maxRetries, idempotencyHeader, diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/StreamResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/StreamResponse.kt new file mode 100644 index 00000000..3903400b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/core/http/StreamResponse.kt @@ -0,0 +1,19 @@ +package com.braintrustdata.api.core.http + +import java.util.stream.Stream + +interface StreamResponse : AutoCloseable { + + fun stream(): Stream + + /** Overridden from [AutoCloseable] to not have a checked exception in its signature. */ + override fun close() +} + +@JvmSynthetic +internal fun StreamResponse.map(transform: (T) -> R): StreamResponse = + object : StreamResponse { + override fun stream(): Stream = this@map.stream().map(transform) + + override fun close() = this@map.close() + } diff --git a/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 old mode 100644 new mode 100755 index 722109a0..9e02c395 --- 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,12 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( - headers: ListMultimap, - private val error: BraintrustError, -) : BraintrustServiceException(headers, "${error}") { +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("400: $body", cause) { + override fun statusCode(): Int = 400 - fun error(): BraintrustError = error + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [BadRequestException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [BadRequestException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(badRequestException: BadRequestException) = apply { + headers = badRequestException.headers + body = badRequestException.body + cause = badRequestException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [BadRequestException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): BadRequestException = + BadRequestException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } } diff --git a/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 100644 index e845c581..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustError.kt +++ /dev/null @@ -1,67 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.errors - -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.util.Objects - -@JsonDeserialize(builder = BraintrustError.Builder::class) -@NoAutoDetect -class BraintrustError -constructor( - private val additionalProperties: Map, -) { - - @JsonAnyGetter fun additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is BraintrustError && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - return Objects.hash(additionalProperties) - } - - override fun toString() = "BraintrustError{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - fun from(error: BraintrustError) = apply { - additionalProperties(error.additionalProperties) - } - - 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(): BraintrustError = BraintrustError(additionalProperties.toUnmodifiable()) - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustException.kt old mode 100644 new mode 100755 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustInvalidDataException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustInvalidDataException.kt old mode 100644 new mode 100755 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustIoException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustIoException.kt old mode 100644 new mode 100755 diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustRetryableException.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustRetryableException.kt new file mode 100644 index 00000000..e70380e9 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/errors/BraintrustRetryableException.kt @@ -0,0 +1,15 @@ +package com.braintrustdata.api.errors + +/** + * Exception that indicates a transient error that can be retried. + * + * When this exception is thrown during an HTTP request, the SDK will automatically retry the + * request up to the maximum number of retries. + * + * @param message A descriptive error message + * @param cause The underlying cause of this exception, if any + */ +class BraintrustRetryableException +@JvmOverloads +constructor(message: String? = null, cause: Throwable? = null) : + BraintrustException(message, cause) 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 old mode 100644 new mode 100755 index 78dc66a3..ebb6267b --- 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,14 +1,17 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.http.Headers abstract class BraintrustServiceException -@JvmOverloads -constructor( - private val headers: ListMultimap, - message: String? = null, - cause: Throwable? = null -) : BraintrustException(message, cause) { +protected constructor(message: String, cause: Throwable? = null) : + BraintrustException(message, cause) { + abstract fun statusCode(): Int - fun headers(): ListMultimap = headers + + abstract fun headers(): Headers + + 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 old mode 100644 new mode 100755 index c7545146..9834c41a --- 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,13 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( +private constructor( private val statusCode: Int, - headers: ListMultimap, - private val error: BraintrustError, -) : BraintrustServiceException(headers, "${error}") { + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : BraintrustServiceException("$statusCode: $body", cause) { + override fun statusCode(): Int = statusCode - fun error(): BraintrustError = error + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InternalServerException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InternalServerException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(internalServerException: InternalServerException) = apply { + statusCode = internalServerException.statusCode + headers = internalServerException.headers + body = internalServerException.body + cause = internalServerException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [InternalServerException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InternalServerException = + InternalServerException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } } diff --git a/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 old mode 100644 new mode 100755 index 99f06d12..d31d5688 --- 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,12 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( - headers: ListMultimap, - private val error: BraintrustError, -) : BraintrustServiceException(headers, "${error}") { +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("404: $body", cause) { + override fun statusCode(): Int = 404 - fun error(): BraintrustError = error + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [NotFoundException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [NotFoundException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(notFoundException: NotFoundException) = apply { + headers = notFoundException.headers + body = notFoundException.body + cause = notFoundException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [NotFoundException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): NotFoundException = + NotFoundException(checkRequired("headers", headers), checkRequired("body", body), cause) + } } diff --git a/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 old mode 100644 new mode 100755 index 259232e4..b6926f3f --- 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,12 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( - headers: ListMultimap, - private val error: BraintrustError, -) : BraintrustServiceException(headers, "${error}") { +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("403: $body", cause) { + override fun statusCode(): Int = 403 - fun error(): BraintrustError = error + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PermissionDeniedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PermissionDeniedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(permissionDeniedException: PermissionDeniedException) = apply { + headers = permissionDeniedException.headers + body = permissionDeniedException.body + cause = permissionDeniedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [PermissionDeniedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PermissionDeniedException = + PermissionDeniedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } } diff --git a/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 old mode 100644 new mode 100755 index d579165a..cb32fed9 --- 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,12 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( - headers: ListMultimap, - private val error: BraintrustError, -) : BraintrustServiceException(headers, "${error}") { +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("429: $body", cause) { + override fun statusCode(): Int = 429 - fun error(): BraintrustError = error + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RateLimitException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RateLimitException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(rateLimitException: RateLimitException) = apply { + headers = rateLimitException.headers + body = rateLimitException.body + cause = rateLimitException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [RateLimitException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RateLimitException = + RateLimitException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } } diff --git a/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 old mode 100644 new mode 100755 index bf2bfb3e..55d60f4c --- 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,12 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( - headers: ListMultimap, - private val error: BraintrustError, -) : BraintrustServiceException(headers, "${error}") { +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("401: $body", cause) { + override fun statusCode(): Int = 401 - fun error(): BraintrustError = error + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnauthorizedException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnauthorizedException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unauthorizedException: UnauthorizedException) = apply { + headers = unauthorizedException.headers + body = unauthorizedException.body + cause = unauthorizedException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [UnauthorizedException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnauthorizedException = + UnauthorizedException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } } diff --git a/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 old mode 100644 new mode 100755 index 7e165e0c..f463ecdd --- 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,13 +1,92 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( +private constructor( private val statusCode: Int, - headers: ListMultimap, - private val body: String -) : BraintrustServiceException(headers, "Unexpected status code: ${statusCode}") { + private val headers: Headers, + private val body: JsonValue, + cause: Throwable?, +) : BraintrustServiceException("$statusCode: $body", cause) { + override fun statusCode(): Int = statusCode - fun body() = body + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [UnexpectedStatusCodeException]. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnexpectedStatusCodeException]. */ + class Builder internal constructor() { + + private var statusCode: Int? = null + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unexpectedStatusCodeException: UnexpectedStatusCodeException) = apply { + statusCode = unexpectedStatusCodeException.statusCode + headers = unexpectedStatusCodeException.headers + body = unexpectedStatusCodeException.body + cause = unexpectedStatusCodeException.cause + } + + fun statusCode(statusCode: Int) = apply { this.statusCode = statusCode } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [UnexpectedStatusCodeException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .statusCode() + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnexpectedStatusCodeException = + UnexpectedStatusCodeException( + checkRequired("statusCode", statusCode), + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } } diff --git a/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 old mode 100644 new mode 100755 index c09e5914..22101f46 --- 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,12 +1,80 @@ +// File generated from our OpenAPI spec by Stainless. + package com.braintrustdata.api.errors -import com.google.common.collect.ListMultimap +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 -constructor( - headers: ListMultimap, - private val error: BraintrustError, -) : BraintrustServiceException(headers, "${error}") { +private constructor(private val headers: Headers, private val body: JsonValue, cause: Throwable?) : + BraintrustServiceException("422: $body", cause) { + override fun statusCode(): Int = 422 - fun error(): BraintrustError = error + + override fun headers(): Headers = headers + + override fun body(): JsonValue = body + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UnprocessableEntityException]. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UnprocessableEntityException]. */ + class Builder internal constructor() { + + private var headers: Headers? = null + private var body: JsonValue? = null + private var cause: Throwable? = null + + @JvmSynthetic + internal fun from(unprocessableEntityException: UnprocessableEntityException) = apply { + headers = unprocessableEntityException.headers + body = unprocessableEntityException.body + cause = unprocessableEntityException.cause + } + + fun headers(headers: Headers) = apply { this.headers = headers } + + fun body(body: JsonValue) = apply { this.body = body } + + fun cause(cause: Throwable?) = apply { this.cause = cause } + + /** Alias for calling [Builder.cause] with `cause.orElse(null)`. */ + fun cause(cause: Optional) = cause(cause.getOrNull()) + + /** + * Returns an immutable instance of [UnprocessableEntityException]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .headers() + * .body() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UnprocessableEntityException = + UnprocessableEntityException( + checkRequired("headers", headers), + checkRequired("body", body), + cause, + ) + } } diff --git a/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 new file mode 100644 index 00000000..a47ab007 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AISecret.kt @@ -0,0 +1,556 @@ +// 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.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.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class AISecret +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * 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") + + /** + * Unique identifier for the organization + * + * @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 orgId(): String = orgId.getRequired("org_id") + + /** + * Date of AI secret creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 = 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 = 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 = type.getOptional("type") + + /** + * Date of last AI secret update + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun updatedAt(): Optional = updatedAt.getOptional("updated_at") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [previewSecret]. + * + * Unlike [previewSecret], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("preview_secret") + @ExcludeMissing + fun _previewSecret(): JsonField = previewSecret + + /** + * 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 + + /** + * Returns the raw JSON value of [updatedAt]. + * + * Unlike [updatedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("updated_at") + @ExcludeMissing + fun _updatedAt(): JsonField = updatedAt + + @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 [AISecret]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .orgId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AISecret]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var orgId: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var previewSecret: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var updatedAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aiSecret: AISecret) = apply { + id = aiSecret.id + name = aiSecret.name + orgId = aiSecret.orgId + created = aiSecret.created + metadata = aiSecret.metadata + previewSecret = aiSecret.previewSecret + type = aiSecret.type + updatedAt = aiSecret.updatedAt + additionalProperties = aiSecret.additionalProperties.toMutableMap() + } + + /** Unique identifier for the AI secret */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** 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 } + + /** Unique identifier for the organization */ + fun orgId(orgId: String) = orgId(JsonField.of(orgId)) + + /** + * 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 } + + /** Date of AI secret creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + 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 previewSecret(previewSecret: String?) = + previewSecret(JsonField.ofNullable(previewSecret)) + + /** Alias for calling [Builder.previewSecret] with `previewSecret.orElse(null)`. */ + fun previewSecret(previewSecret: Optional) = + previewSecret(previewSecret.getOrNull()) + + /** + * Sets [Builder.previewSecret] to an arbitrary JSON value. + * + * You should usually call [Builder.previewSecret] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun previewSecret(previewSecret: JsonField) = apply { + this.previewSecret = previewSecret + } + + 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 } + + /** Date of last AI secret update */ + fun updatedAt(updatedAt: OffsetDateTime?) = updatedAt(JsonField.ofNullable(updatedAt)) + + /** Alias for calling [Builder.updatedAt] with `updatedAt.orElse(null)`. */ + fun updatedAt(updatedAt: Optional) = updatedAt(updatedAt.getOrNull()) + + /** + * Sets [Builder.updatedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.updatedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun updatedAt(updatedAt: JsonField) = apply { this.updatedAt = updatedAt } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AISecret]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .orgId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AISecret = + AISecret( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("orgId", orgId), + created, + metadata, + previewSecret, + type, + updatedAt, + additionalProperties.toMutableMap(), + ) + } + + 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( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AISecret && + id == other.id && + name == other.name && + orgId == other.orgId && + created == other.created && + metadata == other.metadata && + previewSecret == other.previewSecret && + type == other.type && + updatedAt == other.updatedAt && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + orgId, + created, + metadata, + previewSecret, + type, + updatedAt, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AISecret{id=$id, name=$name, orgId=$orgId, created=$created, metadata=$metadata, previewSecret=$previewSecret, type=$type, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..9175b110 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Acl.kt @@ -0,0 +1,591 @@ +// 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.checkRequired +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 + +/** + * 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 Acl +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The organization the ACL's referred object belongs 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 _objectOrgId(): String = _objectOrgId.getRequired("_object_org_id") + + /** + * The id of the object 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 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") + + /** + * Date of acl creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun groupId(): Optional = groupId.getOptional("group_id") + + /** + * Permission 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 permission(): Optional = permission.getOptional("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") + + /** + * 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") + + /** + * 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 userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_objectOrgId]. + * + * Unlike [_objectOrgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_object_org_id") + @ExcludeMissing + fun __objectOrgId(): JsonField = _objectOrgId + + /** + * 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 + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [groupId]. + * + * Unlike [groupId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("group_id") @ExcludeMissing fun _groupId(): JsonField = groupId + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Acl]. + * + * The following fields are required: + * ```java + * .id() + * ._objectOrgId() + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Acl]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var _objectOrgId: JsonField? = null + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var created: JsonField = JsonMissing.of() + 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(acl: Acl) = apply { + id = acl.id + _objectOrgId = acl._objectOrgId + objectId = acl.objectId + objectType = acl.objectType + created = acl.created + groupId = acl.groupId + permission = acl.permission + restrictObjectType = acl.restrictObjectType + roleId = acl.roleId + userId = acl.userId + additionalProperties = acl.additionalProperties.toMutableMap() + } + + /** Unique identifier for the acl */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The organization the ACL's referred object belongs to */ + fun _objectOrgId(_objectOrgId: String) = _objectOrgId(JsonField.of(_objectOrgId)) + + /** + * Sets [Builder._objectOrgId] to an arbitrary JSON value. + * + * You should usually call [Builder._objectOrgId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun _objectOrgId(_objectOrgId: JsonField) = apply { + this._objectOrgId = _objectOrgId + } + + /** 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 + } + + /** Date of acl creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** + * 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)) + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * 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 } + + /** + * 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)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Acl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ._objectOrgId() + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Acl = + Acl( + checkRequired("id", id), + checkRequired("_objectOrgId", _objectOrgId), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + created, + groupId, + permission, + restrictObjectType, + roleId, + userId, + 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 + } + + return other is Acl && + id == other.id && + _objectOrgId == other._objectOrgId && + objectId == other.objectId && + objectType == other.objectType && + created == other.created && + groupId == other.groupId && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + roleId == other.roleId && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _objectOrgId, + objectId, + objectType, + created, + groupId, + permission, + restrictObjectType, + roleId, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Acl{id=$id, _objectOrgId=$_objectOrgId, objectId=$objectId, objectType=$objectType, created=$created, groupId=$groupId, permission=$permission, restrictObjectType=$restrictObjectType, roleId=$roleId, userId=$userId, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..d8471677 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateParams.kt @@ -0,0 +1,1521 @@ +// 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.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.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 + +/** + * Batch update acls. This operation is idempotent, so adding acls which already exist will have no + * effect, and removing acls which do not exist will have no effect. + */ +class AclBatchUpdateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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> = body.addAcls() + + /** + * 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> = body.removeAcls() + + /** + * Returns the raw JSON value of [addAcls]. + * + * Unlike [addAcls], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _addAcls(): JsonField> = body._addAcls() + + /** + * Returns the raw JSON value of [removeAcls]. + * + * Unlike [removeAcls], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _removeAcls(): JsonField> = body._removeAcls() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AclBatchUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AclBatchUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclBatchUpdateParams]. */ + 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(aclBatchUpdateParams: AclBatchUpdateParams) = apply { + body = aclBatchUpdateParams.body.toBuilder() + additionalHeaders = aclBatchUpdateParams.additionalHeaders.toBuilder() + 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. + * + * 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?) = apply { body.addAcls(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 { body.addAcls(addAcls) } + + /** + * Adds a single [AddAcl] to [addAcls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAddAcl(addAcl: AddAcl) = apply { body.addAddAcl(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?) = apply { body.removeAcls(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 { + body.removeAcls(removeAcls) + } + + /** + * Adds a single [RemoveAcl] to [removeAcls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRemoveAcl(removeAcl: RemoveAcl) = apply { body.addRemoveAcl(removeAcl) } + + 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 [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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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)) + + /** 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.toMutableMap(), + ) + } + + 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 isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + addAcls == other.addAcls && + removeAcls == other.removeAcls && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(addAcls, removeAcls, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{addAcls=$addAcls, removeAcls=$removeAcls, additionalProperties=$additionalProperties}" + } + + /** + * 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 AddAcl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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(), + ) + + /** + * The id of the object 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 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") + + /** + * 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(): Optional = groupId.getOptional("group_id") + + /** + * Permission 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 permission(): Optional = permission.getOptional("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") + + /** + * 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") + + /** + * 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 userId(): Optional = userId.getOptional("user_id") + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AddAcl]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AddAcl]. */ + 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(addAcl: AddAcl) = apply { + objectId = addAcl.objectId + objectType = addAcl.objectType + groupId = addAcl.groupId + permission = addAcl.permission + restrictObjectType = addAcl.restrictObjectType + roleId = addAcl.roleId + userId = addAcl.userId + additionalProperties = addAcl.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.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)) + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * 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 } + + /** + * 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)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AddAcl]. + * + * 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(): AddAcl = + AddAcl( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + groupId, + permission, + restrictObjectType, + roleId, + userId, + 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 + } + + return other is AddAcl && + objectId == other.objectId && + objectType == other.objectType && + groupId == other.groupId && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + roleId == other.roleId && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AddAcl{objectId=$objectId, objectType=$objectType, groupId=$groupId, permission=$permission, restrictObjectType=$restrictObjectType, roleId=$roleId, userId=$userId, additionalProperties=$additionalProperties}" + } + + /** + * 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 RemoveAcl + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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(), + ) + + /** + * The id of the object 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 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") + + /** + * 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(): Optional = groupId.getOptional("group_id") + + /** + * Permission 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 permission(): Optional = permission.getOptional("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") + + /** + * 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") + + /** + * 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 userId(): Optional = userId.getOptional("user_id") + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RemoveAcl]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RemoveAcl]. */ + 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(removeAcl: RemoveAcl) = apply { + objectId = removeAcl.objectId + objectType = removeAcl.objectType + groupId = removeAcl.groupId + permission = removeAcl.permission + restrictObjectType = removeAcl.restrictObjectType + roleId = removeAcl.roleId + userId = removeAcl.userId + additionalProperties = removeAcl.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.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)) + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * 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 } + + /** + * 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)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RemoveAcl]. + * + * 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(): RemoveAcl = + RemoveAcl( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + groupId, + permission, + restrictObjectType, + roleId, + userId, + 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 + } + + return other is RemoveAcl && + objectId == other.objectId && + objectType == other.objectType && + groupId == other.groupId && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + roleId == other.roleId && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RemoveAcl{objectId=$objectId, objectType=$objectType, groupId=$groupId, permission=$permission, restrictObjectType=$restrictObjectType, roleId=$roleId, userId=$userId, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AclBatchUpdateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AclBatchUpdateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..a7429202 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponse.kt @@ -0,0 +1,282 @@ +// 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 AclBatchUpdateResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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. + * + * 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 or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun addedAcls(): List = addedAcls.getRequired("added_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 or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun removedAcls(): List = removedAcls.getRequired("removed_acls") + + /** + * Returns the raw JSON value of [addedAcls]. + * + * Unlike [addedAcls], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("added_acls") @ExcludeMissing fun _addedAcls(): JsonField> = addedAcls + + /** + * Returns the raw JSON value of [removedAcls]. + * + * Unlike [removedAcls], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("removed_acls") + @ExcludeMissing + fun _removedAcls(): JsonField> = removedAcls + + @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 [AclBatchUpdateResponse]. + * + * The following fields are required: + * ```java + * .addedAcls() + * .removedAcls() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclBatchUpdateResponse]. */ + class Builder internal constructor() { + + private var addedAcls: JsonField>? = null + private var removedAcls: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aclBatchUpdateResponse: AclBatchUpdateResponse) = apply { + addedAcls = aclBatchUpdateResponse.addedAcls.map { it.toMutableList() } + removedAcls = aclBatchUpdateResponse.removedAcls.map { it.toMutableList() } + additionalProperties = aclBatchUpdateResponse.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 addedAcls(addedAcls: List) = addedAcls(JsonField.of(addedAcls)) + + /** + * Sets [Builder.addedAcls] to an arbitrary JSON value. + * + * You should usually call [Builder.addedAcls] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun addedAcls(addedAcls: JsonField>) = apply { + this.addedAcls = addedAcls.map { it.toMutableList() } + } + + /** + * Adds a single [Acl] to [addedAcls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAddedAcl(addedAcl: Acl) = apply { + addedAcls = + (addedAcls ?: JsonField.of(mutableListOf())).also { + checkKnown("addedAcls", it).add(addedAcl) + } + } + + /** + * 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 removedAcls(removedAcls: List) = removedAcls(JsonField.of(removedAcls)) + + /** + * Sets [Builder.removedAcls] to an arbitrary JSON value. + * + * You should usually call [Builder.removedAcls] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun removedAcls(removedAcls: JsonField>) = apply { + this.removedAcls = removedAcls.map { it.toMutableList() } + } + + /** + * Adds a single [Acl] to [removedAcls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRemovedAcl(removedAcl: Acl) = apply { + removedAcls = + (removedAcls ?: JsonField.of(mutableListOf())).also { + checkKnown("removedAcls", it).add(removedAcl) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AclBatchUpdateResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .addedAcls() + * .removedAcls() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AclBatchUpdateResponse = + AclBatchUpdateResponse( + checkRequired("addedAcls", addedAcls).map { it.toImmutable() }, + checkRequired("removedAcls", removedAcls).map { it.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 + } + + return other is AclBatchUpdateResponse && + addedAcls == other.addedAcls && + removedAcls == other.removedAcls && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(addedAcls, removedAcls, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AclBatchUpdateResponse{addedAcls=$addedAcls, removedAcls=$removedAcls, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..93d86eaf --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclCreateParams.kt @@ -0,0 +1,923 @@ +// 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.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.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 + +/** + * Create a new acl. If there is an existing acl with the same contents as the one specified in the + * request, will return the existing acl unmodified + */ +class AclCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The id of the object 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 objectId(): String = body.objectId() + + /** + * 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 = body.objectType() + + /** + * 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(): Optional = body.groupId() + + /** + * Permission 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 permission(): Optional = body.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 = body.restrictObjectType() + + /** + * 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 = body.roleId() + + /** + * 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 userId(): Optional = body.userId() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + /** + * Returns the raw JSON value of [groupId]. + * + * Unlike [groupId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _groupId(): JsonField = body._groupId() + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _permission(): JsonField = body._permission() + + /** + * Returns the raw JSON value of [restrictObjectType]. + * + * Unlike [restrictObjectType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _restrictObjectType(): JsonField = body._restrictObjectType() + + /** + * Returns the raw JSON value of [roleId]. + * + * Unlike [roleId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _roleId(): JsonField = body._roleId() + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _userId(): JsonField = body._userId() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AclCreateParams]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @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() + } + + /** + * 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] + * - [groupId] + * - [permission] + * - [restrictObjectType] + * - etc. + */ + 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) } + + /** + * 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 object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(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 { body.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?) = apply { body.groupId(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 { 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()) + + /** + * 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 { 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`. + */ + fun restrictObjectType(restrictObjectType: AclObjectType?) = apply { + body.restrictObjectType(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 { + body.restrictObjectType(restrictObjectType) + } + + /** + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + */ + fun roleId(roleId: String?) = apply { body.roleId(roleId) } + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * 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 { body.roleId(roleId) } + + /** + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided + */ + fun userId(userId: String?) = apply { body.userId(userId) } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { body.userId(userId) } + + 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 [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. + */ + fun build(): AclCreateParams = + AclCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** + * 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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(), + ) + + /** + * The id of the object 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 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") + + /** + * 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(): Optional = groupId.getOptional("group_id") + + /** + * Permission 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 permission(): Optional = permission.getOptional("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") + + /** + * 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") + + /** + * 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 userId(): Optional = userId.getOptional("user_id") + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [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.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)) + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * 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 } + + /** + * 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)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = 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 + } + + return 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + additionalProperties, + ) + } + + 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 { + if (this === other) { + return true + } + + return other is AclCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AclCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..1e13b46a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete an acl object by its id */ +class AclDeleteParams +private constructor( + private val aclId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** Acl id */ + fun aclId(): Optional = Optional.ofNullable(aclId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AclDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AclDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclDeleteParams]. */ + class Builder internal constructor() { + + private var aclId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aclDeleteParams: AclDeleteParams) = apply { + aclId = aclDeleteParams.aclId + additionalHeaders = aclDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = aclDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = aclDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** Acl id */ + fun aclId(aclId: String?) = apply { this.aclId = aclId } + + /** Alias for calling [Builder.aclId] with `aclId.orElse(null)`. */ + fun aclId(aclId: Optional) = aclId(aclId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [AclDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AclDeleteParams = + AclDeleteParams( + aclId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is AclDeleteParams && + aclId == other.aclId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(aclId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "AclDeleteParams{aclId=$aclId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100644 index 00000000..4241a5ff --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParams.kt @@ -0,0 +1,924 @@ +// 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.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.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 + +/** Delete a single acl */ +class AclFindAndDeleteParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * The id of the object 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 objectId(): String = body.objectId() + + /** + * 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 = body.objectType() + + /** + * 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(): Optional = body.groupId() + + /** + * Permission 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 permission(): Optional = body.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 = body.restrictObjectType() + + /** + * 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 = body.roleId() + + /** + * 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 userId(): Optional = body.userId() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + /** + * Returns the raw JSON value of [groupId]. + * + * Unlike [groupId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _groupId(): JsonField = body._groupId() + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _permission(): JsonField = body._permission() + + /** + * Returns the raw JSON value of [restrictObjectType]. + * + * Unlike [restrictObjectType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _restrictObjectType(): JsonField = body._restrictObjectType() + + /** + * Returns the raw JSON value of [roleId]. + * + * Unlike [roleId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _roleId(): JsonField = body._roleId() + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _userId(): JsonField = body._userId() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AclFindAndDeleteParams]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @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() + } + + /** + * 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] + * - [groupId] + * - [permission] + * - [restrictObjectType] + * - etc. + */ + 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) } + + /** + * 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 object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(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 { body.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?) = apply { body.groupId(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 { 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()) + + /** + * 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 { 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`. + */ + fun restrictObjectType(restrictObjectType: AclObjectType?) = apply { + body.restrictObjectType(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 { + body.restrictObjectType(restrictObjectType) + } + + /** + * Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided + */ + fun roleId(roleId: String?) = apply { body.roleId(roleId) } + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * 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 { body.roleId(roleId) } + + /** + * Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be + * provided + */ + fun userId(userId: String?) = apply { body.userId(userId) } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { body.userId(userId) } + + 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** + * 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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(), + ) + + /** + * The id of the object 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 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") + + /** + * 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(): Optional = groupId.getOptional("group_id") + + /** + * Permission 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 permission(): Optional = permission.getOptional("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") + + /** + * 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") + + /** + * 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 userId(): Optional = userId.getOptional("user_id") + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [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.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)) + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * 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 } + + /** + * 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)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = 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 + } + + return 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + objectId, + objectType, + groupId, + permission, + restrictObjectType, + roleId, + userId, + additionalProperties, + ) + } + + 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 { + if (this === other) { + return true + } + + return other is AclFindAndDeleteParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AclFindAndDeleteParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..8938e4ed --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPage.kt @@ -0,0 +1,123 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.AclService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see AclService.list */ +class AclListPage +private constructor( + private val service: AclService, + private val params: AclListParams, + private val response: AclListPageResponse, +) : Page { + + /** + * Delegates to [AclListPageResponse], but gracefully handles missing data. + * + * @see AclListPageResponse.objects + */ + fun objects(): List = response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): AclListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): AclListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): AclListParams = params + + /** The response that this page was parsed from. */ + fun response(): AclListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AclListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclListPage]. */ + class Builder internal constructor() { + + private var service: AclService? = null + private var params: AclListParams? = null + private var response: AclListPageResponse? = null + + @JvmSynthetic + internal fun from(aclListPage: AclListPage) = apply { + service = aclListPage.service + params = aclListPage.params + response = aclListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AclListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..def7bff5 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageAsync.kt @@ -0,0 +1,137 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.AclServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see AclServiceAsync.list */ +class AclListPageAsync +private constructor( + private val service: AclServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: AclListParams, + private val response: AclListPageResponse, +) : PageAsync { + + /** + * Delegates to [AclListPageResponse], but gracefully handles missing data. + * + * @see AclListPageResponse.objects + */ + fun objects(): List = response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): AclListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): AclListParams = params + + /** The response that this page was parsed from. */ + fun response(): AclListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AclListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclListPageAsync]. */ + class Builder internal constructor() { + + private var service: AclServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: AclListParams? = null + private var response: AclListPageResponse? = null + + @JvmSynthetic + internal fun from(aclListPageAsync: AclListPageAsync) = apply { + service = aclListPageAsync.service + streamHandlerExecutor = aclListPageAsync.streamHandlerExecutor + params = aclListPageAsync.params + response = aclListPageAsync.response + } + + fun service(service: AclServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AclListPageAsync = + AclListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AclListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "AclListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..b1cc5192 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListPageResponse.kt @@ -0,0 +1,193 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is AclListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..d0fefc9b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclListParams.kt @@ -0,0 +1,410 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all acls. The acls are sorted by creation date, with the most recently-created acls + * coming first + */ +class AclListParams +private constructor( + private val objectId: String, + private val objectType: AclObjectType, + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** The id of the object the ACL applies to */ + fun objectId(): String = objectId + + /** The object type that the ACL applies to */ + fun objectType(): AclObjectType = objectType + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AclListParams]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclListParams]. */ + class Builder internal constructor() { + + private var objectId: String? = null + private var objectType: AclObjectType? = null + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(aclListParams: AclListParams) = apply { + objectId = aclListParams.objectId + objectType = aclListParams.objectType + endingBefore = aclListParams.endingBefore + ids = aclListParams.ids + limit = aclListParams.limit + startingAfter = aclListParams.startingAfter + additionalHeaders = aclListParams.additionalHeaders.toBuilder() + additionalQueryParams = aclListParams.additionalQueryParams.toBuilder() + } + + /** The id of the object the ACL applies to */ + fun objectId(objectId: String) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { this.objectType = objectType } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [AclListParams]. + * + * 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(): AclListParams = + AclListParams( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + endingBefore, + ids, + limit, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AclListParams && + objectId == other.objectId && + objectType == other.objectType && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + objectId, + objectType, + endingBefore, + ids, + limit, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "AclListParams{objectId=$objectId, objectType=$objectType, endingBefore=$endingBefore, ids=$ids, limit=$limit, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..d70f1270 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclObjectType.kt @@ -0,0 +1,188 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.errors.BraintrustInvalidDataException +import com.fasterxml.jackson.annotation.JsonCreator + +/** The object type that the ACL applies to */ +class AclObjectType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ORGANIZATION = of("organization") + + @JvmField val PROJECT = of("project") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val DATASET = of("dataset") + + @JvmField val PROMPT = of("prompt") + + @JvmField val PROMPT_SESSION = of("prompt_session") + + @JvmField val GROUP = of("group") + + @JvmField val ROLE = of("role") + + @JvmField val ORG_MEMBER = of("org_member") + + @JvmField val PROJECT_LOG = of("project_log") + + @JvmField val ORG_PROJECT = of("org_project") + + @JvmStatic fun of(value: String) = AclObjectType(JsonField.of(value)) + } + + /** An enum containing [AclObjectType]'s known values. */ + enum class Known { + ORGANIZATION, + PROJECT, + EXPERIMENT, + DATASET, + PROMPT, + PROMPT_SESSION, + GROUP, + ROLE, + ORG_MEMBER, + PROJECT_LOG, + ORG_PROJECT, + } + + /** + * An enum containing [AclObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [AclObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ORGANIZATION, + PROJECT, + EXPERIMENT, + DATASET, + PROMPT, + PROMPT_SESSION, + GROUP, + ROLE, + ORG_MEMBER, + PROJECT_LOG, + ORG_PROJECT, + /** + * An enum member indicating that [AclObjectType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + ORGANIZATION -> Value.ORGANIZATION + PROJECT -> Value.PROJECT + EXPERIMENT -> Value.EXPERIMENT + DATASET -> Value.DATASET + PROMPT -> Value.PROMPT + PROMPT_SESSION -> Value.PROMPT_SESSION + GROUP -> Value.GROUP + ROLE -> Value.ROLE + ORG_MEMBER -> Value.ORG_MEMBER + PROJECT_LOG -> Value.PROJECT_LOG + ORG_PROJECT -> Value.ORG_PROJECT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + ORGANIZATION -> Known.ORGANIZATION + PROJECT -> Known.PROJECT + EXPERIMENT -> Known.EXPERIMENT + DATASET -> Known.DATASET + PROMPT -> Known.PROMPT + PROMPT_SESSION -> Known.PROMPT_SESSION + GROUP -> Known.GROUP + ROLE -> Known.ROLE + ORG_MEMBER -> Known.ORG_MEMBER + PROJECT_LOG -> Known.PROJECT_LOG + ORG_PROJECT -> Known.ORG_PROJECT + else -> throw BraintrustInvalidDataException("Unknown AclObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + 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 + } + + return other is AclObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} 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 new file mode 100755 index 00000000..553c84c3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AclRetrieveParams.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get an acl object by its id */ +class AclRetrieveParams +private constructor( + private val aclId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Acl id */ + fun aclId(): Optional = Optional.ofNullable(aclId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AclRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AclRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AclRetrieveParams]. */ + class Builder internal constructor() { + + private var aclId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(aclRetrieveParams: AclRetrieveParams) = apply { + aclId = aclRetrieveParams.aclId + additionalHeaders = aclRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = aclRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Acl id */ + fun aclId(aclId: String?) = apply { this.aclId = aclId } + + /** Alias for calling [Builder.aclId] with `aclId.orElse(null)`. */ + fun aclId(aclId: Optional) = aclId(aclId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [AclRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AclRetrieveParams = + AclRetrieveParams(aclId, additionalHeaders.build(), additionalQueryParams.build()) + } + + 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 + } + + return other is AclRetrieveParams && + aclId == other.aclId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(aclId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AclRetrieveParams{aclId=$aclId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..0fa8596a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretCreateParams.kt @@ -0,0 +1,811 @@ +// 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.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.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 + +/** + * Create a new ai_secret. If there is an existing ai_secret with the same name as the one specified + * in the request, will return the existing ai_secret unmodified + */ +class AiSecretCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.name() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.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(): Optional = body.orgName() + + /** + * 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(): Optional = body.secret() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = body.type() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _secret(): JsonField = body._secret() + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _type(): JsonField = body._type() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AiSecretCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** + * 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] + * - [metadata] + * - [orgName] + * - [secret] + * - [type] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the AI secret */ + 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) } + + 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) } + + /** + * 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?) = 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) } + + /** + * Secret value. If omitted in a PUT request, the existing secret value will be left intact, + * not replaced with null. + */ + fun secret(secret: String?) = apply { body.secret(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 { body.secret(secret) } + + fun type(type: String?) = apply { body.type(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 { body.type(type) } + + 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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()) + + /** + * 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") + + /** + * @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") + + /** + * 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") + + /** + * 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(): 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 [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 [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 [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + /** + * 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 = + 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)) + + /** + * 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 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 } + + /** + * 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 } + + /** + * 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)) + + /** 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. + * + * 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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + metadata().ifPresent { it.validate() } + orgName() + 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 = + (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + metadata == other.metadata && + orgName == other.orgName && + secret == other.secret && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, metadata, orgName, secret, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, metadata=$metadata, orgName=$orgName, 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 { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiSecretCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AiSecretCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..61a67496 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete an ai_secret object by its id */ +class AiSecretDeleteParams +private constructor( + private val aiSecretId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** AiSecret id */ + fun aiSecretId(): Optional = Optional.ofNullable(aiSecretId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AiSecretDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AiSecretDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretDeleteParams]. */ + class Builder internal constructor() { + + private var aiSecretId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(aiSecretDeleteParams: AiSecretDeleteParams) = apply { + aiSecretId = aiSecretDeleteParams.aiSecretId + additionalHeaders = aiSecretDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = aiSecretDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = aiSecretDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** AiSecret id */ + fun aiSecretId(aiSecretId: String?) = apply { this.aiSecretId = aiSecretId } + + /** Alias for calling [Builder.aiSecretId] with `aiSecretId.orElse(null)`. */ + fun aiSecretId(aiSecretId: Optional) = aiSecretId(aiSecretId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [AiSecretDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiSecretDeleteParams = + AiSecretDeleteParams( + aiSecretId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is AiSecretDeleteParams && + aiSecretId == other.aiSecretId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(aiSecretId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "AiSecretDeleteParams{aiSecretId=$aiSecretId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100644 index 00000000..7e4aa36a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParams.kt @@ -0,0 +1,497 @@ +// 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.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.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 + +/** Delete a single ai_secret */ +class AiSecretFindAndDeleteParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.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 = body.orgName() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AiSecretFindAndDeleteParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretFindAndDeleteParams]. */ + 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(aiSecretFindAndDeleteParams: AiSecretFindAndDeleteParams) = apply { + body = aiSecretFindAndDeleteParams.body.toBuilder() + additionalHeaders = aiSecretFindAndDeleteParams.additionalHeaders.toBuilder() + 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) } + + /** + * 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) } + + /** + * 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?) = 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) + } + + 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 [AiSecretFindAndDeleteParams]. + * + * 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(): AiSecretFindAndDeleteParams = + AiSecretFindAndDeleteParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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 other is Body && + name == other.name && + orgName == other.orgName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } + + 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 + } + + return other is AiSecretFindAndDeleteParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AiSecretFindAndDeleteParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..b3de4d4f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPage.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.AiSecretService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see AiSecretService.list */ +class AiSecretListPage +private constructor( + private val service: AiSecretService, + private val params: AiSecretListParams, + private val response: AiSecretListPageResponse, +) : Page { + + /** + * Delegates to [AiSecretListPageResponse], but gracefully handles missing data. + * + * @see AiSecretListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): AiSecretListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): AiSecretListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): AiSecretListParams = params + + /** The response that this page was parsed from. */ + fun response(): AiSecretListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AiSecretListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretListPage]. */ + class Builder internal constructor() { + + private var service: AiSecretService? = null + private var params: AiSecretListParams? = null + private var response: AiSecretListPageResponse? = null + + @JvmSynthetic + internal fun from(aiSecretListPage: AiSecretListPage) = apply { + service = aiSecretListPage.service + params = aiSecretListPage.params + response = aiSecretListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiSecretListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100644 index 00000000..535d9386 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageAsync.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.AiSecretServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see AiSecretServiceAsync.list */ +class AiSecretListPageAsync +private constructor( + private val service: AiSecretServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: AiSecretListParams, + private val response: AiSecretListPageResponse, +) : PageAsync { + + /** + * Delegates to [AiSecretListPageResponse], but gracefully handles missing data. + * + * @see AiSecretListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): AiSecretListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): AiSecretListParams = params + + /** The response that this page was parsed from. */ + fun response(): AiSecretListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AiSecretListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretListPageAsync]. */ + class Builder internal constructor() { + + private var service: AiSecretServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: AiSecretListParams? = null + private var response: AiSecretListPageResponse? = null + + @JvmSynthetic + internal fun from(aiSecretListPageAsync: AiSecretListPageAsync) = apply { + service = aiSecretListPageAsync.service + streamHandlerExecutor = aiSecretListPageAsync.streamHandlerExecutor + params = aiSecretListPageAsync.params + response = aiSecretListPageAsync.response + } + + fun service(service: AiSecretServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AiSecretListPageAsync = + AiSecretListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiSecretListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "AiSecretListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..5d469b49 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is AiSecretListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100644 index 00000000..d57cd54f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretListParams.kt @@ -0,0 +1,495 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +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 + */ +class AiSecretListParams +private constructor( + private val aiSecretName: String?, + private val aiSecretType: AiSecretType?, + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Name of the ai_secret to search for */ + fun aiSecretName(): Optional = Optional.ofNullable(aiSecretName) + + fun aiSecretType(): Optional = Optional.ofNullable(aiSecretType) + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AiSecretListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AiSecretListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretListParams]. */ + class Builder internal constructor() { + + private var aiSecretName: String? = null + private var aiSecretType: AiSecretType? = null + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(aiSecretListParams: AiSecretListParams) = apply { + aiSecretName = aiSecretListParams.aiSecretName + aiSecretType = aiSecretListParams.aiSecretType + endingBefore = aiSecretListParams.endingBefore + ids = aiSecretListParams.ids + limit = aiSecretListParams.limit + orgName = aiSecretListParams.orgName + startingAfter = aiSecretListParams.startingAfter + additionalHeaders = aiSecretListParams.additionalHeaders.toBuilder() + additionalQueryParams = aiSecretListParams.additionalQueryParams.toBuilder() + } + + /** Name of the ai_secret to search for */ + fun aiSecretName(aiSecretName: String?) = apply { this.aiSecretName = aiSecretName } + + /** Alias for calling [Builder.aiSecretName] with `aiSecretName.orElse(null)`. */ + fun aiSecretName(aiSecretName: Optional) = aiSecretName(aiSecretName.getOrNull()) + + fun aiSecretType(aiSecretType: AiSecretType?) = apply { this.aiSecretType = aiSecretType } + + /** Alias for calling [Builder.aiSecretType] with `aiSecretType.orElse(null)`. */ + fun aiSecretType(aiSecretType: Optional) = + aiSecretType(aiSecretType.getOrNull()) + + /** Alias for calling [aiSecretType] with `AiSecretType.ofString(string)`. */ + fun aiSecretType(string: String) = aiSecretType(AiSecretType.ofString(string)) + + /** Alias for calling [aiSecretType] with `AiSecretType.ofStrings(strings)`. */ + fun aiSecretTypeOfStrings(strings: List) = + aiSecretType(AiSecretType.ofStrings(strings)) + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [AiSecretListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiSecretListParams = + AiSecretListParams( + aiSecretName, + aiSecretType, + endingBefore, + ids, + limit, + orgName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid AiSecretType") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiSecretType && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "AiSecretType{string=$string}" + strings != null -> "AiSecretType{strings=$strings}" + else -> throw IllegalStateException("Invalid AiSecretType") + } + + companion object { + + @JvmStatic fun ofString(string: String) = AiSecretType(string = string) + + @JvmStatic + fun ofStrings(strings: List) = AiSecretType(strings = strings.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [AiSecretType] to a value of type + * [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiSecretListParams && + aiSecretName == other.aiSecretName && + aiSecretType == other.aiSecretType && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + aiSecretName, + aiSecretType, + endingBefore, + ids, + limit, + orgName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "AiSecretListParams{aiSecretName=$aiSecretName, aiSecretType=$aiSecretType, endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..b73cb945 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretReplaceParams.kt @@ -0,0 +1,811 @@ +// 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.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.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 + +/** + * Create or replace ai_secret. If there is an existing ai_secret with the same name as the one + * specified in the request, will replace the existing ai_secret with the provided fields + */ +class AiSecretReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.name() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.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(): Optional = body.orgName() + + /** + * 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(): Optional = body.secret() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = body.type() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _secret(): JsonField = body._secret() + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _type(): JsonField = body._type() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [AiSecretReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** + * 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] + * - [metadata] + * - [orgName] + * - [secret] + * - [type] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the AI secret */ + 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) } + + 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) } + + /** + * 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?) = 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) } + + /** + * Secret value. If omitted in a PUT request, the existing secret value will be left intact, + * not replaced with null. + */ + fun secret(secret: String?) = apply { body.secret(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 { body.secret(secret) } + + fun type(type: String?) = apply { body.type(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 { body.type(type) } + + 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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()) + + /** + * 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") + + /** + * @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") + + /** + * 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") + + /** + * 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(): 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 [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 [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 [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + /** + * 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 = + 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)) + + /** + * 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 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 } + + /** + * 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 } + + /** + * 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)) + + /** 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. + * + * 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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + metadata().ifPresent { it.validate() } + orgName() + 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 = + (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + metadata == other.metadata && + orgName == other.orgName && + secret == other.secret && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, metadata, orgName, secret, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, metadata=$metadata, orgName=$orgName, 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 { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiSecretReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AiSecretReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..c52011db --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParams.kt @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get an ai_secret object by its id */ +class AiSecretRetrieveParams +private constructor( + private val aiSecretId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** AiSecret id */ + fun aiSecretId(): Optional = Optional.ofNullable(aiSecretId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AiSecretRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AiSecretRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretRetrieveParams]. */ + class Builder internal constructor() { + + private var aiSecretId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(aiSecretRetrieveParams: AiSecretRetrieveParams) = apply { + aiSecretId = aiSecretRetrieveParams.aiSecretId + additionalHeaders = aiSecretRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = aiSecretRetrieveParams.additionalQueryParams.toBuilder() + } + + /** AiSecret id */ + fun aiSecretId(aiSecretId: String?) = apply { this.aiSecretId = aiSecretId } + + /** Alias for calling [Builder.aiSecretId] with `aiSecretId.orElse(null)`. */ + fun aiSecretId(aiSecretId: Optional) = aiSecretId(aiSecretId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [AiSecretRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiSecretRetrieveParams = + AiSecretRetrieveParams( + aiSecretId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is AiSecretRetrieveParams && + aiSecretId == other.aiSecretId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(aiSecretId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AiSecretRetrieveParams{aiSecretId=$aiSecretId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..6bd772e6 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/AiSecretUpdateParams.kt @@ -0,0 +1,711 @@ +// 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.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +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 + +/** + * Partially update an ai_secret object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ +class AiSecretUpdateParams +private constructor( + private val aiSecretId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** AiSecret id */ + fun aiSecretId(): Optional = Optional.ofNullable(aiSecretId) + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.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 = body.name() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun secret(): Optional = body.secret() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun type(): Optional = body.type() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [secret]. + * + * Unlike [secret], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _secret(): JsonField = body._secret() + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _type(): JsonField = body._type() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): AiSecretUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [AiSecretUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AiSecretUpdateParams]. */ + class Builder internal constructor() { + + private var aiSecretId: 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(aiSecretUpdateParams: AiSecretUpdateParams) = apply { + aiSecretId = aiSecretUpdateParams.aiSecretId + body = aiSecretUpdateParams.body.toBuilder() + additionalHeaders = aiSecretUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = aiSecretUpdateParams.additionalQueryParams.toBuilder() + } + + /** AiSecret id */ + fun aiSecretId(aiSecretId: String?) = apply { this.aiSecretId = aiSecretId } + + /** Alias for calling [Builder.aiSecretId] with `aiSecretId.orElse(null)`. */ + fun aiSecretId(aiSecretId: Optional) = aiSecretId(aiSecretId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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)`. */ + 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 AI secret */ + 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) } + + fun secret(secret: String?) = apply { body.secret(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 { body.secret(secret) } + + fun type(type: String?) = apply { body.type(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 { body.type(type) } + + 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 [AiSecretUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): AiSecretUpdateParams = + AiSecretUpdateParams( + aiSecretId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = + 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(): 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 other is Body && + metadata == other.metadata && + name == other.name && + secret == other.secret && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(metadata, name, secret, type, additionalProperties) + } + + 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 { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is AiSecretUpdateParams && + aiSecretId == other.aiSecretId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(aiSecretId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "AiSecretUpdateParams{aiSecretId=$aiSecretId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..4d05c260 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKey.kt @@ -0,0 +1,368 @@ +// 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.checkRequired +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 + +class ApiKey +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * Name of the api key + * + * @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") + + /** + * @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 previewName(): String = previewName.getRequired("preview_name") + + /** + * Date of api key creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Unique identifier for the organization + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun orgId(): Optional = orgId.getOptional("org_id") + + /** + * Unique identifier for the user + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [previewName]. + * + * Unlike [previewName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("preview_name") + @ExcludeMissing + fun _previewName(): JsonField = previewName + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ApiKey]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .previewName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKey]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var previewName: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var orgId: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(apiKey: ApiKey) = apply { + id = apiKey.id + name = apiKey.name + previewName = apiKey.previewName + created = apiKey.created + orgId = apiKey.orgId + userId = apiKey.userId + additionalProperties = apiKey.additionalProperties.toMutableMap() + } + + /** Unique identifier for the api key */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the api key */ + 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 previewName(previewName: String) = previewName(JsonField.of(previewName)) + + /** + * Sets [Builder.previewName] to an arbitrary JSON value. + * + * You should usually call [Builder.previewName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun previewName(previewName: JsonField) = apply { this.previewName = previewName } + + /** Date of api key creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Unique identifier for the organization */ + 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 } + + /** Unique identifier for the user */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ApiKey]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .previewName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ApiKey = + ApiKey( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("previewName", previewName), + created, + orgId, + userId, + 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 + } + + return other is ApiKey && + id == other.id && + name == other.name && + previewName == other.previewName && + created == other.created && + orgId == other.orgId && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, name, previewName, created, orgId, userId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ApiKey{id=$id, name=$name, previewName=$previewName, created=$created, orgId=$orgId, userId=$userId, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..5d6c5394 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyCreateParams.kt @@ -0,0 +1,500 @@ +// 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.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.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 + +/** + * Create a new api_key. It is possible to have multiple API keys with the same name. There is no + * de-duplication + */ +class ApiKeyCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.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 = body.orgName() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ApiKeyCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKeyCreateParams]. */ + 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(apiKeyCreateParams: ApiKeyCreateParams) = apply { + body = apiKeyCreateParams.body.toBuilder() + additionalHeaders = apiKeyCreateParams.additionalHeaders.toBuilder() + 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) } + + /** + * 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) } + + /** + * 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?) = 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) + } + + 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 [ApiKeyCreateParams]. + * + * 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(): ApiKeyCreateParams = + ApiKeyCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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 other is Body && + name == other.name && + orgName == other.orgName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } + + 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 + } + + return other is ApiKeyCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ApiKeyCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..f3add49a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete an api_key object by its id */ +class ApiKeyDeleteParams +private constructor( + private val apiKeyId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** ApiKey id */ + fun apiKeyId(): Optional = Optional.ofNullable(apiKeyId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ApiKeyDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ApiKeyDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKeyDeleteParams]. */ + class Builder internal constructor() { + + private var apiKeyId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(apiKeyDeleteParams: ApiKeyDeleteParams) = apply { + apiKeyId = apiKeyDeleteParams.apiKeyId + additionalHeaders = apiKeyDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = apiKeyDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = apiKeyDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** ApiKey id */ + fun apiKeyId(apiKeyId: String?) = apply { this.apiKeyId = apiKeyId } + + /** Alias for calling [Builder.apiKeyId] with `apiKeyId.orElse(null)`. */ + fun apiKeyId(apiKeyId: Optional) = apiKeyId(apiKeyId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [ApiKeyDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ApiKeyDeleteParams = + ApiKeyDeleteParams( + apiKeyId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is ApiKeyDeleteParams && + apiKeyId == other.apiKeyId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(apiKeyId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "ApiKeyDeleteParams{apiKeyId=$apiKeyId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100644 index 00000000..230a76da --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPage.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.ApiKeyService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see ApiKeyService.list */ +class ApiKeyListPage +private constructor( + private val service: ApiKeyService, + private val params: ApiKeyListParams, + private val response: ApiKeyListPageResponse, +) : Page { + + /** + * Delegates to [ApiKeyListPageResponse], but gracefully handles missing data. + * + * @see ApiKeyListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ApiKeyListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): ApiKeyListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): ApiKeyListParams = params + + /** The response that this page was parsed from. */ + fun response(): ApiKeyListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ApiKeyListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKeyListPage]. */ + class Builder internal constructor() { + + private var service: ApiKeyService? = null + private var params: ApiKeyListParams? = null + private var response: ApiKeyListPageResponse? = null + + @JvmSynthetic + internal fun from(apiKeyListPage: ApiKeyListPage) = apply { + service = apiKeyListPage.service + params = apiKeyListPage.params + response = apiKeyListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ApiKeyListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100644 index 00000000..4cb580a2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageAsync.kt @@ -0,0 +1,138 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.ApiKeyServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see ApiKeyServiceAsync.list */ +class ApiKeyListPageAsync +private constructor( + private val service: ApiKeyServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: ApiKeyListParams, + private val response: ApiKeyListPageResponse, +) : PageAsync { + + /** + * Delegates to [ApiKeyListPageResponse], but gracefully handles missing data. + * + * @see ApiKeyListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ApiKeyListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): ApiKeyListParams = params + + /** The response that this page was parsed from. */ + fun response(): ApiKeyListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ApiKeyListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKeyListPageAsync]. */ + class Builder internal constructor() { + + private var service: ApiKeyServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ApiKeyListParams? = null + private var response: ApiKeyListPageResponse? = null + + @JvmSynthetic + internal fun from(apiKeyListPageAsync: ApiKeyListPageAsync) = apply { + service = apiKeyListPageAsync.service + streamHandlerExecutor = apiKeyListPageAsync.streamHandlerExecutor + params = apiKeyListPageAsync.params + response = apiKeyListPageAsync.response + } + + fun service(service: ApiKeyServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ApiKeyListPageAsync = + ApiKeyListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ApiKeyListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "ApiKeyListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..367f30ff --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListPageResponse.kt @@ -0,0 +1,193 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is ApiKeyListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100644 index 00000000..8615dda7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyListParams.kt @@ -0,0 +1,401 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +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 + */ +class ApiKeyListParams +private constructor( + private val apiKeyName: String?, + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Name of the api_key to search for */ + fun apiKeyName(): Optional = Optional.ofNullable(apiKeyName) + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ApiKeyListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ApiKeyListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKeyListParams]. */ + class Builder internal constructor() { + + private var apiKeyName: String? = null + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(apiKeyListParams: ApiKeyListParams) = apply { + apiKeyName = apiKeyListParams.apiKeyName + endingBefore = apiKeyListParams.endingBefore + ids = apiKeyListParams.ids + limit = apiKeyListParams.limit + orgName = apiKeyListParams.orgName + startingAfter = apiKeyListParams.startingAfter + additionalHeaders = apiKeyListParams.additionalHeaders.toBuilder() + additionalQueryParams = apiKeyListParams.additionalQueryParams.toBuilder() + } + + /** Name of the api_key to search for */ + fun apiKeyName(apiKeyName: String?) = apply { this.apiKeyName = apiKeyName } + + /** Alias for calling [Builder.apiKeyName] with `apiKeyName.orElse(null)`. */ + fun apiKeyName(apiKeyName: Optional) = apiKeyName(apiKeyName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ApiKeyListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ApiKeyListParams = + ApiKeyListParams( + apiKeyName, + endingBefore, + ids, + limit, + orgName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ApiKeyListParams && + apiKeyName == other.apiKeyName && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + apiKeyName, + endingBefore, + ids, + limit, + orgName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ApiKeyListParams{apiKeyName=$apiKeyName, endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..4a7aa490 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParams.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get an api_key object by its id */ +class ApiKeyRetrieveParams +private constructor( + private val apiKeyId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** ApiKey id */ + fun apiKeyId(): Optional = Optional.ofNullable(apiKeyId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ApiKeyRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ApiKeyRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ApiKeyRetrieveParams]. */ + class Builder internal constructor() { + + private var apiKeyId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(apiKeyRetrieveParams: ApiKeyRetrieveParams) = apply { + apiKeyId = apiKeyRetrieveParams.apiKeyId + additionalHeaders = apiKeyRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = apiKeyRetrieveParams.additionalQueryParams.toBuilder() + } + + /** ApiKey id */ + fun apiKeyId(apiKeyId: String?) = apply { this.apiKeyId = apiKeyId } + + /** Alias for calling [Builder.apiKeyId] with `apiKeyId.orElse(null)`. */ + fun apiKeyId(apiKeyId: Optional) = apiKeyId(apiKeyId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ApiKeyRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ApiKeyRetrieveParams = + ApiKeyRetrieveParams(apiKeyId, additionalHeaders.build(), additionalQueryParams.build()) + } + + 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 + } + + return other is ApiKeyRetrieveParams && + apiKeyId == other.apiKeyId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(apiKeyId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ApiKeyRetrieveParams{apiKeyId=$apiKeyId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..eb663486 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImage.kt @@ -0,0 +1,653 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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 + +class ChatCompletionContentPartImage +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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). + */ + fun imageUrl(): ImageUrl = imageUrl.getRequired("image_url") + + /** + * @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") + + /** + * Returns the raw JSON value of [imageUrl]. + * + * Unlike [imageUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("image_url") @ExcludeMissing fun _imageUrl(): JsonField = imageUrl + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionContentPartImage]. + * + * The following fields are required: + * ```java + * .imageUrl() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionContentPartImage]. */ + class Builder internal constructor() { + + private var imageUrl: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionContentPartImage: ChatCompletionContentPartImage) = apply { + imageUrl = chatCompletionContentPartImage.imageUrl + type = chatCompletionContentPartImage.type + additionalProperties = + chatCompletionContentPartImage.additionalProperties.toMutableMap() + } + + fun imageUrl(imageUrl: ImageUrl) = imageUrl(JsonField.of(imageUrl)) + + /** + * Sets [Builder.imageUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.imageUrl] with a well-typed [ImageUrl] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun imageUrl(imageUrl: JsonField) = apply { this.imageUrl = imageUrl } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionContentPartImage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .imageUrl() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionContentPartImage = + ChatCompletionContentPartImage( + checkRequired("imageUrl", imageUrl), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val url: JsonField, + private val detail: JsonField, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("url") @ExcludeMissing url: JsonField = JsonMissing.of(), + @JsonProperty("detail") @ExcludeMissing detail: JsonField = JsonMissing.of(), + ) : this(url, detail, mutableMapOf()) + + /** + * @throws 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 url(): String = url.getRequired("url") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun detail(): Optional = detail.getOptional("detail") + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [detail]. + * + * Unlike [detail], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("detail") @ExcludeMissing fun _detail(): JsonField = detail + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ImageUrl]. + * + * The following fields are required: + * ```java + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ImageUrl]. */ + class Builder internal constructor() { + + private var url: JsonField? = null + private var detail: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(imageUrl: ImageUrl) = apply { + url = imageUrl.url + detail = imageUrl.detail + additionalProperties = imageUrl.additionalProperties.toMutableMap() + } + + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + fun detail(detail: Detail) = detail(JsonField.of(detail)) + + /** + * Sets [Builder.detail] to an arbitrary JSON value. + * + * You should usually call [Builder.detail] with a well-typed [Detail] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun detail(detail: JsonField) = apply { this.detail = detail } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ImageUrl]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ImageUrl = + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val LOW = of("low") + + @JvmField val HIGH = of("high") + + @JvmStatic fun of(value: String) = Detail(JsonField.of(value)) + } + + /** An enum containing [Detail]'s known values. */ + enum class Known { + AUTO, + LOW, + HIGH, + } + + /** + * An enum containing [Detail]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Detail] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + LOW, + HIGH, + /** + * An enum member indicating that [Detail] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + LOW -> Value.LOW + HIGH -> Value.HIGH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + LOW -> Known.LOW + HIGH -> Known.HIGH + else -> throw BraintrustInvalidDataException("Unknown Detail: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Detail && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ImageUrl && + url == other.url && + detail == other.detail && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(url, detail, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ImageUrl{url=$url, detail=$detail, additionalProperties=$additionalProperties}" + } + + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val IMAGE_URL = of("image_url") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + IMAGE_URL + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + IMAGE_URL, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + IMAGE_URL -> Value.IMAGE_URL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + IMAGE_URL -> Known.IMAGE_URL + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionContentPartImage && + imageUrl == other.imageUrl && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(imageUrl, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionContentPartImage{imageUrl=$imageUrl, type=$type, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..dfeea28c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartText.kt @@ -0,0 +1,327 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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 + +class ChatCompletionContentPartText +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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). + */ + fun type(): Type = type.getRequired("type") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun text(): Optional = text.getOptional("text") + + /** + * 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 + + /** + * Returns the raw JSON value of [text]. + * + * Unlike [text], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("text") @ExcludeMissing fun _text(): JsonField = text + + @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 + * [ChatCompletionContentPartText]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionContentPartText]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var text: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionContentPartText: ChatCompletionContentPartText) = apply { + type = chatCompletionContentPartText.type + text = chatCompletionContentPartText.text + additionalProperties = chatCompletionContentPartText.additionalProperties.toMutableMap() + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun text(text: String) = text(JsonField.of(text)) + + /** + * Sets [Builder.text] to an arbitrary JSON value. + * + * You should usually call [Builder.text] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun text(text: JsonField) = apply { this.text = text } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionContentPartText]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionContentPartText = + ChatCompletionContentPartText( + checkRequired("type", type), + text, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TEXT = of("text") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + TEXT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TEXT, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TEXT -> Value.TEXT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + TEXT -> Known.TEXT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionContentPartText && + type == other.type && + text == other.text && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, text, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionContentPartText{type=$type, text=$text, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..3f9bc106 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCall.kt @@ -0,0 +1,556 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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 ChatCompletionMessageToolCall +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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). + */ + fun id(): String = id.getRequired("id") + + /** + * @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 function(): Function = function.getRequired("function") + + /** + * @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") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [function]. + * + * Unlike [function], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("function") @ExcludeMissing fun _function(): JsonField = function + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [ChatCompletionMessageToolCall]. + * + * The following fields are required: + * ```java + * .id() + * .function() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChatCompletionMessageToolCall]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var function: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chatCompletionMessageToolCall: ChatCompletionMessageToolCall) = apply { + id = chatCompletionMessageToolCall.id + function = chatCompletionMessageToolCall.function + type = chatCompletionMessageToolCall.type + additionalProperties = chatCompletionMessageToolCall.additionalProperties.toMutableMap() + } + + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun function(function: Function) = function(JsonField.of(function)) + + /** + * Sets [Builder.function] to an arbitrary JSON value. + * + * You should usually call [Builder.function] with a well-typed [Function] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun function(function: JsonField) = apply { this.function = function } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ChatCompletionMessageToolCall]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .function() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ChatCompletionMessageToolCall = + ChatCompletionMessageToolCall( + checkRequired("id", id), + checkRequired("function", function), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun arguments(): String = arguments.getRequired("arguments") + + /** + * @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") + + /** + * Returns the raw JSON value of [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField = arguments + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .arguments() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var arguments: JsonField? = null + private var name: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + arguments = function.arguments + name = function.name + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun arguments(arguments: JsonField) = apply { this.arguments = arguments } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .arguments() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("arguments", arguments), + checkRequired("name", name), + 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 + } + + return other is Function && + arguments == other.arguments && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(arguments, name, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{arguments=$arguments, name=$name, additionalProperties=$additionalProperties}" + } + + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FUNCTION, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionMessageToolCall && + id == other.id && + function == other.function && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, function, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ChatCompletionMessageToolCall{id=$id, function=$function, type=$type, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..b21ccf20 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CodeBundle.kt @@ -0,0 +1,2299 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.allMaxBy +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.getOrThrow +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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class CodeBundle +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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). + */ + fun bundleId(): String = bundleId.getRequired("bundle_id") + + /** + * @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 location(): Location = location.getRequired("location") + + /** + * @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 runtimeContext(): RuntimeContext = runtimeContext.getRequired("runtime_context") + + /** + * A preview of the code + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun preview(): Optional = preview.getOptional("preview") + + /** + * Returns the raw JSON value of [bundleId]. + * + * Unlike [bundleId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("bundle_id") @ExcludeMissing fun _bundleId(): JsonField = bundleId + + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("location") @ExcludeMissing fun _location(): JsonField = location + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [preview]. + * + * Unlike [preview], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("preview") @ExcludeMissing fun _preview(): JsonField = preview + + @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 [CodeBundle]. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CodeBundle]. */ + class Builder internal constructor() { + + private var bundleId: JsonField? = null + private var location: JsonField? = null + private var runtimeContext: JsonField? = null + private var preview: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(codeBundle: CodeBundle) = apply { + bundleId = codeBundle.bundleId + location = codeBundle.location + runtimeContext = codeBundle.runtimeContext + preview = codeBundle.preview + additionalProperties = codeBundle.additionalProperties.toMutableMap() + } + + fun bundleId(bundleId: String) = bundleId(JsonField.of(bundleId)) + + /** + * Sets [Builder.bundleId] to an arbitrary JSON value. + * + * You should usually call [Builder.bundleId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun bundleId(bundleId: JsonField) = apply { this.bundleId = bundleId } + + fun location(location: Location) = location(JsonField.of(location)) + + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed [Location] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun location(location: JsonField) = apply { this.location = location } + + /** Alias for calling [location] with `Location.ofExperiment(experiment)`. */ + fun location(experiment: Location.Experiment) = location(Location.ofExperiment(experiment)) + + /** Alias for calling [location] with `Location.ofFunction(function)`. */ + fun location(function: Location.Function) = location(Location.ofFunction(function)) + + fun runtimeContext(runtimeContext: RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed [RuntimeContext] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = apply { + this.runtimeContext = runtimeContext + } + + /** A preview of the code */ + fun preview(preview: String?) = preview(JsonField.ofNullable(preview)) + + /** Alias for calling [Builder.preview] with `preview.orElse(null)`. */ + fun preview(preview: Optional) = preview(preview.getOrNull()) + + /** + * Sets [Builder.preview] to an arbitrary JSON value. + * + * You should usually call [Builder.preview] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun preview(preview: JsonField) = apply { this.preview = preview } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CodeBundle]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CodeBundle = + CodeBundle( + checkRequired("bundleId", bundleId), + checkRequired("location", location), + checkRequired("runtimeContext", runtimeContext), + preview, + 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 + private constructor( + private val experiment: Experiment? = null, + private val function: Function? = null, + private val _json: JsonValue? = null, + ) { + + fun experiment(): Optional = Optional.ofNullable(experiment) + + fun function(): Optional = Optional.ofNullable(function) + + fun isExperiment(): Boolean = experiment != null + + fun isFunction(): Boolean = function != null + + fun asExperiment(): Experiment = experiment.getOrThrow("experiment") + + fun asFunction(): Function = function.getOrThrow("function") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Location = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitExperiment(experiment: Experiment) { + experiment.validate() + } + + override fun visitFunction(function: Function) { + function.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 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 + } + + return other is Location && experiment == other.experiment && function == other.function + } + + override fun hashCode(): Int = Objects.hash(experiment, function) + + override fun toString(): String = + when { + experiment != null -> "Location{experiment=$experiment}" + function != null -> "Location{function=$function}" + _json != null -> "Location{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Location") + } + + companion object { + + @JvmStatic fun ofExperiment(experiment: Experiment) = Location(experiment = experiment) + + @JvmStatic fun ofFunction(function: Function) = Location(function = function) + } + + /** + * An interface that defines how to map each variant of [Location] to a value of type [T]. + */ + interface Visitor { + + fun visitExperiment(experiment: Experiment): T + + fun visitFunction(function: Function): T + + /** + * Maps an unknown variant of [Location] to a value of type [T]. + * + * An instance of [Location] 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 Location: $json") + } + } + + internal class Deserializer : BaseDeserializer(Location::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Location { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Location::class) { + + override fun serialize( + value: Location, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.experiment != null -> generator.writeObject(value.experiment) + value.function != null -> generator.writeObject(value.function) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Location") + } + } + } + + class Experiment + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun evalName(): String = evalName.getRequired("eval_name") + + /** + * @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 position(): Position = position.getRequired("position") + + /** + * @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") + + /** + * Returns the raw JSON value of [evalName]. + * + * Unlike [evalName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("eval_name") @ExcludeMissing fun _evalName(): JsonField = evalName + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("position") + @ExcludeMissing + fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Experiment]. + * + * The following fields are required: + * ```java + * .evalName() + * .position() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Experiment]. */ + class Builder internal constructor() { + + private var evalName: JsonField? = null + private var position: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(experiment: Experiment) = apply { + evalName = experiment.evalName + position = experiment.position + type = experiment.type + additionalProperties = experiment.additionalProperties.toMutableMap() + } + + fun evalName(evalName: String) = evalName(JsonField.of(evalName)) + + /** + * Sets [Builder.evalName] to an arbitrary JSON value. + * + * You should usually call [Builder.evalName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun evalName(evalName: JsonField) = apply { this.evalName = evalName } + + fun position(position: Position) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [Position] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + /** Alias for calling [position] with `Position.ofType(type)`. */ + fun position(type: Position.Type) = position(Position.ofType(type)) + + /** Alias for calling [position] with `Position.ofScorer(scorer)`. */ + fun position(scorer: Position.Scorer) = position(Position.ofScorer(scorer)) + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Experiment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .evalName() + * .position() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Experiment = + Experiment( + checkRequired("evalName", evalName), + checkRequired("position", position), + checkRequired("type", type), + 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 + private constructor( + private val type: Type? = null, + private val scorer: Scorer? = null, + private val _json: JsonValue? = null, + ) { + + fun type(): Optional = Optional.ofNullable(type) + + fun scorer(): Optional = Optional.ofNullable(scorer) + + fun isType(): Boolean = type != null + + fun isScorer(): Boolean = scorer != null + + fun asType(): Type = type.getOrThrow("type") + + fun asScorer(): Scorer = scorer.getOrThrow("scorer") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Position = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitType(type: Type) { + type.validate() + } + + override fun visitScorer(scorer: Scorer) { + scorer.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 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 + } + + return other is Position && type == other.type && scorer == other.scorer + } + + override fun hashCode(): Int = Objects.hash(type, scorer) + + override fun toString(): String = + when { + type != null -> "Position{type=$type}" + scorer != null -> "Position{scorer=$scorer}" + _json != null -> "Position{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Position") + } + + companion object { + + @JvmStatic fun ofType(type: Type) = Position(type = type) + + @JvmStatic fun ofScorer(scorer: Scorer) = Position(scorer = scorer) + } + + /** + * An interface that defines how to map each variant of [Position] to a value of + * type [T]. + */ + interface Visitor { + + fun visitType(type: Type): T + + fun visitScorer(scorer: Scorer): T + + /** + * Maps an unknown variant of [Position] to a value of type [T]. + * + * An instance of [Position] 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 Position: $json") + } + } + + internal class Deserializer : BaseDeserializer(Position::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Position { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Position::class) { + + override fun serialize( + value: Position, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.type != null -> generator.writeObject(value.type) + value.scorer != null -> generator.writeObject(value.scorer) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Position") + } + } + } + + class Type + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun type(): InnerType = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Type]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Type]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(type: Type) = apply { + this.type = type.type + additionalProperties = type.additionalProperties.toMutableMap() + } + + fun type(type: InnerType) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [InnerType] + * 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 [Type]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Type = + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val TASK = of("task") + + @JvmStatic fun of(value: String) = InnerType(JsonField.of(value)) + } + + /** An enum containing [InnerType]'s known values. */ + enum class Known { + TASK + } + + /** + * An enum containing [InnerType]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [InnerType] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TASK, + /** + * An enum member indicating that [InnerType] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TASK -> Value.TASK + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + TASK -> Known.TASK + else -> + throw BraintrustInvalidDataException( + "Unknown InnerType: $value" + ) + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is InnerType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Type{type=$type, additionalProperties=$additionalProperties}" + } + + class Scorer + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun index(): Long = index.getRequired("index") + + /** + * @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") + + /** + * Returns the raw JSON value of [index]. + * + * Unlike [index], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("index") @ExcludeMissing fun _index(): JsonField = index + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Scorer]. + * + * The following fields are required: + * ```java + * .index() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scorer]. */ + class Builder internal constructor() { + + private var index: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(scorer: Scorer) = apply { + index = scorer.index + type = scorer.type + additionalProperties = scorer.additionalProperties.toMutableMap() + } + + fun index(index: Long) = index(JsonField.of(index)) + + /** + * Sets [Builder.index] to an arbitrary JSON value. + * + * You should usually call [Builder.index] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun index(index: JsonField) = apply { this.index = index } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Scorer]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .index() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Scorer = + Scorer( + checkRequired("index", index), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val SCORER = of("scorer") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + SCORER + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SCORER, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SCORER -> Value.SCORER + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + SCORER -> Known.SCORER + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Scorer && + index == other.index && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(index, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Scorer{index=$index, type=$type, additionalProperties=$additionalProperties}" + } + } + + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EXPERIMENT = of("experiment") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + EXPERIMENT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EXPERIMENT, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EXPERIMENT -> Value.EXPERIMENT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + EXPERIMENT -> Known.EXPERIMENT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Experiment && + evalName == other.evalName && + position == other.position && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(evalName, position, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Experiment{evalName=$evalName, position=$position, type=$type, additionalProperties=$additionalProperties}" + } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun index(): Long = index.getRequired("index") + + /** + * @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") + + /** + * Returns the raw JSON value of [index]. + * + * Unlike [index], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("index") @ExcludeMissing fun _index(): JsonField = index + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .index() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var index: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + index = function.index + type = function.type + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun index(index: Long) = index(JsonField.of(index)) + + /** + * Sets [Builder.index] to an arbitrary JSON value. + * + * You should usually call [Builder.index] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun index(index: JsonField) = apply { this.index = index } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .index() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("index", index), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FUNCTION, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + index == other.index && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(index, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{index=$index, type=$type, additionalProperties=$additionalProperties}" + } + } + + class RuntimeContext + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun runtime(): Runtime = runtime.getRequired("runtime") + + /** + * @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 version(): String = version.getRequired("version") + + /** + * Returns the raw JSON value of [runtime]. + * + * Unlike [runtime], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("runtime") @ExcludeMissing fun _runtime(): JsonField = runtime + + /** + * 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 + + @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 [RuntimeContext]. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuntimeContext]. */ + class Builder internal constructor() { + + private var runtime: JsonField? = null + private var version: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(runtimeContext: RuntimeContext) = apply { + runtime = runtimeContext.runtime + version = runtimeContext.version + additionalProperties = runtimeContext.additionalProperties.toMutableMap() + } + + fun runtime(runtime: Runtime) = runtime(JsonField.of(runtime)) + + /** + * Sets [Builder.runtime] to an arbitrary JSON value. + * + * You should usually call [Builder.runtime] with a well-typed [Runtime] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun runtime(runtime: JsonField) = apply { this.runtime = runtime } + + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuntimeContext]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RuntimeContext = + RuntimeContext( + checkRequired("runtime", runtime), + checkRequired("version", version), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val NODE = of("node") + + @JvmField val PYTHON = of("python") + + @JvmStatic fun of(value: String) = Runtime(JsonField.of(value)) + } + + /** An enum containing [Runtime]'s known values. */ + enum class Known { + NODE, + PYTHON, + } + + /** + * An enum containing [Runtime]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Runtime] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + NODE, + PYTHON, + /** + * An enum member indicating that [Runtime] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + NODE -> Value.NODE + PYTHON -> Value.PYTHON + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + NODE -> Known.NODE + PYTHON -> Known.PYTHON + else -> throw BraintrustInvalidDataException("Unknown Runtime: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Runtime && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RuntimeContext && + runtime == other.runtime && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(runtime, version, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuntimeContext{runtime=$runtime, version=$version, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CodeBundle && + bundleId == other.bundleId && + location == other.location && + runtimeContext == other.runtimeContext && + preview == other.preview && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(bundleId, location, runtimeContext, preview, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CodeBundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..951173c8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CreateApiKeyOutput.kt @@ -0,0 +1,404 @@ +// 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.checkRequired +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 + +class CreateApiKeyOutput +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The raw API key. It will only be exposed this one time + * + * @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 key(): String = key.getRequired("key") + + /** + * Name of the api key + * + * @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") + + /** + * @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 previewName(): String = previewName.getRequired("preview_name") + + /** + * Date of api key creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Unique identifier for the organization + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun orgId(): Optional = orgId.getOptional("org_id") + + /** + * Unique identifier for the user + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [key]. + * + * Unlike [key], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("key") @ExcludeMissing fun _key(): JsonField = key + + /** + * 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 [previewName]. + * + * Unlike [previewName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("preview_name") + @ExcludeMissing + fun _previewName(): JsonField = previewName + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [CreateApiKeyOutput]. + * + * The following fields are required: + * ```java + * .id() + * .key() + * .name() + * .previewName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CreateApiKeyOutput]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var key: JsonField? = null + private var name: JsonField? = null + private var previewName: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var orgId: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(createApiKeyOutput: CreateApiKeyOutput) = apply { + id = createApiKeyOutput.id + key = createApiKeyOutput.key + name = createApiKeyOutput.name + previewName = createApiKeyOutput.previewName + created = createApiKeyOutput.created + orgId = createApiKeyOutput.orgId + userId = createApiKeyOutput.userId + additionalProperties = createApiKeyOutput.additionalProperties.toMutableMap() + } + + /** Unique identifier for the api key */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The raw API key. It will only be exposed this one time */ + fun key(key: String) = key(JsonField.of(key)) + + /** + * Sets [Builder.key] to an arbitrary JSON value. + * + * You should usually call [Builder.key] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun key(key: JsonField) = apply { this.key = key } + + /** Name of the api key */ + 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 previewName(previewName: String) = previewName(JsonField.of(previewName)) + + /** + * Sets [Builder.previewName] to an arbitrary JSON value. + * + * You should usually call [Builder.previewName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun previewName(previewName: JsonField) = apply { this.previewName = previewName } + + /** Date of api key creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Unique identifier for the organization */ + 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 } + + /** Unique identifier for the user */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CreateApiKeyOutput]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .key() + * .name() + * .previewName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): CreateApiKeyOutput = + CreateApiKeyOutput( + checkRequired("id", id), + checkRequired("key", key), + checkRequired("name", name), + checkRequired("previewName", previewName), + created, + orgId, + userId, + 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 + } + + return other is CreateApiKeyOutput && + id == other.id && + key == other.key && + name == other.name && + previewName == other.previewName && + created == other.created && + orgId == other.orgId && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, key, name, previewName, created, orgId, userId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CreateApiKeyOutput{id=$id, key=$key, name=$name, previewName=$previewName, created=$created, orgId=$orgId, userId=$userId, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..fb130110 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponse.kt @@ -0,0 +1,556 @@ +// 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.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 + +class CrossObjectInsertResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 = dataset.getOptional("dataset") + + /** + * A mapping from experiment 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 experiment(): Optional = experiment.getOptional("experiment") + + /** + * A mapping from project 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 projectLogs(): Optional = projectLogs.getOptional("project_logs") + + /** + * Returns the raw JSON value of [dataset]. + * + * Unlike [dataset], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("dataset") @ExcludeMissing fun _dataset(): JsonField = dataset + + /** + * Returns the raw JSON value of [experiment]. + * + * Unlike [experiment], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("experiment") + @ExcludeMissing + fun _experiment(): JsonField = experiment + + /** + * Returns the raw JSON value of [projectLogs]. + * + * Unlike [projectLogs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_logs") + @ExcludeMissing + fun _projectLogs(): JsonField = projectLogs + + @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 [CrossObjectInsertResponse]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [CrossObjectInsertResponse]. */ + class Builder internal constructor() { + + private var dataset: JsonField = JsonMissing.of() + private var experiment: JsonField = JsonMissing.of() + private var projectLogs: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(crossObjectInsertResponse: CrossObjectInsertResponse) = apply { + dataset = crossObjectInsertResponse.dataset + experiment = crossObjectInsertResponse.experiment + projectLogs = crossObjectInsertResponse.projectLogs + additionalProperties = crossObjectInsertResponse.additionalProperties.toMutableMap() + } + + /** A mapping from dataset id to row ids for inserted `events` */ + fun dataset(dataset: Dataset?) = dataset(JsonField.ofNullable(dataset)) + + /** Alias for calling [Builder.dataset] with `dataset.orElse(null)`. */ + fun dataset(dataset: Optional) = dataset(dataset.getOrNull()) + + /** + * Sets [Builder.dataset] to an arbitrary JSON value. + * + * You should usually call [Builder.dataset] with a well-typed [Dataset] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun dataset(dataset: JsonField) = apply { this.dataset = dataset } + + /** A mapping from experiment id to row ids for inserted `events` */ + fun experiment(experiment: Experiment?) = experiment(JsonField.ofNullable(experiment)) + + /** Alias for calling [Builder.experiment] with `experiment.orElse(null)`. */ + fun experiment(experiment: Optional) = experiment(experiment.getOrNull()) + + /** + * Sets [Builder.experiment] to an arbitrary JSON value. + * + * You should usually call [Builder.experiment] with a well-typed [Experiment] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun experiment(experiment: JsonField) = apply { this.experiment = experiment } + + /** A mapping from project id to row ids for inserted `events` */ + fun projectLogs(projectLogs: ProjectLogs?) = projectLogs(JsonField.ofNullable(projectLogs)) + + /** Alias for calling [Builder.projectLogs] with `projectLogs.orElse(null)`. */ + fun projectLogs(projectLogs: Optional) = projectLogs(projectLogs.getOrNull()) + + /** + * Sets [Builder.projectLogs] to an arbitrary JSON value. + * + * You should usually call [Builder.projectLogs] with a well-typed [ProjectLogs] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun projectLogs(projectLogs: JsonField) = apply { + this.projectLogs = projectLogs + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [CrossObjectInsertResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): CrossObjectInsertResponse = + CrossObjectInsertResponse( + dataset, + experiment, + projectLogs, + 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` */ + class Dataset + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Dataset]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Dataset]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(dataset: Dataset) = apply { + additionalProperties = dataset.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 [Dataset]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Dataset && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Dataset{additionalProperties=$additionalProperties}" + } + + /** A mapping from experiment id to row ids for inserted `events` */ + class Experiment + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Experiment]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Experiment]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(experiment: Experiment) = apply { + additionalProperties = experiment.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 [Experiment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Experiment && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Experiment{additionalProperties=$additionalProperties}" + } + + /** A mapping from project id to row ids for inserted `events` */ + class ProjectLogs + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ProjectLogs]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectLogs]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectLogs: ProjectLogs) = apply { + additionalProperties = projectLogs.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 [ProjectLogs]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is ProjectLogs && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ProjectLogs{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CrossObjectInsertResponse && + dataset == other.dataset && + experiment == other.experiment && + projectLogs == other.projectLogs && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(dataset, experiment, projectLogs, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "CrossObjectInsertResponse{dataset=$dataset, experiment=$experiment, projectLogs=$projectLogs, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..e2485a60 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DataSummary.kt @@ -0,0 +1,179 @@ +// 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.checkRequired +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 */ +class DataSummary +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 totalRecords(): Long = totalRecords.getRequired("total_records") + + /** + * Returns the raw JSON value of [totalRecords]. + * + * Unlike [totalRecords], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("total_records") + @ExcludeMissing + fun _totalRecords(): JsonField = totalRecords + + @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 [DataSummary]. + * + * The following fields are required: + * ```java + * .totalRecords() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DataSummary]. */ + class Builder internal constructor() { + + private var totalRecords: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(dataSummary: DataSummary) = apply { + totalRecords = dataSummary.totalRecords + additionalProperties = dataSummary.additionalProperties.toMutableMap() + } + + /** Total number of records in the dataset */ + fun totalRecords(totalRecords: Long) = totalRecords(JsonField.of(totalRecords)) + + /** + * Sets [Builder.totalRecords] to an arbitrary JSON value. + * + * You should usually call [Builder.totalRecords] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun totalRecords(totalRecords: JsonField) = apply { this.totalRecords = totalRecords } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DataSummary]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .totalRecords() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): DataSummary = + DataSummary( + checkRequired("totalRecords", totalRecords), + 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 + } + + return other is DataSummary && + totalRecords == other.totalRecords && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(totalRecords, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "DataSummary{totalRecords=$totalRecords, additionalProperties=$additionalProperties}" +} 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 old mode 100644 new mode 100755 index 53a8d63c..e7e950c6 --- 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,239 +6,556 @@ 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.toUnmodifiable +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 com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@JsonDeserialize(builder = Dataset.Builder::class) -@NoAutoDetect class Dataset +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val id: JsonField, - private val projectId: JsonField, private val name: JsonField, - private val description: 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: Map, + private val additionalProperties: MutableMap, ) { - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Unique identifier for the dataset */ + @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 + * + * @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 id(): String = id.getRequired("id") - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(): Optional = Optional.ofNullable(projectId.getNullable("project_id")) - - /** Name of the dataset. Within a project, dataset names are unique */ + /** + * 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") - /** Textual description of the dataset */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** Date of dataset creation */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) - - /** Date of dataset deletion, or null if the dataset is still active */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) - - /** Identifies the user who created the dataset */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - /** Unique identifier for the dataset */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId - - /** Name of the dataset. Within a project, dataset names are unique */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Textual description of the dataset */ - @JsonProperty("description") @ExcludeMissing fun _description() = description - - /** Date of dataset creation */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Date of dataset deletion, or null if the dataset is still active */ - @JsonProperty("deleted_at") @ExcludeMissing fun _deletedAt() = deletedAt - - /** Identifies the user who created the dataset */ - @JsonProperty("user_id") @ExcludeMissing fun _userId() = userId + /** + * 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") + + /** + * Date of dataset creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Date of dataset deletion, or null if the dataset 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") + + /** + * 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") + + /** + * Identifies the user who created the dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [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 [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Dataset = apply { - if (!validated) { - id() - projectId() - name() - description() - created() - deletedAt() - userId() - validated = true - } - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Dataset && - this.id == other.id && - this.projectId == other.projectId && - this.name == other.name && - this.description == other.description && - this.created == other.created && - this.deletedAt == other.deletedAt && - this.userId == other.userId && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - projectId, - name, - description, - created, - deletedAt, - userId, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Dataset{id=$id, projectId=$projectId, name=$name, description=$description, created=$created, deletedAt=$deletedAt, userId=$userId, additionalProperties=$additionalProperties}" - companion object { + /** + * Returns a mutable builder for constructing an instance of [Dataset]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * ``` + */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Dataset]. */ + class Builder internal constructor() { - private var id: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() + private var id: JsonField? = null + private var name: JsonField? = null + private var projectId: JsonField? = null private var created: JsonField = JsonMissing.of() private var deletedAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() private var userId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(dataset: Dataset) = apply { - this.id = dataset.id - this.projectId = dataset.projectId - this.name = dataset.name - this.description = dataset.description - this.created = dataset.created - this.deletedAt = dataset.deletedAt - this.userId = dataset.userId - additionalProperties(dataset.additionalProperties) + id = dataset.id + name = dataset.name + projectId = dataset.projectId + created = dataset.created + deletedAt = dataset.deletedAt + description = dataset.description + metadata = dataset.metadata + userId = dataset.userId + additionalProperties = dataset.additionalProperties.toMutableMap() } /** Unique identifier for the dataset */ fun id(id: String) = id(JsonField.of(id)) - /** Unique identifier for the dataset */ - @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } - - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } /** Name of the dataset. Within a project, dataset names are unique */ fun name(name: String) = name(JsonField.of(name)) - /** Name of the dataset. Within a project, dataset names are unique */ - @JsonProperty("name") - @ExcludeMissing + /** + * 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 dataset */ - fun description(description: String) = description(JsonField.of(description)) - - /** Textual description of the dataset */ - @JsonProperty("description") - @ExcludeMissing - fun description(description: JsonField) = apply { this.description = description } + /** Unique identifier for the project that the dataset belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - /** Date of dataset creation */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) + /** + * 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 } /** Date of dataset creation */ - @JsonProperty("created") - @ExcludeMissing + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun created(created: JsonField) = apply { this.created = created } /** Date of dataset deletion, or null if the dataset is still active */ - fun deletedAt(deletedAt: OffsetDateTime) = deletedAt(JsonField.of(deletedAt)) - - /** Date of dataset deletion, or null if the dataset is still active */ - @JsonProperty("deleted_at") - @ExcludeMissing + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } - /** Identifies the user who created the dataset */ - fun userId(userId: String) = userId(JsonField.of(userId)) + /** 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 } /** Identifies the user who created the dataset */ - @JsonProperty("user_id") - @ExcludeMissing + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun userId(userId: JsonField) = apply { this.userId = userId } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Dataset]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Dataset = Dataset( - id, - projectId, - name, - description, + checkRequired("id", id), + checkRequired("name", name), + checkRequired("projectId", projectId), created, deletedAt, + description, + metadata, userId, - additionalProperties.toUnmodifiable(), + 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 */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Dataset && + id == other.id && + name == other.name && + projectId == other.projectId && + created == other.created && + deletedAt == other.deletedAt && + description == other.description && + metadata == other.metadata && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + projectId, + created, + deletedAt, + description, + metadata, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Dataset{id=$id, name=$name, projectId=$projectId, created=$created, deletedAt=$deletedAt, description=$description, metadata=$metadata, userId=$userId, additionalProperties=$additionalProperties}" } 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 old mode 100644 new mode 100755 index 27919b29..23585870 --- 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 @@ -3,289 +3,741 @@ 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.toUnmodifiable -import com.braintrustdata.api.models.* +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.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 com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Create a new dataset. If there is an existing dataset in the project with the same name as the + * one specified in the request, will return the existing dataset unmodified + */ class DatasetCreateParams -constructor( - private val name: String, - private val description: String?, - private val projectId: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun name(): String = name - - fun description(): Optional = Optional.ofNullable(description) - - fun projectId(): Optional = Optional.ofNullable(projectId) - - @JvmSynthetic - internal fun getBody(): DatasetCreateBody { - return DatasetCreateBody( - name, - description, - projectId, - additionalBodyProperties, - ) +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.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 = body.projectId() + + /** + * 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 = body.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 = body.metadata() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [DatasetCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [DatasetCreateParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - @JsonDeserialize(builder = DatasetCreateBody.Builder::class) - @NoAutoDetect - class DatasetCreateBody - internal constructor( - private val name: String?, - private val description: String?, - private val projectId: String?, - private val additionalProperties: Map, - ) { + @JvmSynthetic + internal fun from(datasetCreateParams: DatasetCreateParams) = apply { + body = datasetCreateParams.body.toBuilder() + additionalHeaders = datasetCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetCreateParams.additionalQueryParams.toBuilder() + } - private var hashCode: Int = 0 + /** + * 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 */ - @JsonProperty("name") fun name(): String? = name + fun name(name: String) = apply { body.name(name) } - /** Textual description of the dataset */ - @JsonProperty("description") fun description(): String? = 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 { body.name(name) } /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") fun projectId(): String? = projectId + fun projectId(projectId: String) = apply { body.projectId(projectId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** + * 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) } - fun toBuilder() = Builder().from(this) + /** Textual description of the dataset */ + 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 dataset */ + 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) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + 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) } - return other is DatasetCreateBody && - this.name == other.name && - this.description == other.description && - this.projectId == other.projectId && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - description, - projectId, - additionalProperties, - ) + 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) } - return hashCode + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - override fun toString() = - "DatasetCreateBody{name=$name, description=$description, projectId=$projectId, additionalProperties=$additionalProperties}" + 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 [DatasetCreateParams]. + * + * 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(): DatasetCreateParams = + DatasetCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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 = + 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() } - class Builder { + /** A builder for [Body]. */ + class Builder internal constructor() { - private var name: String? = null - private var description: String? = null - private var projectId: String? = null + 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(datasetCreateBody: DatasetCreateBody) = apply { - this.name = datasetCreateBody.name - this.description = datasetCreateBody.description - this.projectId = datasetCreateBody.projectId - additionalProperties(datasetCreateBody.additionalProperties) + 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 */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } + fun name(name: String) = name(JsonField.of(name)) - /** Textual description of the dataset */ - @JsonProperty("description") - fun description(description: String) = apply { this.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 } /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") - fun projectId(projectId: String) = apply { this.projectId = projectId } + 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() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): DatasetCreateBody = - DatasetCreateBody( - checkNotNull(name) { "`name` is required but was not set" }, + 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, - projectId, - additionalProperties.toUnmodifiable(), + metadata, + additionalProperties.toMutableMap(), ) } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - fun _additionalHeaders(): Map> = additionalHeaders + private var validated: Boolean = false - fun _additionalBodyProperties(): Map = additionalBodyProperties + fun validate(): Body = apply { + if (validated) { + return@apply + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + name() + projectId() + description() + metadata().ifPresent { it.validate() } + validated = true } - return other is DatasetCreateParams && - this.name == other.name && - this.description == other.description && - this.projectId == other.projectId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - override fun hashCode(): Int { - return Objects.hash( - name, - description, - projectId, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + /** + * Returns a 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 toString() = - "DatasetCreateParams{name=$name, description=$description, projectId=$projectId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun toBuilder() = Builder().from(this) + return other is Body && + name == other.name && + projectId == other.projectId && + description == other.description && + metadata == other.metadata && + additionalProperties == other.additionalProperties + } - companion object { + private val hashCode: Int by lazy { + Objects.hash(name, projectId, description, metadata, additionalProperties) + } - @JvmStatic fun builder() = Builder() + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, description=$description, metadata=$metadata, additionalProperties=$additionalProperties}" } - @NoAutoDetect - class Builder { + /** User-controlled metadata about the dataset */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { - private var name: String? = null - private var description: String? = null - private var projectId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties - @JvmSynthetic - internal fun from(datasetCreateParams: DatasetCreateParams) = apply { - this.name = datasetCreateParams.name - this.description = datasetCreateParams.description - this.projectId = datasetCreateParams.projectId - additionalQueryParams(datasetCreateParams.additionalQueryParams) - additionalHeaders(datasetCreateParams.additionalHeaders) - additionalBodyProperties(datasetCreateParams.additionalBodyProperties) + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() } - /** Name of the dataset. Within a project, dataset names are unique */ - fun name(name: String) = apply { this.name = name } + /** A builder for [Metadata]. */ + class Builder internal constructor() { - /** Textual description of the dataset */ - fun description(description: String) = apply { this.description = description } + private var additionalProperties: MutableMap = mutableMapOf() - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } + private var validated: Boolean = false - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun validate(): Metadata = apply { + if (validated) { + return@apply + } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + validated = true } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + /** + * Returns 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() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - fun build(): DatasetCreateParams = - DatasetCreateParams( - checkNotNull(name) { "`name` is required but was not set" }, - description, - projectId, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DatasetCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "DatasetCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index 29ce38b2..bd822a26 --- 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,141 +3,172 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Delete a dataset object by its id */ class DatasetDeleteParams -constructor( - private val datasetId: String, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, +private constructor( + private val datasetId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, -) { +) : Params { - fun datasetId(): String = datasetId - - @JvmSynthetic - internal fun getBody(): Optional> { - return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetDeleteParams && - this.datasetId == other.datasetId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - override fun hashCode(): Int { - return Objects.hash( - datasetId, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "DatasetDeleteParams{datasetId=$datasetId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): DatasetDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [DatasetDeleteParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [DatasetDeleteParams]. */ + class Builder internal constructor() { private var datasetId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(datasetDeleteParams: DatasetDeleteParams) = apply { - this.datasetId = datasetDeleteParams.datasetId - additionalQueryParams(datasetDeleteParams.additionalQueryParams) - additionalHeaders(datasetDeleteParams.additionalHeaders) - additionalBodyProperties(datasetDeleteParams.additionalBodyProperties) + datasetId = datasetDeleteParams.datasetId + additionalHeaders = datasetDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = datasetDeleteParams.additionalBodyProperties.toMutableMap() } /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(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 putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + putAllAdditionalBodyProperties(additionalBodyProperties) } fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + additionalBodyProperties.put(key, value) } fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = @@ -145,12 +176,56 @@ constructor( this.additionalBodyProperties.putAll(additionalBodyProperties) } + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [DatasetDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): DatasetDeleteParams = DatasetDeleteParams( - checkNotNull(datasetId) { "`datasetId` is required but was not set" }, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), + datasetId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), ) } + + 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 + } + + return other is DatasetDeleteParams && + datasetId == other.datasetId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(datasetId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "DatasetDeleteParams{datasetId=$datasetId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } 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 new file mode 100755 index 00000000..783c2948 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetEvent.kt @@ -0,0 +1,816 @@ +// 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.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class DatasetEvent +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The transaction id of an event is unique to the network operation that processed the event + * insertion. Transaction ids are monotonically increasing over time and can be used to retrieve + * a versioned snapshot of the dataset (see the `version` parameter) + * + * @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 _xactId(): String = _xactId.getRequired("_xact_id") + + /** + * The timestamp the dataset event was created + * + * @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 created(): OffsetDateTime = created.getRequired("created") + + /** + * Unique identifier for the dataset + * + * @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 datasetId(): String = datasetId.getRequired("dataset_id") + + /** + * 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") + + /** + * A unique identifier for the trace this dataset event belongs 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 rootSpanId(): String = rootSpanId.getRequired("root_span_id") + + /** + * A unique identifier used to link different dataset events together as part of a full trace. + * See the [tracing guide](https://www.braintrust.dev/docs/guides/tracing) for full details on + * tracing + * + * @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 spanId(): String = spanId.getRequired("span_id") + + /** + * The output of your application, including post-processing (an arbitrary, JSON serializable + * object) + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** The argument that uniquely define an input case (an arbitrary, JSON serializable object) */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonValue = input + + /** + * Whether this span is a root span + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isRoot(): Optional = isRoot.getOptional("is_root") + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + * + * @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") + + /** + * Indicates the event was copied from another object. + * + * @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") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_xactId]. + * + * Unlike [_xactId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_xact_id") @ExcludeMissing fun __xactId(): JsonField = _xactId + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [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 [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId(): JsonField = rootSpanId + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + + /** + * Returns the raw JSON value of [isRoot]. + * + * Unlike [isRoot], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("is_root") @ExcludeMissing fun _isRoot(): JsonField = isRoot + + /** + * 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 [origin]. + * + * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("origin") @ExcludeMissing fun _origin(): JsonField = origin + + /** + * 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 [DatasetEvent]. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .created() + * .datasetId() + * .projectId() + * .rootSpanId() + * .spanId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DatasetEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var _xactId: JsonField? = null + private var created: JsonField? = null + private var datasetId: JsonField? = null + private var projectId: JsonField? = null + private var rootSpanId: JsonField? = null + private var spanId: JsonField? = null + private var expected: JsonValue = JsonMissing.of() + private var input: JsonValue = JsonMissing.of() + private var isRoot: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(datasetEvent: DatasetEvent) = apply { + id = datasetEvent.id + _xactId = datasetEvent._xactId + created = datasetEvent.created + datasetId = datasetEvent.datasetId + projectId = datasetEvent.projectId + rootSpanId = datasetEvent.rootSpanId + spanId = datasetEvent.spanId + expected = datasetEvent.expected + input = datasetEvent.input + isRoot = datasetEvent.isRoot + metadata = datasetEvent.metadata + origin = datasetEvent.origin + tags = datasetEvent.tags.map { it.toMutableList() } + additionalProperties = datasetEvent.additionalProperties.toMutableMap() + } + + /** + * A unique identifier for the dataset event. If you don't provide one, BrainTrust will + * generate one for you + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The transaction id of an event is unique to the network operation that processed the + * event insertion. Transaction ids are monotonically increasing over time and can be used + * to retrieve a versioned snapshot of the dataset (see the `version` parameter) + */ + fun _xactId(_xactId: String) = _xactId(JsonField.of(_xactId)) + + /** + * Sets [Builder._xactId] to an arbitrary JSON value. + * + * You should usually call [Builder._xactId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } + + /** The timestamp the dataset event was created */ + fun created(created: OffsetDateTime) = created(JsonField.of(created)) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Unique identifier for the dataset */ + fun datasetId(datasetId: String) = datasetId(JsonField.of(datasetId)) + + /** + * 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 } + + /** 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 } + + /** A unique identifier for the trace this dataset event belongs to */ + fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } + + /** + * A unique identifier used to link different dataset events together as part of a full + * trace. See the [tracing guide](https://www.braintrust.dev/docs/guides/tracing) for full + * details on tracing + */ + fun spanId(spanId: String) = spanId(JsonField.of(spanId)) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + /** + * The output of your application, including post-processing (an arbitrary, JSON + * serializable object) + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * The argument that uniquely define an input case (an arbitrary, JSON serializable object) + */ + fun input(input: JsonValue) = apply { this.input = input } + + /** Whether this span is a root span */ + fun isRoot(isRoot: Boolean?) = isRoot(JsonField.ofNullable(isRoot)) + + /** + * Alias for [Builder.isRoot]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isRoot(isRoot: Boolean) = isRoot(isRoot as Boolean?) + + /** Alias for calling [Builder.isRoot] with `isRoot.orElse(null)`. */ + fun isRoot(isRoot: Optional) = isRoot(isRoot.getOrNull()) + + /** + * Sets [Builder.isRoot] to an arbitrary JSON value. + * + * You should usually call [Builder.isRoot] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun isRoot(isRoot: JsonField) = apply { this.isRoot = isRoot } + + /** + * 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 example, you could log the `prompt`, example's `id`, or anything else that would be + * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, + * but its keys must be strings + */ + 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 } + + /** Indicates the event was copied from another object. */ + fun origin(origin: ObjectReference?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [ObjectReference] 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 } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DatasetEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .created() + * .datasetId() + * .projectId() + * .rootSpanId() + * .spanId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): DatasetEvent = + DatasetEvent( + checkRequired("id", id), + checkRequired("_xactId", _xactId), + checkRequired("created", created), + checkRequired("datasetId", datasetId), + checkRequired("projectId", projectId), + checkRequired("rootSpanId", rootSpanId), + checkRequired("spanId", spanId), + expected, + input, + isRoot, + metadata, + origin, + (tags ?: JsonMissing.of()).map { it.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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + */ + class Metadata + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = model.getOptional("model") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + @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 [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var model: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + model = metadata.model + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + /** The model used for this example */ + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(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 + } + + return other is Metadata && + model == other.model && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(model, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{model=$model, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DatasetEvent && + id == other.id && + _xactId == other._xactId && + created == other.created && + datasetId == other.datasetId && + projectId == other.projectId && + rootSpanId == other.rootSpanId && + spanId == other.spanId && + expected == other.expected && + input == other.input && + isRoot == other.isRoot && + metadata == other.metadata && + origin == other.origin && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _xactId, + created, + datasetId, + projectId, + rootSpanId, + spanId, + expected, + input, + isRoot, + metadata, + origin, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "DatasetEvent{id=$id, _xactId=$_xactId, created=$created, datasetId=$datasetId, projectId=$projectId, rootSpanId=$rootSpanId, spanId=$spanId, expected=$expected, input=$input, isRoot=$isRoot, metadata=$metadata, origin=$origin, tags=$tags, additionalProperties=$additionalProperties}" +} 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 old mode 100644 new mode 100755 index 43c1cb70..d0ac1c86 --- 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 @@ -4,525 +4,470 @@ 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.toUnmodifiable +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.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Log feedback for a set of dataset events */ class DatasetFeedbackParams -constructor( - private val datasetId: String, - private val feedback: List, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { +private constructor( + private val datasetId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + + /** + * 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 = body.feedback() + + /** + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _feedback(): JsonField> = body._feedback() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun datasetId(): String = datasetId + fun toBuilder() = Builder().from(this) - fun feedback(): List = feedback + companion object { - @JvmSynthetic - internal fun getBody(): DatasetFeedbackBody { - return DatasetFeedbackBody(feedback, additionalBodyProperties) + /** + * Returns a mutable builder for constructing an instance of [DatasetFeedbackParams]. + * + * The following fields are required: + * ```java + * .feedback() + * ``` + */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [DatasetFeedbackParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" + @JvmSynthetic + internal fun from(datasetFeedbackParams: DatasetFeedbackParams) = apply { + datasetId = datasetFeedbackParams.datasetId + body = datasetFeedbackParams.body.toBuilder() + additionalHeaders = datasetFeedbackParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetFeedbackParams.additionalQueryParams.toBuilder() } - } - - @JsonDeserialize(builder = DatasetFeedbackBody.Builder::class) - @NoAutoDetect - class DatasetFeedbackBody - internal constructor( - private val feedback: List?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - /** A list of dataset feedback items */ - @JsonProperty("feedback") fun feedback(): List? = feedback - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Dataset id */ + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } - fun toBuilder() = Builder().from(this) + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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() } - return other is DatasetFeedbackBody && - this.feedback == other.feedback && - this.additionalProperties == other.additionalProperties - } + /** A list of dataset feedback items */ + fun feedback(feedback: List) = apply { body.feedback(feedback) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(feedback, additionalProperties) - } - return hashCode + /** + * 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 { + body.feedback(feedback) } - override fun toString() = - "DatasetFeedbackBody{feedback=$feedback, additionalProperties=$additionalProperties}" - - companion object { + /** + * Adds a single [FeedbackDatasetItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFeedback(feedback: FeedbackDatasetItem) = apply { body.addFeedback(feedback) } - @JvmStatic fun builder() = Builder() + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - class Builder { - - private var feedback: List? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(datasetFeedbackBody: DatasetFeedbackBody) = apply { - this.feedback = datasetFeedbackBody.feedback - additionalProperties(datasetFeedbackBody.additionalProperties) - } - - /** A list of dataset feedback items */ - @JsonProperty("feedback") - fun feedback(feedback: List) = apply { this.feedback = feedback } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun build(): DatasetFeedbackBody = - DatasetFeedbackBody( - checkNotNull(feedback) { "`feedback` is required but was not set" } - .toUnmodifiable(), - additionalProperties.toUnmodifiable() - ) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - return other is DatasetFeedbackParams && - this.datasetId == other.datasetId && - this.feedback == other.feedback && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - override fun hashCode(): Int { - return Objects.hash( - datasetId, - feedback, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - override fun toString() = - "DatasetFeedbackParams{datasetId=$datasetId, feedback=$feedback, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - fun toBuilder() = Builder().from(this) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - companion object { + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmStatic fun builder() = Builder() - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - @NoAutoDetect - class Builder { + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - private var datasetId: String? = null - private var feedback: MutableList = mutableListOf() - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(datasetFeedbackParams: DatasetFeedbackParams) = apply { - this.datasetId = datasetFeedbackParams.datasetId - this.feedback(datasetFeedbackParams.feedback) - additionalQueryParams(datasetFeedbackParams.additionalQueryParams) - additionalHeaders(datasetFeedbackParams.additionalHeaders) - additionalBodyProperties(datasetFeedbackParams.additionalBodyProperties) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** A list of dataset feedback items */ - fun feedback(feedback: List) = apply { - this.feedback.clear() - this.feedback.addAll(feedback) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - /** A list of dataset feedback items */ - fun addFeedback(feedback: Feedback) = apply { this.feedback.add(feedback) } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + putAllAdditionalQueryParams(additionalQueryParams) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - + /** + * Returns an immutable instance of [DatasetFeedbackParams]. + * + * 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(): DatasetFeedbackParams = DatasetFeedbackParams( - checkNotNull(datasetId) { "`datasetId` is required but was not set" }, - checkNotNull(feedback) { "`feedback` is required but was not set" } - .toUnmodifiable(), - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), + datasetId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } - @JsonDeserialize(builder = Feedback.Builder::class) - @NoAutoDetect - class Feedback + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( - private val id: String?, - private val comment: String?, - private val metadata: Metadata?, - private val source: Source?, - private val additionalProperties: Map, + private val feedback: JsonField>, + private val additionalProperties: MutableMap, ) { - private var hashCode: Int = 0 + @JsonCreator + private constructor( + @JsonProperty("feedback") + @ExcludeMissing + feedback: JsonField> = JsonMissing.of() + ) : this(feedback, mutableMapOf()) /** - * The id of the dataset event to log feedback for. This is the row `id` returned by `POST - * /v1/dataset/{dataset_id}/insert` + * 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). */ - @JsonProperty("id") fun id(): String? = id - - /** An optional comment string to log about the dataset event */ - @JsonProperty("comment") fun comment(): String? = comment + fun feedback(): List = feedback.getRequired("feedback") /** - * 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. + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("metadata") fun metadata(): Metadata? = metadata + @JsonProperty("feedback") + @ExcludeMissing + fun _feedback(): JsonField> = feedback - /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ - @JsonProperty("source") fun source(): Source? = source + @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) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Feedback && - this.id == other.id && - this.comment == other.comment && - this.metadata == other.metadata && - this.source == other.source && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - comment, - metadata, - source, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Feedback{id=$id, comment=$comment, metadata=$metadata, source=$source, additionalProperties=$additionalProperties}" - companion object { + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .feedback() + * ``` + */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Body]. */ + class Builder internal constructor() { - private var id: String? = null - private var comment: String? = null - private var metadata: Metadata? = null - private var source: Source? = null + private var feedback: JsonField>? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(feedback: Feedback) = apply { - this.id = feedback.id - this.comment = feedback.comment - this.metadata = feedback.metadata - this.source = feedback.source - additionalProperties(feedback.additionalProperties) + 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)) + /** - * The id of the dataset event to log feedback for. This is the row `id` returned by - * `POST /v1/dataset/{dataset_id}/insert` + * 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. */ - @JsonProperty("id") fun id(id: String) = apply { this.id = id } - - /** An optional comment string to log about the dataset event */ - @JsonProperty("comment") fun comment(comment: String) = apply { this.comment = comment } + fun feedback(feedback: JsonField>) = apply { + this.feedback = feedback.map { it.toMutableList() } + } /** - * 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. + * Adds a single [FeedbackDatasetItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("metadata") - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } - - /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ - @JsonProperty("source") fun source(source: Source) = apply { this.source = source } + 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() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Feedback = - Feedback( - checkNotNull(id) { "`id` is required but was not set" }, - comment, - metadata, - source, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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. - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + /** + * 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(), + ) + } - companion object { + private var validated: Boolean = false - @JvmStatic fun builder() = Builder() + fun validate(): Body = apply { + if (validated) { + return@apply } - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } + feedback().forEach { it.validate() } + validated = true } - class Source - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Source && this.value == other.value + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val APP = Source(JsonField.of("app")) - - @JvmField val API = Source(JsonField.of("api")) - - @JvmField val EXTERNAL = Source(JsonField.of("external")) + /** + * Returns 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) - @JvmStatic fun of(value: String) = Source(JsonField.of(value)) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - enum class Known { - APP, - API, - EXTERNAL, - } + return other is Body && + feedback == other.feedback && + additionalProperties == other.additionalProperties + } - enum class Value { - APP, - API, - EXTERNAL, - _UNKNOWN, - } + private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } - fun value(): Value = - when (this) { - APP -> Value.APP - API -> Value.API - EXTERNAL -> Value.EXTERNAL - else -> Value._UNKNOWN - } + override fun hashCode(): Int = hashCode - fun known(): Known = - when (this) { - APP -> Known.APP - API -> Known.API - EXTERNAL -> Known.EXTERNAL - else -> throw BraintrustInvalidDataException("Unknown Source: $value") - } + override fun toString() = + "Body{feedback=$feedback, additionalProperties=$additionalProperties}" + } - fun asString(): String = _value().asStringOrThrow() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } + + return other is DatasetFeedbackParams && + datasetId == other.datasetId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = + Objects.hash(datasetId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "DatasetFeedbackParams{datasetId=$datasetId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index f6236059..38306f2a --- 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,120 +2,131 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Fetch the events in a dataset. Equivalent to the POST form of the same path, but with the + * parameters in the URL query rather than in the request body. For more complex queries, use the + * `POST /btql` endpoint. + */ class DatasetFetchParams -constructor( - private val datasetId: String, +private constructor( + private val datasetId: String?, private val limit: Long?, private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { - - fun datasetId(): String = datasetId - + private val maxXactId: String?, + private val version: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + + /** + * 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(): Optional = Optional.ofNullable(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(): Optional = Optional.ofNullable(maxRootSpanId) - fun maxXactId(): Optional = Optional.ofNullable(maxXactId) - - fun version(): Optional = Optional.ofNullable(version) - - @JvmSynthetic - internal fun getQueryParams(): Map> { - val params = mutableMapOf>() - this.limit?.let { params.put("limit", listOf(it.toString())) } - this.maxRootSpanId?.let { params.put("max_root_span_id", listOf(it.toString())) } - this.maxXactId?.let { params.put("max_xact_id", listOf(it.toString())) } - this.version?.let { params.put("version", listOf(it.toString())) } - params.putAll(additionalQueryParams) - return params.toUnmodifiable() - } - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetFetchParams && - this.datasetId == other.datasetId && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } - - override fun hashCode(): Int { - return Objects.hash( - datasetId, - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams, - additionalHeaders, - ) - } - - override fun toString() = - "DatasetFetchParams{datasetId=$datasetId, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + /** + * 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(): Optional = Optional.ofNullable(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(): Optional = Optional.ofNullable(version) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): DatasetFetchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [DatasetFetchParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [DatasetFetchParams]. */ + class Builder internal constructor() { private var datasetId: String? = null private var limit: Long? = null private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var maxXactId: String? = null + private var version: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(datasetFetchParams: DatasetFetchParams) = apply { - this.datasetId = datasetFetchParams.datasetId - this.limit = datasetFetchParams.limit - this.maxRootSpanId = datasetFetchParams.maxRootSpanId - this.maxXactId = datasetFetchParams.maxXactId - this.version = datasetFetchParams.version - additionalQueryParams(datasetFetchParams.additionalQueryParams) - additionalHeaders(datasetFetchParams.additionalHeaders) + datasetId = datasetFetchParams.datasetId + limit = datasetFetchParams.limit + maxRootSpanId = datasetFetchParams.maxRootSpanId + maxXactId = datasetFetchParams.maxXactId + version = datasetFetchParams.version + additionalHeaders = datasetFetchParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetFetchParams.additionalQueryParams.toBuilder() } /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } + + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) /** + * 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, @@ -128,80 +139,224 @@ constructor( * with more individual rows than the specified limit if you are fetching events containing * traces. */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(limit: Long?) = apply { this.limit = limit } /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. */ - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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: Long) = apply { this.maxXactId = maxXactId } + fun maxRootSpanId(maxRootSpanId: String?) = apply { this.maxRootSpanId = maxRootSpanId } + + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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 version(version: Long) = apply { this.version = version } + fun maxXactId(maxXactId: String?) = apply { this.maxXactId = maxXactId } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** 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. + */ + fun version(version: String?) = apply { this.version = version } + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [DatasetFetchParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): DatasetFetchParams = DatasetFetchParams( - checkNotNull(datasetId) { "`datasetId` is required but was not set" }, + datasetId, limit, maxRootSpanId, maxXactId, version, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + } + + return other is DatasetFetchParams && + datasetId == other.datasetId && + limit == other.limit && + maxRootSpanId == other.maxRootSpanId && + maxXactId == other.maxXactId && + version == other.version && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + datasetId, + limit, + maxRootSpanId, + maxXactId, + version, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "DatasetFetchParams{datasetId=$datasetId, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index f8d96e73..955438aa --- 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 @@ -4,88 +4,224 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Fetch the events in a dataset. Equivalent to the GET form of the same path, but with the + * parameters in the request body rather than in the URL query. For more complex queries, use the + * `POST /btql` endpoint. + */ class DatasetFetchPostParams -constructor( - private val datasetId: String, - private val filters: List?, - private val limit: Long?, - private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun datasetId(): String = datasetId - - fun filters(): Optional> = Optional.ofNullable(filters) - - fun limit(): Optional = Optional.ofNullable(limit) - - fun maxRootSpanId(): Optional = Optional.ofNullable(maxRootSpanId) - - fun maxXactId(): Optional = Optional.ofNullable(maxXactId) - - fun version(): Optional = Optional.ofNullable(version) - - @JvmSynthetic - internal fun getBody(): DatasetFetchPostBody { - return DatasetFetchPostBody( - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalBodyProperties, - ) +private constructor( + private val datasetId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cursor(): Optional = body.cursor() + + /** + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxRootSpanId(): Optional = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxXactId(): Optional = body.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 = body.version() + + /** + * Returns the raw JSON value of [cursor]. + * + * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _cursor(): JsonField = body._cursor() + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _limit(): JsonField = body._limit() + + /** + * Returns the raw JSON value of [maxRootSpanId]. + * + * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxRootSpanId(): JsonField = body._maxRootSpanId() + + /** + * Returns the raw JSON value of [maxXactId]. + * + * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxXactId(): JsonField = body._maxXactId() + + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _version(): JsonField = body._version() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): DatasetFetchPostParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [DatasetFetchPostParams]. */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [DatasetFetchPostParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" + @JvmSynthetic + internal fun from(datasetFetchPostParams: DatasetFetchPostParams) = apply { + datasetId = datasetFetchPostParams.datasetId + body = datasetFetchPostParams.body.toBuilder() + additionalHeaders = datasetFetchPostParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetFetchPostParams.additionalQueryParams.toBuilder() } - } - @JsonDeserialize(builder = DatasetFetchPostBody.Builder::class) - @NoAutoDetect - class DatasetFetchPostBody - internal constructor( - private val filters: List?, - private val limit: Long?, - private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalProperties: Map, - ) { + /** Dataset id */ + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } + + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [cursor] + * - [limit] + * - [maxRootSpanId] + * - [maxXactId] + * - [version] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } - private var hashCode: Int = 0 + /** + * 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?) = apply { body.cursor(cursor) } + + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * 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. */ - @JsonProperty("filters") fun filters(): List? = filters + fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } /** + * 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, @@ -98,259 +234,282 @@ constructor( * with more individual rows than the specified limit if you are fetching events containing * traces. */ - @JsonProperty("limit") fun limit(): Long? = limit + fun limit(limit: Long?) = apply { body.limit(limit) } /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("max_root_span_id") fun maxRootSpanId(): String? = maxRootSpanId + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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. */ - @JsonProperty("max_xact_id") fun maxXactId(): Long? = maxXactId + fun limit(limit: JsonField) = apply { body.limit(limit) } /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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. */ - @JsonProperty("version") fun version(): Long? = version + fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - fun toBuilder() = Builder().from(this) + /** + * 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 { + body.maxRootSpanId(maxRootSpanId) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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?) = apply { body.maxXactId(maxXactId) } - return other is DatasetFetchPostBody && - this.filters == other.filters && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties, - ) - } - return hashCode - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - override fun toString() = - "DatasetFetchPostBody{filters=$filters, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" + /** + * 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 { body.maxXactId(maxXactId) } - companion object { + /** + * 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?) = apply { body.version(version) } - @JvmStatic fun builder() = Builder() - } + /** 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 { body.version(version) } - class Builder { + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - private var filters: List? = null - private var limit: Long? = null - private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - @JvmSynthetic - internal fun from(datasetFetchPostBody: DatasetFetchPostBody) = apply { - this.filters = datasetFetchPostBody.filters - this.limit = datasetFetchPostBody.limit - this.maxRootSpanId = datasetFetchPostBody.maxRootSpanId - this.maxXactId = datasetFetchPostBody.maxXactId - this.version = datasetFetchPostBody.version - additionalProperties(datasetFetchPostBody.additionalProperties) + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters - * are supported, but we may add more in the future - */ - @JsonProperty("filters") - fun filters(filters: List) = apply { this.filters = filters } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** - * 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. - */ - @JsonProperty("limit") fun limit(limit: Long) = apply { this.limit = limit } + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine - * `max_root_span_id` as the maximum of the `root_span_id` field over all rows. See the - * documentation for `limit` for an overview of paginating fetch queries. - */ - @JsonProperty("max_root_span_id") - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` - * as the maximum of the `_xact_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. - */ - @JsonProperty("max_xact_id") - fun maxXactId(maxXactId: Long) = apply { this.maxXactId = maxXactId } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * You may specify a version id to retrieve a snapshot of the 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. - */ - @JsonProperty("version") fun version(version: Long) = apply { this.version = version } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - fun build(): DatasetFetchPostBody = - DatasetFetchPostBody( - filters?.toUnmodifiable(), - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties.toUnmodifiable(), - ) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - } - fun _additionalQueryParams(): Map> = additionalQueryParams + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun _additionalHeaders(): Map> = additionalHeaders + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun _additionalBodyProperties(): Map = additionalBodyProperties + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - return other is DatasetFetchPostParams && - this.datasetId == other.datasetId && - this.filters == other.filters && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - override fun hashCode(): Int { - return Objects.hash( - datasetId, - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - override fun toString() = - "DatasetFetchPostParams{datasetId=$datasetId, filters=$filters, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun toBuilder() = Builder().from(this) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - companion object { + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - @JvmStatic fun builder() = Builder() - } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - @NoAutoDetect - class Builder { + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - private var datasetId: String? = null - private var filters: MutableList = mutableListOf() - private var limit: Long? = null - private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - @JvmSynthetic - internal fun from(datasetFetchPostParams: DatasetFetchPostParams) = apply { - this.datasetId = datasetFetchPostParams.datasetId - this.filters(datasetFetchPostParams.filters ?: listOf()) - this.limit = datasetFetchPostParams.limit - this.maxRootSpanId = datasetFetchPostParams.maxRootSpanId - this.maxXactId = datasetFetchPostParams.maxXactId - this.version = datasetFetchPostParams.version - additionalQueryParams(datasetFetchPostParams.additionalQueryParams) - additionalHeaders(datasetFetchPostParams.additionalHeaders) - additionalBodyProperties(datasetFetchPostParams.additionalBodyProperties) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + 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) + } /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * Returns an immutable instance of [DatasetFetchPostParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. */ - fun filters(filters: List) = apply { - this.filters.clear() - this.filters.addAll(filters) + fun build(): DatasetFetchPostParams = + DatasetFetchPostParams( + datasetId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun addFilter(filter: Filter) = apply { this.filters.add(filter) } + fun cursor(): Optional = cursor.getOptional("cursor") /** + * 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, @@ -362,279 +521,378 @@ 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(): Optional = limit.getOptional("limit") /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun maxRootSpanId(): Optional = maxRootSpanId.getOptional("max_root_span_id") /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxXactId(maxXactId: Long) = apply { this.maxXactId = maxXactId } + fun maxXactId(): Optional = maxXactId.getOptional("max_xact_id") /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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(version: Long) = apply { this.version = version } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } + fun version(): Optional = version.getOptional("version") - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + /** + * 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 - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + /** + * 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 removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + /** + * 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 putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } + fun toBuilder() = Builder().from(this) - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + companion object { - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) + 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() + + @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 build(): DatasetFetchPostParams = - DatasetFetchPostParams( - checkNotNull(datasetId) { "`datasetId` is required but was not set" }, - if (filters.size == 0) null else filters.toUnmodifiable(), - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } + /** + * 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)) - /** - * A path-lookup filter describes an equality comparison against a specific sub-field in the - * event row. For instance, if you wish to filter on the value of `c` in `{"input": {"a": {"b": - * {"c": "hello"}}}}`, pass `path=["input", "a", "b", "c"]` and `value="hello"` - */ - @JsonDeserialize(builder = Filter.Builder::class) - @NoAutoDetect - class Filter - private constructor( - private val type: Type?, - private val path: List?, - private val value: JsonValue?, - private val additionalProperties: Map, - ) { + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - private var hashCode: Int = 0 + /** + * 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 } - /** Denotes the type of filter as a path-lookup filter */ - @JsonProperty("type") fun type(): Type? = type + /** + * 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)) - /** - * List of fields describing the path to the value to be checked against. For instance, if - * you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": "hello"}}}}`, pass - * `path=["input", "a", "b", "c"]` - */ - @JsonProperty("path") fun path(): List? = path + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) - /** - * The value to compare equality-wise against the event value at the specified `path`. The - * value must be a "primitive", that is, any JSON-serializable object except for objects and - * arrays. For instance, if you wish to filter on the value of "input.a.b.c" in the object - * `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `value="hello"` - */ - @JsonProperty("value") fun value(): JsonValue? = value + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** + * 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 toBuilder() = Builder().from(this) + /** + * 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)) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - return other is Filter && - this.type == other.type && - this.path == other.path && - this.value == other.value && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - type, - path, - value, - additionalProperties, - ) + /** + * 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 } - return hashCode - } - - override fun toString() = - "Filter{type=$type, path=$path, value=$value, additionalProperties=$additionalProperties}" - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var type: Type? = null - private var path: List? = null - private var value: JsonValue? = null - private var additionalProperties: MutableMap = mutableMapOf() + /** + * 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)) - @JvmSynthetic - internal fun from(filter: Filter) = apply { - this.type = filter.type - this.path = filter.path - this.value = filter.value - additionalProperties(filter.additionalProperties) - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - /** Denotes the type of filter as a path-lookup filter */ - @JsonProperty("type") fun type(type: Type) = apply { this.type = type } + /** + * 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 } /** - * List of fields describing the path to the value to be checked against. For instance, - * if you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": - * "hello"}}}}`, pass `path=["input", "a", "b", "c"]` + * 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. */ - @JsonProperty("path") fun path(path: List) = apply { this.path = path } + fun version(version: String?) = version(JsonField.ofNullable(version)) + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) /** - * The value to compare equality-wise against the event value at the specified `path`. - * The value must be a "primitive", that is, any JSON-serializable object except for - * objects and arrays. For instance, if you wish to filter on the value of "input.a.b.c" - * in the object `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `value="hello"` + * 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. */ - @JsonProperty("value") fun value(value: JsonValue) = apply { this.value = value } + fun version(version: JsonField) = apply { this.version = version } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Filter = - Filter( - checkNotNull(type) { "`type` is required but was not set" }, - checkNotNull(path) { "`path` is required but was not set" }.toUnmodifiable(), - value, - additionalProperties.toUnmodifiable(), - ) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + /** + * 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(), + ) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + private var validated: Boolean = false - return other is Type && this.value == other.value + fun validate(): Body = apply { + if (validated) { + return@apply } - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() + cursor() + limit() + maxRootSpanId() + maxXactId() + version() + validated = true + } - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - @JvmField val PATH_LOOKUP = Type(JsonField.of("path_lookup")) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @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) - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - enum class Known { - PATH_LOOKUP, - } + return other is Body && + cursor == other.cursor && + limit == other.limit && + maxRootSpanId == other.maxRootSpanId && + maxXactId == other.maxXactId && + version == other.version && + additionalProperties == other.additionalProperties + } - enum class Value { - PATH_LOOKUP, - _UNKNOWN, - } + private val hashCode: Int by lazy { + Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) + } - fun value(): Value = - when (this) { - PATH_LOOKUP -> Value.PATH_LOOKUP - else -> Value._UNKNOWN - } + override fun hashCode(): Int = hashCode - fun known(): Known = - when (this) { - PATH_LOOKUP -> Known.PATH_LOOKUP - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } + override fun toString() = + "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" + } - fun asString(): String = _value().asStringOrThrow() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } + + return other is DatasetFetchPostParams && + datasetId == other.datasetId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = + Objects.hash(datasetId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "DatasetFetchPostParams{datasetId=$datasetId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchPostResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchPostResponse.kt deleted file mode 100644 index 4b0487e7..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchPostResponse.kt +++ /dev/null @@ -1,563 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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.time.OffsetDateTime -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = DatasetFetchPostResponse.Builder::class) -@NoAutoDetect -class DatasetFetchPostResponse -private constructor( - private val events: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** A list of fetched events */ - fun events(): List = events.getRequired("events") - - /** A list of fetched events */ - @JsonProperty("events") @ExcludeMissing fun _events() = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): DatasetFetchPostResponse = apply { - if (!validated) { - events().forEach { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetFetchPostResponse && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "DatasetFetchPostResponse{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(datasetFetchPostResponse: DatasetFetchPostResponse) = apply { - this.events = datasetFetchPostResponse.events - additionalProperties(datasetFetchPostResponse.additionalProperties) - } - - /** A list of fetched events */ - fun events(events: List) = events(JsonField.of(events)) - - /** A list of fetched events */ - @JsonProperty("events") - @ExcludeMissing - fun events(events: JsonField>) = apply { this.events = events } - - 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(): DatasetFetchPostResponse = - DatasetFetchPostResponse( - events.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } - - @JsonDeserialize(builder = Event.Builder::class) - @NoAutoDetect - class Event - private constructor( - private val id: JsonField, - private val _xactId: JsonField, - private val created: JsonField, - private val projectId: JsonField, - private val datasetId: JsonField, - private val input: JsonValue, - private val output: JsonValue, - private val metadata: JsonField, - private val spanId: JsonField, - private val rootSpanId: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): String = id.getRequired("id") - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - fun _xactId(): Long = _xactId.getRequired("_xact_id") - - /** The timestamp the dataset event was created */ - fun created(): Optional = - Optional.ofNullable(created.getNullable("created")) - - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(): Optional = Optional.ofNullable(projectId.getNullable("project_id")) - - /** Unique identifier for the dataset */ - fun datasetId(): String = datasetId.getRequired("dataset_id") - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable object) - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - fun output(): JsonValue = output - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - fun spanId(): String = spanId.getRequired("span_id") - - /** The `span_id` of the root of the trace this dataset event belongs to */ - fun rootSpanId(): String = rootSpanId.getRequired("root_span_id") - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - @JsonProperty("_xact_id") @ExcludeMissing fun __xactId() = _xactId - - /** The timestamp the dataset event was created */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId - - /** Unique identifier for the dataset */ - @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId() = datasetId - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable object) - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - @JsonProperty("span_id") @ExcludeMissing fun _spanId() = spanId - - /** The `span_id` of the root of the trace this dataset event belongs to */ - @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId() = rootSpanId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Event = apply { - if (!validated) { - id() - _xactId() - created() - projectId() - datasetId() - input() - output() - metadata().map { it.validate() } - spanId() - rootSpanId() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Event && - this.id == other.id && - this._xactId == other._xactId && - this.created == other.created && - this.projectId == other.projectId && - this.datasetId == other.datasetId && - this.input == other.input && - this.output == other.output && - this.metadata == other.metadata && - this.spanId == other.spanId && - this.rootSpanId == other.rootSpanId && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - _xactId, - created, - projectId, - datasetId, - input, - output, - metadata, - spanId, - rootSpanId, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Event{id=$id, _xactId=$_xactId, created=$created, projectId=$projectId, datasetId=$datasetId, input=$input, output=$output, metadata=$metadata, spanId=$spanId, rootSpanId=$rootSpanId, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var id: JsonField = JsonMissing.of() - private var _xactId: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var datasetId: JsonField = JsonMissing.of() - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var spanId: JsonField = JsonMissing.of() - private var rootSpanId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(event: Event) = apply { - this.id = event.id - this._xactId = event._xactId - this.created = event.created - this.projectId = event.projectId - this.datasetId = event.datasetId - this.input = event.input - this.output = event.output - this.metadata = event.metadata - this.spanId = event.spanId - this.rootSpanId = event.rootSpanId - additionalProperties(event.additionalProperties) - } - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - fun _xactId(_xactId: Long) = _xactId(JsonField.of(_xactId)) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - @JsonProperty("_xact_id") - @ExcludeMissing - fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } - - /** The timestamp the dataset event was created */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** The timestamp the dataset event was created */ - @JsonProperty("created") - @ExcludeMissing - fun created(created: JsonField) = apply { this.created = created } - - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the dataset */ - fun datasetId(datasetId: String) = datasetId(JsonField.of(datasetId)) - - /** Unique identifier for the dataset */ - @JsonProperty("dataset_id") - @ExcludeMissing - fun datasetId(datasetId: JsonField) = apply { this.datasetId = datasetId } - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) - * for full details on tracing - */ - fun spanId(spanId: String) = spanId(JsonField.of(spanId)) - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) - * for full details on tracing - */ - @JsonProperty("span_id") - @ExcludeMissing - fun spanId(spanId: JsonField) = apply { this.spanId = spanId } - - /** The `span_id` of the root of the trace this dataset event belongs to */ - fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) - - /** The `span_id` of the root of the trace this dataset event belongs to */ - @JsonProperty("root_span_id") - @ExcludeMissing - fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } - - 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(): Event = - Event( - id, - _xactId, - created, - projectId, - datasetId, - input, - output, - metadata, - spanId, - rootSpanId, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchResponse.kt deleted file mode 100644 index ffbf1d15..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetFetchResponse.kt +++ /dev/null @@ -1,563 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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.time.OffsetDateTime -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = DatasetFetchResponse.Builder::class) -@NoAutoDetect -class DatasetFetchResponse -private constructor( - private val events: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** A list of fetched events */ - fun events(): List = events.getRequired("events") - - /** A list of fetched events */ - @JsonProperty("events") @ExcludeMissing fun _events() = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): DatasetFetchResponse = apply { - if (!validated) { - events().forEach { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetFetchResponse && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "DatasetFetchResponse{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(datasetFetchResponse: DatasetFetchResponse) = apply { - this.events = datasetFetchResponse.events - additionalProperties(datasetFetchResponse.additionalProperties) - } - - /** A list of fetched events */ - fun events(events: List) = events(JsonField.of(events)) - - /** A list of fetched events */ - @JsonProperty("events") - @ExcludeMissing - fun events(events: JsonField>) = apply { this.events = events } - - 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(): DatasetFetchResponse = - DatasetFetchResponse( - events.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } - - @JsonDeserialize(builder = Event.Builder::class) - @NoAutoDetect - class Event - private constructor( - private val id: JsonField, - private val _xactId: JsonField, - private val created: JsonField, - private val projectId: JsonField, - private val datasetId: JsonField, - private val input: JsonValue, - private val output: JsonValue, - private val metadata: JsonField, - private val spanId: JsonField, - private val rootSpanId: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): String = id.getRequired("id") - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - fun _xactId(): Long = _xactId.getRequired("_xact_id") - - /** The timestamp the dataset event was created */ - fun created(): Optional = - Optional.ofNullable(created.getNullable("created")) - - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(): Optional = Optional.ofNullable(projectId.getNullable("project_id")) - - /** Unique identifier for the dataset */ - fun datasetId(): String = datasetId.getRequired("dataset_id") - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable object) - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - fun output(): JsonValue = output - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - fun spanId(): String = spanId.getRequired("span_id") - - /** The `span_id` of the root of the trace this dataset event belongs to */ - fun rootSpanId(): String = rootSpanId.getRequired("root_span_id") - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - @JsonProperty("_xact_id") @ExcludeMissing fun __xactId() = _xactId - - /** The timestamp the dataset event was created */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId - - /** Unique identifier for the dataset */ - @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId() = datasetId - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable object) - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - @JsonProperty("span_id") @ExcludeMissing fun _spanId() = spanId - - /** The `span_id` of the root of the trace this dataset event belongs to */ - @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId() = rootSpanId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Event = apply { - if (!validated) { - id() - _xactId() - created() - projectId() - datasetId() - input() - output() - metadata().map { it.validate() } - spanId() - rootSpanId() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Event && - this.id == other.id && - this._xactId == other._xactId && - this.created == other.created && - this.projectId == other.projectId && - this.datasetId == other.datasetId && - this.input == other.input && - this.output == other.output && - this.metadata == other.metadata && - this.spanId == other.spanId && - this.rootSpanId == other.rootSpanId && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - _xactId, - created, - projectId, - datasetId, - input, - output, - metadata, - spanId, - rootSpanId, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Event{id=$id, _xactId=$_xactId, created=$created, projectId=$projectId, datasetId=$datasetId, input=$input, output=$output, metadata=$metadata, spanId=$spanId, rootSpanId=$rootSpanId, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var id: JsonField = JsonMissing.of() - private var _xactId: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var datasetId: JsonField = JsonMissing.of() - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var spanId: JsonField = JsonMissing.of() - private var rootSpanId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(event: Event) = apply { - this.id = event.id - this._xactId = event._xactId - this.created = event.created - this.projectId = event.projectId - this.datasetId = event.datasetId - this.input = event.input - this.output = event.output - this.metadata = event.metadata - this.spanId = event.spanId - this.rootSpanId = event.rootSpanId - additionalProperties(event.additionalProperties) - } - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - fun _xactId(_xactId: Long) = _xactId(JsonField.of(_xactId)) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the dataset (see the `version` parameter) - */ - @JsonProperty("_xact_id") - @ExcludeMissing - fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } - - /** The timestamp the dataset event was created */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** The timestamp the dataset event was created */ - @JsonProperty("created") - @ExcludeMissing - fun created(created: JsonField) = apply { this.created = created } - - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the dataset */ - fun datasetId(datasetId: String) = datasetId(JsonField.of(datasetId)) - - /** Unique identifier for the dataset */ - @JsonProperty("dataset_id") - @ExcludeMissing - fun datasetId(datasetId: JsonField) = apply { this.datasetId = datasetId } - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) - * for full details on tracing - */ - fun spanId(spanId: String) = spanId(JsonField.of(spanId)) - - /** - * A unique identifier used to link different dataset events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) - * for full details on tracing - */ - @JsonProperty("span_id") - @ExcludeMissing - fun spanId(spanId: JsonField) = apply { this.spanId = spanId } - - /** The `span_id` of the root of the trace this dataset event belongs to */ - fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) - - /** The `span_id` of the root of the trace this dataset event belongs to */ - @JsonProperty("root_span_id") - @ExcludeMissing - fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } - - 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(): Event = - Event( - id, - _xactId, - created, - projectId, - datasetId, - input, - output, - metadata, - spanId, - rootSpanId, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - } -} 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 old mode 100644 new mode 100755 index 74764255..b9537932 --- 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 @@ -2,1354 +2,469 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer 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.getOrThrow -import com.braintrustdata.api.core.toUnmodifiable +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.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Insert a set of events into the dataset */ class DatasetInsertParams -constructor( - private val datasetId: String, - private val events: List, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun datasetId(): String = datasetId - - fun events(): List = events - - @JvmSynthetic - internal fun getBody(): DatasetInsertBody { - return DatasetInsertBody(events, additionalBodyProperties) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } - } - - @JsonDeserialize(builder = DatasetInsertBody.Builder::class) - @NoAutoDetect - class DatasetInsertBody - internal constructor( - private val events: List?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** A list of dataset events to insert */ - @JsonProperty("events") fun events(): List? = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetInsertBody && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "DatasetInsertBody{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: List? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(datasetInsertBody: DatasetInsertBody) = apply { - this.events = datasetInsertBody.events - additionalProperties(datasetInsertBody.additionalProperties) - } - - /** A list of dataset events to insert */ - @JsonProperty("events") fun events(events: List) = apply { this.events = events } - - 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(): DatasetInsertBody = - DatasetInsertBody( - checkNotNull(events) { "`events` is required but was not set" } - .toUnmodifiable(), - additionalProperties.toUnmodifiable() - ) - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetInsertParams && - this.datasetId == other.datasetId && - this.events == other.events && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int { - return Objects.hash( - datasetId, - events, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "DatasetInsertParams{datasetId=$datasetId, events=$events, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" +private constructor( + private val datasetId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + + /** + * 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 = body.events() + + /** + * Returns the raw JSON value of [events]. + * + * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _events(): JsonField> = body._events() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [DatasetInsertParams]. + * + * The following fields are required: + * ```java + * .events() + * ``` + */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [DatasetInsertParams]. */ + class Builder internal constructor() { private var datasetId: String? = null - private var events: MutableList = mutableListOf() - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + 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(datasetInsertParams: DatasetInsertParams) = apply { - this.datasetId = datasetInsertParams.datasetId - this.events(datasetInsertParams.events) - additionalQueryParams(datasetInsertParams.additionalQueryParams) - additionalHeaders(datasetInsertParams.additionalHeaders) - additionalBodyProperties(datasetInsertParams.additionalBodyProperties) + datasetId = datasetInsertParams.datasetId + body = datasetInsertParams.body.toBuilder() + additionalHeaders = datasetInsertParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetInsertParams.additionalQueryParams.toBuilder() } /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } - /** A list of dataset events to insert */ - fun events(events: List) = apply { - this.events.clear() - this.events.addAll(events) - } + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [events] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } /** A list of dataset events to insert */ - fun addEvent(event: Event) = apply { this.events.add(event) } + fun events(events: List) = apply { body.events(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 { body.events(events) } + + /** + * Adds a single [InsertDatasetEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: InsertDatasetEvent) = apply { body.addEvent(event) } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } fun additionalHeaders(additionalHeaders: Map>) = apply { this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + putAllAdditionalHeaders(additionalHeaders) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun build(): DatasetInsertParams = - DatasetInsertParams( - checkNotNull(datasetId) { "`datasetId` is required but was not set" }, - checkNotNull(events) { "`events` is required but was not set" }.toUnmodifiable(), - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - @JsonDeserialize(using = Event.Deserializer::class) - @JsonSerialize(using = Event.Serializer::class) - class Event - private constructor( - private val insertDatasetEventReplace: InsertDatasetEventReplace? = null, - private val insertDatasetEventMerge: InsertDatasetEventMerge? = null, - private val _json: JsonValue? = null, - ) { + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - private var validated: Boolean = false + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun insertDatasetEventReplace(): Optional = - Optional.ofNullable(insertDatasetEventReplace) - fun insertDatasetEventMerge(): Optional = - Optional.ofNullable(insertDatasetEventMerge) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun isInsertDatasetEventReplace(): Boolean = insertDatasetEventReplace != null - fun isInsertDatasetEventMerge(): Boolean = insertDatasetEventMerge != null + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun asInsertDatasetEventReplace(): InsertDatasetEventReplace = - insertDatasetEventReplace.getOrThrow("insertDatasetEventReplace") - fun asInsertDatasetEventMerge(): InsertDatasetEventMerge = - insertDatasetEventMerge.getOrThrow("insertDatasetEventMerge") + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun _json(): Optional = Optional.ofNullable(_json) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun accept(visitor: Visitor): T { - return when { - insertDatasetEventReplace != null -> - visitor.visitInsertDatasetEventReplace(insertDatasetEventReplace) - insertDatasetEventMerge != null -> - visitor.visitInsertDatasetEventMerge(insertDatasetEventMerge) - else -> visitor.unknown(_json) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun validate(): Event = apply { - if (!validated) { - if (insertDatasetEventReplace == null && insertDatasetEventMerge == null) { - throw BraintrustInvalidDataException("Unknown Event: $_json") - } - insertDatasetEventReplace?.validate() - insertDatasetEventMerge?.validate() - validated = true - } + 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 other is Event && - this.insertDatasetEventReplace == other.insertDatasetEventReplace && - this.insertDatasetEventMerge == other.insertDatasetEventMerge + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - override fun hashCode(): Int { - return Objects.hash(insertDatasetEventReplace, insertDatasetEventMerge) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) } - override fun toString(): String { - return when { - insertDatasetEventReplace != null -> - "Event{insertDatasetEventReplace=$insertDatasetEventReplace}" - insertDatasetEventMerge != null -> - "Event{insertDatasetEventMerge=$insertDatasetEventMerge}" - _json != null -> "Event{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Event") - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - companion object { + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - @JvmStatic - fun ofInsertDatasetEventReplace(insertDatasetEventReplace: InsertDatasetEventReplace) = - Event(insertDatasetEventReplace = insertDatasetEventReplace) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - @JvmStatic - fun ofInsertDatasetEventMerge(insertDatasetEventMerge: InsertDatasetEventMerge) = - Event(insertDatasetEventMerge = insertDatasetEventMerge) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) } - interface Visitor { - - fun visitInsertDatasetEventReplace( - insertDatasetEventReplace: InsertDatasetEventReplace - ): T + /** + * Returns an immutable instance of [DatasetInsertParams]. + * + * 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(): DatasetInsertParams = + DatasetInsertParams( + datasetId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } - fun visitInsertDatasetEventMerge(insertDatasetEventMerge: InsertDatasetEventMerge): T + fun _body(): Body = body - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Event: $json") - } + fun _pathParam(index: Int): String = + when (index) { + 0 -> datasetId ?: "" + else -> "" } - class Deserializer : BaseDeserializer(Event::class) { + override fun _headers(): Headers = additionalHeaders - override fun ObjectCodec.deserialize(node: JsonNode): Event { - val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Event(insertDatasetEventReplace = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Event(insertDatasetEventMerge = it, _json = json) - } + override fun _queryParams(): QueryParams = additionalQueryParams - return Event(_json = json) - } - } - - class Serializer : BaseSerializer(Event::class) { - - override fun serialize( - value: Event, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.insertDatasetEventReplace != null -> - generator.writeObject(value.insertDatasetEventReplace) - value.insertDatasetEventMerge != null -> - generator.writeObject(value.insertDatasetEventMerge) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Event") - } - } - } + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val events: JsonField>, + private val additionalProperties: MutableMap, + ) { - @JsonDeserialize(builder = InsertDatasetEventReplace.Builder::class) - @NoAutoDetect - class InsertDatasetEventReplace + @JsonCreator private constructor( - private val input: JsonValue, - private val output: JsonValue, - private val metadata: JsonField, - private val id: JsonField, - private val _objectDelete: JsonField, - private val _isMerge: JsonField, - private val _parentId: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - fun output(): JsonValue = output + @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 - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will not - * show up in subsequent fetches for this dataset - */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) + fun toBuilder() = Builder().from(this) - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - fun _isMerge(): Optional = - Optional.ofNullable(_isMerge.getNullable("_is_merge")) + companion object { /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical relationships - * are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). + * Returns a mutable builder for constructing an instance of [Body]. * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", - * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the - * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": - * "What comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, - * only the root span row `"abc"` will show up in the summary view. You can view the - * full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" - * row. + * The following fields are required: + * ```java + * .events() + * ``` */ - fun _parentId(): Optional = - Optional.ofNullable(_parentId.getNullable("_parent_id")) - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input + @JvmStatic fun builder() = Builder() + } - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output + /** A builder for [Body]. */ + class Builder internal constructor() { - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata + private var events: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id + @JvmSynthetic + internal fun from(body: Body) = apply { + events = body.events.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will not - * show up in subsequent fetches for this dataset - */ - @JsonProperty("_object_delete") @ExcludeMissing fun __objectDelete() = _objectDelete + /** A list of dataset events to insert */ + fun events(events: List) = events(JsonField.of(events)) /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row + * Sets [Builder.events] to an arbitrary JSON value. * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` + * 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. */ - @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge() = _isMerge + fun events(events: JsonField>) = apply { + this.events = events.map { it.toMutableList() } + } /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical relationships - * are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). + * Adds a single [InsertDatasetEvent] to [events]. * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", - * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the - * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": - * "What comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, - * only the root span row `"abc"` will show up in the summary view. You can view the - * full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" - * row. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("_parent_id") @ExcludeMissing fun __parentId() = _parentId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): InsertDatasetEventReplace = apply { - if (!validated) { - input() - output() - metadata().map { it.validate() } - id() - _objectDelete() - _isMerge() - _parentId() - validated = true - } + fun addEvent(event: InsertDatasetEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InsertDatasetEventReplace && - this.input == other.input && - this.output == other.output && - this.metadata == other.metadata && - this.id == other.id && - this._objectDelete == other._objectDelete && - this._isMerge == other._isMerge && - this._parentId == other._parentId && - this.additionalProperties == other.additionalProperties + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - input, - output, - metadata, - id, - _objectDelete, - _isMerge, - _parentId, - additionalProperties, - ) - } - return hashCode + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) } - override fun toString() = - "InsertDatasetEventReplace{input=$input, output=$output, metadata=$metadata, id=$id, _objectDelete=$_objectDelete, _isMerge=$_isMerge, _parentId=$_parentId, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) } - class Builder { - - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var id: JsonField = JsonMissing.of() - private var _objectDelete: JsonField = JsonMissing.of() - private var _isMerge: JsonField = JsonMissing.of() - private var _parentId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(insertDatasetEventReplace: InsertDatasetEventReplace) = apply { - this.input = insertDatasetEventReplace.input - this.output = insertDatasetEventReplace.output - this.metadata = insertDatasetEventReplace.metadata - this.id = insertDatasetEventReplace.id - this._objectDelete = insertDatasetEventReplace._objectDelete - this._isMerge = insertDatasetEventReplace._isMerge - this._parentId = insertDatasetEventReplace._parentId - additionalProperties(insertDatasetEventReplace.additionalProperties) - } - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will - * not show up in subsequent fetches for this dataset - */ - fun _objectDelete(_objectDelete: Boolean) = - _objectDelete(JsonField.of(_objectDelete)) - - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will - * not show up in subsequent fetches for this dataset - */ - @JsonProperty("_object_delete") - @ExcludeMissing - fun _objectDelete(_objectDelete: JsonField) = apply { - this._objectDelete = _objectDelete - } - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - fun _isMerge(_isMerge: Boolean) = _isMerge(JsonField.of(_isMerge)) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - @JsonProperty("_is_merge") - @ExcludeMissing - fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } - - /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical - * relationships are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). - * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": - * "bar", "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a - * sub-span of the parent row by logging `{"_parent_id": "abc", "id": "llm_call", - * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": - * {"tokens": 1}}`. In the webapp, only the root span row `"abc"` will show up in - * the summary view. You can view the full trace hierarchy (in this case, the - * `"llm_call"` row) by clicking on the "abc" row. - */ - fun _parentId(_parentId: String) = _parentId(JsonField.of(_parentId)) - - /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical - * relationships are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). - * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": - * "bar", "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a - * sub-span of the parent row by logging `{"_parent_id": "abc", "id": "llm_call", - * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": - * {"tokens": 1}}`. In the webapp, only the root span row `"abc"` will show up in - * the summary view. You can view the full trace hierarchy (in this case, the - * `"llm_call"` row) by clicking on the "abc" row. - */ - @JsonProperty("_parent_id") - @ExcludeMissing - fun _parentId(_parentId: JsonField) = apply { this._parentId = _parentId } - - 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 removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun build(): InsertDatasetEventReplace = - InsertDatasetEventReplace( - input, - output, - metadata, - id, - _objectDelete, - _isMerge, - _parentId, - additionalProperties.toUnmodifiable(), - ) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - } - - @JsonDeserialize(builder = InsertDatasetEventMerge.Builder::class) - @NoAutoDetect - class InsertDatasetEventMerge - private constructor( - private val input: JsonValue, - private val output: JsonValue, - private val metadata: JsonField, - private val id: JsonField, - private val _objectDelete: JsonField, - private val _isMerge: JsonField, - private val _mergePaths: JsonField>>, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - fun output(): JsonValue = output - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will not - * show up in subsequent fetches for this dataset - */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - fun _isMerge(): Boolean = _isMerge.getRequired("_is_merge") - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only be - * specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where each - * path is a list of field names. The deep merge will not descend below any of the - * specified merge paths. + * Returns an immutable instance of [Body]. * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be - * `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, - * "output": {"d": 40}}`. In this case, due to the merge paths, we have replaced - * `input.a` and `output`, but have still deep-merged `input` and `input.c`. - */ - fun _mergePaths(): Optional>> = - Optional.ofNullable(_mergePaths.getNullable("_merge_paths")) - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will not - * show up in subsequent fetches for this dataset - */ - @JsonProperty("_object_delete") @ExcludeMissing fun __objectDelete() = _objectDelete - - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row + * Further updates to this [Builder] will not mutate the returned instance. * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge() = _isMerge - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only be - * specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where each - * path is a list of field names. The deep merge will not descend below any of the - * specified merge paths. + * The following fields are required: + * ```java + * .events() + * ``` * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be - * `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, - * "output": {"d": 40}}`. In this case, due to the merge paths, we have replaced - * `input.a` and `output`, but have still deep-merged `input` and `input.c`. + * @throws IllegalStateException if any required field is unset. */ - @JsonProperty("_merge_paths") @ExcludeMissing fun __mergePaths() = _mergePaths - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): InsertDatasetEventMerge = apply { - if (!validated) { - input() - output() - metadata().map { it.validate() } - id() - _objectDelete() - _isMerge() - _mergePaths() - validated = true - } - } + fun build(): Body = + Body( + checkRequired("events", events).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InsertDatasetEventMerge && - this.input == other.input && - this.output == other.output && - this.metadata == other.metadata && - this.id == other.id && - this._objectDelete == other._objectDelete && - this._isMerge == other._isMerge && - this._mergePaths == other._mergePaths && - this.additionalProperties == other.additionalProperties - } + private var validated: Boolean = false - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - input, - output, - metadata, - id, - _objectDelete, - _isMerge, - _mergePaths, - additionalProperties, - ) - } - return hashCode + fun validate(): Body = apply { + if (validated) { + return@apply } - override fun toString() = - "InsertDatasetEventMerge{input=$input, output=$output, metadata=$metadata, id=$id, _objectDelete=$_objectDelete, _isMerge=$_isMerge, _mergePaths=$_mergePaths, additionalProperties=$additionalProperties}" - - companion object { + events().forEach { it.validate() } + validated = true + } - @JvmStatic fun builder() = Builder() + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - class Builder { - - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var id: JsonField = JsonMissing.of() - private var _objectDelete: JsonField = JsonMissing.of() - private var _isMerge: JsonField = JsonMissing.of() - private var _mergePaths: JsonField>> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(insertDatasetEventMerge: InsertDatasetEventMerge) = apply { - this.input = insertDatasetEventMerge.input - this.output = insertDatasetEventMerge.output - this.metadata = insertDatasetEventMerge.metadata - this.id = insertDatasetEventMerge.id - this._objectDelete = insertDatasetEventMerge._objectDelete - this._isMerge = insertDatasetEventMerge._isMerge - this._mergePaths = insertDatasetEventMerge._mergePaths - additionalProperties(insertDatasetEventMerge.additionalProperties) - } - - /** - * The argument that uniquely define an input case (an arbitrary, JSON serializable - * object) - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object) - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the dataset event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will - * not show up in subsequent fetches for this dataset - */ - fun _objectDelete(_objectDelete: Boolean) = - _objectDelete(JsonField.of(_objectDelete)) - - /** - * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will - * not show up in subsequent fetches for this dataset - */ - @JsonProperty("_object_delete") - @ExcludeMissing - fun _objectDelete(_objectDelete: JsonField) = apply { - this._objectDelete = _objectDelete - } - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - fun _isMerge(_isMerge: Boolean) = _isMerge(JsonField.of(_isMerge)) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - @JsonProperty("_is_merge") - @ExcludeMissing - fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only - * be specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where - * each path is a list of field names. The deep merge will not descend below any of - * the specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will - * be `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": - * "baz"}, "output": {"d": 40}}`. In this case, due to the merge paths, we have - * replaced `input.a` and `output`, but have still deep-merged `input` and - * `input.c`. - */ - fun _mergePaths(_mergePaths: List>) = - _mergePaths(JsonField.of(_mergePaths)) - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only - * be specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where - * each path is a list of field names. The deep merge will not descend below any of - * the specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will - * be `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": - * "baz"}, "output": {"d": 40}}`. In this case, due to the merge paths, we have - * replaced `input.a` and `output`, but have still deep-merged `input` and - * `input.c`. - */ - @JsonProperty("_merge_paths") - @ExcludeMissing - fun _mergePaths(_mergePaths: JsonField>>) = apply { - this._mergePaths = _mergePaths - } - - 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) - } + /** + * Returns 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) - fun build(): InsertDatasetEventMerge = - InsertDatasetEventMerge( - input, - output, - metadata, - id, - _objectDelete, - _isMerge, - _mergePaths.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable(), - ) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } + return other is Body && + events == other.events && + additionalProperties == other.additionalProperties + } - class Builder { + private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } - private var additionalProperties: MutableMap = mutableMapOf() + override fun hashCode(): Int = hashCode - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } + override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } + return other is DatasetInsertParams && + datasetId == other.datasetId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } + override fun hashCode(): Int = + Objects.hash(datasetId, body, additionalHeaders, additionalQueryParams) - fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - } - } + override fun toString() = + "DatasetInsertParams{datasetId=$datasetId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetInsertResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetInsertResponse.kt deleted file mode 100644 index 831b00ef..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetInsertResponse.kt +++ /dev/null @@ -1,122 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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.Objects - -@JsonDeserialize(builder = DatasetInsertResponse.Builder::class) -@NoAutoDetect -class DatasetInsertResponse -private constructor( - private val rowIds: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as input - */ - fun rowIds(): List = rowIds.getRequired("row_ids") - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as input - */ - @JsonProperty("row_ids") @ExcludeMissing fun _rowIds() = rowIds - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): DatasetInsertResponse = apply { - if (!validated) { - rowIds() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetInsertResponse && - this.rowIds == other.rowIds && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(rowIds, additionalProperties) - } - return hashCode - } - - override fun toString() = - "DatasetInsertResponse{rowIds=$rowIds, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var rowIds: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(datasetInsertResponse: DatasetInsertResponse) = apply { - this.rowIds = datasetInsertResponse.rowIds - additionalProperties(datasetInsertResponse.additionalProperties) - } - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as - * input - */ - fun rowIds(rowIds: List) = rowIds(JsonField.of(rowIds)) - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as - * input - */ - @JsonProperty("row_ids") - @ExcludeMissing - fun rowIds(rowIds: JsonField>) = apply { this.rowIds = rowIds } - - 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(): DatasetInsertResponse = - DatasetInsertResponse( - rowIds.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } -} 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 old mode 100644 new mode 100755 index 0e34b802..6c7094af --- 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,192 +2,124 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +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.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull +/** @see DatasetService.list */ class DatasetListPage private constructor( - private val datasetService: DatasetService, + private val service: DatasetService, private val params: DatasetListParams, - private val response: Response, -) { + private val response: DatasetListPageResponse, +) : Page { - 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 items(): List = objects() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetListPage && - this.datasetService == other.datasetService && - this.params == other.params && - this.response == other.response - } - - override fun hashCode(): Int { - return Objects.hash( - datasetService, - params, - response, - ) - } - - override fun toString() = - "DatasetListPage{datasetService=$datasetService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + override fun hasNextPage(): Boolean = items().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() - ) + fun nextPageParams(): DatasetListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() } else { - Optional.of( - DatasetListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() } - } - - fun getNextPage(): Optional { - return getNextPageParams().map { datasetService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(datasetService: DatasetService, params: DatasetListParams, response: Response) = - DatasetListPage( - datasetService, - params, - response, - ) - } - @JsonDeserialize(builder = Response.Builder::class) - @NoAutoDetect - class Response - constructor( - private val objects: JsonField>, - private val additionalProperties: Map, - ) { + override fun nextPage(): DatasetListPage = service.list(nextPageParams()) - private var validated: Boolean = false + fun autoPager(): AutoPager = AutoPager.from(this) - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The parameters that were used to request this page. */ + fun params(): DatasetListParams = params - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) + /** The response that this page was parsed from. */ + fun response(): DatasetListPageResponse = response - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun toBuilder() = Builder().from(this) - fun validate(): Response = apply { - if (!validated) { - objects().map { it.validate() } - validated = true - } - } + companion object { - fun toBuilder() = Builder().from(this) + /** + * 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 equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** A builder for [DatasetListPage]. */ + class Builder internal constructor() { - return other is Response && - this.objects == other.objects && - this.additionalProperties == other.additionalProperties - } + private var service: DatasetService? = null + private var params: DatasetListParams? = null + private var response: DatasetListPageResponse? = null - override fun hashCode(): Int { - return Objects.hash(objects, additionalProperties) + @JvmSynthetic + internal fun from(datasetListPage: DatasetListPage) = apply { + service = datasetListPage.service + params = datasetListPage.params + response = datasetListPage.response } - override fun toString() = - "DatasetListPage.Response{objects=$objects, additionalProperties=$additionalProperties}" - - companion object { + 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), + ) + } - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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)) - - @JsonProperty("objects") - fun objects(objects: JsonField>) = apply { this.objects = objects } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(objects, additionalProperties.toUnmodifiable()) - } + return other is DatasetListPage && + service == other.service && + params == other.params && + response == other.response } - class AutoPager - constructor( - private val firstPage: DatasetListPage, - ) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.objects().size) { - yield(page.objects()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } + override fun hashCode(): Int = Objects.hash(service, params, response) - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } + 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 old mode 100644 new mode 100755 index 39698676..b198e6a7 --- 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,202 +2,138 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +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.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize 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 +/** @see DatasetServiceAsync.list */ class DatasetListPageAsync private constructor( - private val datasetService: DatasetServiceAsync, + private val service: DatasetServiceAsync, + private val streamHandlerExecutor: Executor, private val params: DatasetListParams, - private val response: Response, -) { + private val response: DatasetListPageResponse, +) : PageAsync { - 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 items(): List = objects() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetListPageAsync && - this.datasetService == other.datasetService && - this.params == other.params && - this.response == other.response - } - - override fun hashCode(): Int { - return Objects.hash( - datasetService, - params, - response, - ) - } - - override fun toString() = - "DatasetListPageAsync{datasetService=$datasetService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } + override fun hasNextPage(): Boolean = items().isNotEmpty() - return if (params.endingBefore().isPresent) { - Optional.of( - DatasetListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) + fun nextPageParams(): DatasetListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() } else { - Optional.of( - DatasetListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() } - } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { datasetService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) - fun autoPager(): AutoPager = AutoPager(this) + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) - companion object { + /** The parameters that were used to request this page. */ + fun params(): DatasetListParams = params - @JvmStatic - fun of(datasetService: DatasetServiceAsync, params: DatasetListParams, response: Response) = - DatasetListPageAsync( - datasetService, - params, - response, - ) - } + /** The response that this page was parsed from. */ + fun response(): DatasetListPageResponse = response - @JsonDeserialize(builder = Response.Builder::class) - @NoAutoDetect - class Response - constructor( - private val objects: JsonField>, - private val additionalProperties: Map, - ) { + fun toBuilder() = Builder().from(this) - private var validated: Boolean = false + companion object { - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** + * Returns a mutable builder for constructing an instance of [DatasetListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) + /** A builder for [DatasetListPageAsync]. */ + class Builder internal constructor() { - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + private var service: DatasetServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: DatasetListParams? = null + private var response: DatasetListPageResponse? = null - fun validate(): Response = apply { - if (!validated) { - objects().map { it.validate() } - validated = true - } + @JvmSynthetic + internal fun from(datasetListPageAsync: DatasetListPageAsync) = apply { + service = datasetListPageAsync.service + streamHandlerExecutor = datasetListPageAsync.streamHandlerExecutor + params = datasetListPageAsync.params + response = datasetListPageAsync.response } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Response && - this.objects == other.objects && - this.additionalProperties == other.additionalProperties - } + fun service(service: DatasetServiceAsync) = apply { this.service = service } - override fun hashCode(): Int { - return Objects.hash(objects, additionalProperties) + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor } - override fun toString() = - "DatasetListPageAsync.Response{objects=$objects, additionalProperties=$additionalProperties}" - - companion object { + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): DatasetListPageAsync = + DatasetListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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)) - - @JsonProperty("objects") - fun objects(objects: JsonField>) = apply { this.objects = objects } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(objects, additionalProperties.toUnmodifiable()) - } + return other is DatasetListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response } - class AutoPager - constructor( - private val firstPage: DatasetListPageAsync, - ) { - - fun forEach(action: Predicate, executor: Executor): CompletableFuture { - fun CompletableFuture>.forEach( - action: (Dataset) -> Boolean, - executor: Executor - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.objects().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } + override fun toString() = + "DatasetListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..cd29a6ab --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is DatasetListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 old mode 100644 new mode 100755 index 6cb4d8cc..cee6532b --- 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,194 +2,432 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +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.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * List out all datasets. The datasets are sorted by creation date, with the most recently-created + * datasets coming first + */ class DatasetListParams -constructor( +private constructor( private val datasetName: String?, private val endingBefore: String?, + private val ids: Ids?, private val limit: Long?, private val orgName: String?, + private val projectId: String?, private val projectName: String?, private val startingAfter: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + /** Name of the dataset to search for */ fun datasetName(): Optional = Optional.ofNullable(datasetName) + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ fun limit(): Optional = Optional.ofNullable(limit) + /** Filter search results to within a particular organization */ fun orgName(): Optional = Optional.ofNullable(orgName) + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** Name of the project to search for */ fun projectName(): Optional = Optional.ofNullable(projectName) + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ fun startingAfter(): Optional = Optional.ofNullable(startingAfter) - @JvmSynthetic - internal fun getQueryParams(): Map> { - val params = mutableMapOf>() - this.datasetName?.let { params.put("dataset_name", listOf(it.toString())) } - this.endingBefore?.let { params.put("ending_before", listOf(it.toString())) } - this.limit?.let { params.put("limit", listOf(it.toString())) } - this.orgName?.let { params.put("org_name", listOf(it.toString())) } - this.projectName?.let { params.put("project_name", listOf(it.toString())) } - this.startingAfter?.let { params.put("starting_after", listOf(it.toString())) } - params.putAll(additionalQueryParams) - return params.toUnmodifiable() - } - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetListParams && - this.datasetName == other.datasetName && - this.endingBefore == other.endingBefore && - this.limit == other.limit && - this.orgName == other.orgName && - this.projectName == other.projectName && - this.startingAfter == other.startingAfter && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } - - override fun hashCode(): Int { - return Objects.hash( - datasetName, - endingBefore, - limit, - orgName, - projectName, - startingAfter, - additionalQueryParams, - additionalHeaders, - ) - } + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - override fun toString() = - "DatasetListParams{datasetName=$datasetName, endingBefore=$endingBefore, limit=$limit, orgName=$orgName, projectName=$projectName, startingAfter=$startingAfter, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): DatasetListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [DatasetListParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [DatasetListParams]. */ + class Builder internal constructor() { private var datasetName: String? = null private var endingBefore: String? = null + private var ids: Ids? = null private var limit: Long? = null private var orgName: String? = null + private var projectId: String? = null private var projectName: String? = null private var startingAfter: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(datasetListParams: DatasetListParams) = apply { - this.datasetName = datasetListParams.datasetName - this.endingBefore = datasetListParams.endingBefore - this.limit = datasetListParams.limit - this.orgName = datasetListParams.orgName - this.projectName = datasetListParams.projectName - this.startingAfter = datasetListParams.startingAfter - additionalQueryParams(datasetListParams.additionalQueryParams) - additionalHeaders(datasetListParams.additionalHeaders) + datasetName = datasetListParams.datasetName + endingBefore = datasetListParams.endingBefore + ids = datasetListParams.ids + limit = datasetListParams.limit + orgName = datasetListParams.orgName + projectId = datasetListParams.projectId + projectName = datasetListParams.projectName + startingAfter = datasetListParams.startingAfter + additionalHeaders = datasetListParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetListParams.additionalQueryParams.toBuilder() } /** Name of the dataset to search for */ - fun datasetName(datasetName: String) = apply { this.datasetName = datasetName } + fun datasetName(datasetName: String?) = apply { this.datasetName = datasetName } + + /** Alias for calling [Builder.datasetName] with `datasetName.orElse(null)`. */ + fun datasetName(datasetName: Optional) = datasetName(datasetName.getOrNull()) /** - * A cursor for pagination. For example, if the initial item in the last page you fetched - * had an id of `foo`, pass `ending_before=foo` to fetch the previous page. Note: you may - * only pass one of `starting_after` and `ending_before` + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` */ - fun endingBefore(endingBefore: String) = apply { this.endingBefore = endingBefore } + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) /** Limit the number of objects to return */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(limit: Long?) = apply { this.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()) /** Filter search results to within a particular organization */ - fun orgName(orgName: String) = apply { this.orgName = orgName } + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) /** Name of the project to search for */ - fun projectName(projectName: String) = apply { this.projectName = projectName } + fun projectName(projectName: String?) = apply { this.projectName = projectName } + + /** Alias for calling [Builder.projectName] with `projectName.orElse(null)`. */ + fun projectName(projectName: Optional) = projectName(projectName.getOrNull()) /** - * A cursor for pagination. For example, if the final item in the last page you fetched had - * an id of `foo`, pass `starting_after=foo` to fetch the next page. Note: you may only pass - * one of `starting_after` and `ending_before` + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` */ - fun startingAfter(startingAfter: String) = apply { this.startingAfter = startingAfter } + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(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 putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + 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 putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [DatasetListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): DatasetListParams = DatasetListParams( datasetName, endingBefore, + ids, limit, orgName, + projectId, projectName, startingAfter, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DatasetListParams && + datasetName == other.datasetName && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + projectId == other.projectId && + projectName == other.projectName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + datasetName, + endingBefore, + ids, + limit, + orgName, + projectId, + projectName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "DatasetListParams{datasetName=$datasetName, endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, projectId=$projectId, projectName=$projectName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetReplaceParams.kt deleted file mode 100644 index fdae08cd..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetReplaceParams.kt +++ /dev/null @@ -1,291 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -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.toUnmodifiable -import com.braintrustdata.api.models.* -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.Objects -import java.util.Optional - -class DatasetReplaceParams -constructor( - private val name: String, - private val description: String?, - private val projectId: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun name(): String = name - - fun description(): Optional = Optional.ofNullable(description) - - fun projectId(): Optional = Optional.ofNullable(projectId) - - @JvmSynthetic - internal fun getBody(): DatasetReplaceBody { - return DatasetReplaceBody( - name, - description, - projectId, - additionalBodyProperties, - ) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - @JsonDeserialize(builder = DatasetReplaceBody.Builder::class) - @NoAutoDetect - class DatasetReplaceBody - internal constructor( - private val name: String?, - private val description: String?, - private val projectId: String?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** Name of the dataset. Within a project, dataset names are unique */ - @JsonProperty("name") fun name(): String? = name - - /** Textual description of the dataset */ - @JsonProperty("description") fun description(): String? = description - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") fun projectId(): String? = projectId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetReplaceBody && - this.name == other.name && - this.description == other.description && - this.projectId == other.projectId && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - description, - projectId, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "DatasetReplaceBody{name=$name, description=$description, projectId=$projectId, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: String? = null - private var description: String? = null - private var projectId: String? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(datasetReplaceBody: DatasetReplaceBody) = apply { - this.name = datasetReplaceBody.name - this.description = datasetReplaceBody.description - this.projectId = datasetReplaceBody.projectId - additionalProperties(datasetReplaceBody.additionalProperties) - } - - /** Name of the dataset. Within a project, dataset names are unique */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } - - /** Textual description of the dataset */ - @JsonProperty("description") - fun description(description: String) = apply { this.description = description } - - /** Unique identifier for the project that the dataset belongs under */ - @JsonProperty("project_id") - fun projectId(projectId: String) = apply { this.projectId = projectId } - - 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(): DatasetReplaceBody = - DatasetReplaceBody( - checkNotNull(name) { "`name` is required but was not set" }, - description, - projectId, - additionalProperties.toUnmodifiable(), - ) - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is DatasetReplaceParams && - this.name == other.name && - this.description == other.description && - this.projectId == other.projectId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int { - return Objects.hash( - name, - description, - projectId, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "DatasetReplaceParams{name=$name, description=$description, projectId=$projectId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - @NoAutoDetect - class Builder { - - private var name: String? = null - private var description: String? = null - private var projectId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(datasetReplaceParams: DatasetReplaceParams) = apply { - this.name = datasetReplaceParams.name - this.description = datasetReplaceParams.description - this.projectId = datasetReplaceParams.projectId - additionalQueryParams(datasetReplaceParams.additionalQueryParams) - additionalHeaders(datasetReplaceParams.additionalHeaders) - additionalBodyProperties(datasetReplaceParams.additionalBodyProperties) - } - - /** Name of the dataset. Within a project, dataset names are unique */ - fun name(name: String) = apply { this.name = name } - - /** Textual description of the dataset */ - fun description(description: String) = apply { this.description = description } - - /** Unique identifier for the project that the dataset belongs under */ - fun projectId(projectId: String) = apply { this.projectId = projectId } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } - - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } - - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } - - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } - - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } - - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } - - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } - - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } - - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun build(): DatasetReplaceParams = - DatasetReplaceParams( - checkNotNull(name) { "`name` is required but was not set" }, - description, - projectId, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } -} 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 old mode 100644 new mode 100755 index 963469a6..2673f27c --- 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,126 +2,194 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Get a dataset object by its id */ class DatasetRetrieveParams -constructor( - private val datasetId: String, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { +private constructor( + private val datasetId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { - fun datasetId(): String = datasetId + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" - } + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): DatasetRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [DatasetRetrieveParams]. */ + @JvmStatic fun builder() = Builder() } - fun _additionalQueryParams(): Map> = additionalQueryParams + /** A builder for [DatasetRetrieveParams]. */ + class Builder internal constructor() { - fun _additionalHeaders(): Map> = additionalHeaders + private var datasetId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + @JvmSynthetic + internal fun from(datasetRetrieveParams: DatasetRetrieveParams) = apply { + datasetId = datasetRetrieveParams.datasetId + additionalHeaders = datasetRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetRetrieveParams.additionalQueryParams.toBuilder() } - return other is DatasetRetrieveParams && - this.datasetId == other.datasetId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } + /** Dataset id */ + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } - override fun hashCode(): Int { - return Objects.hash( - datasetId, - additionalQueryParams, - additionalHeaders, - ) - } + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) - override fun toString() = - "DatasetRetrieveParams{datasetId=$datasetId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - @JvmStatic fun builder() = Builder() - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @NoAutoDetect - class Builder { + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - private var datasetId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(datasetRetrieveParams: DatasetRetrieveParams) = apply { - this.datasetId = datasetRetrieveParams.datasetId - additionalQueryParams(datasetRetrieveParams.additionalQueryParams) - additionalHeaders(datasetRetrieveParams.additionalHeaders) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + 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 removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [DatasetRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): DatasetRetrieveParams = DatasetRetrieveParams( - checkNotNull(datasetId) { "`datasetId` is required but was not set" }, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + datasetId, + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + } + + return other is DatasetRetrieveParams && + datasetId == other.datasetId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(datasetId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "DatasetRetrieveParams{datasetId=$datasetId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 new file mode 100755 index 00000000..daf714c8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/DatasetSummarizeParams.kt @@ -0,0 +1,226 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Summarize dataset */ +class DatasetSummarizeParams +private constructor( + private val datasetId: String?, + private val summarizeData: Boolean?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + + /** Whether to summarize the data. If false (or omitted), only the metadata will be returned. */ + fun summarizeData(): Optional = Optional.ofNullable(summarizeData) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): DatasetSummarizeParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [DatasetSummarizeParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DatasetSummarizeParams]. */ + class Builder internal constructor() { + + private var datasetId: String? = null + private var summarizeData: Boolean? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(datasetSummarizeParams: DatasetSummarizeParams) = apply { + datasetId = datasetSummarizeParams.datasetId + summarizeData = datasetSummarizeParams.summarizeData + additionalHeaders = datasetSummarizeParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetSummarizeParams.additionalQueryParams.toBuilder() + } + + /** Dataset id */ + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } + + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) + + /** + * Whether to summarize the data. If false (or omitted), only the metadata will be returned. + */ + fun summarizeData(summarizeData: Boolean?) = apply { this.summarizeData = summarizeData } + + /** + * Alias for [Builder.summarizeData]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun summarizeData(summarizeData: Boolean) = summarizeData(summarizeData as Boolean?) + + /** Alias for calling [Builder.summarizeData] with `summarizeData.orElse(null)`. */ + fun summarizeData(summarizeData: Optional) = + summarizeData(summarizeData.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [DatasetSummarizeParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): DatasetSummarizeParams = + DatasetSummarizeParams( + datasetId, + summarizeData, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is DatasetSummarizeParams && + datasetId == other.datasetId && + summarizeData == other.summarizeData && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(datasetId, summarizeData, additionalHeaders, additionalQueryParams) + + override fun toString() = + "DatasetSummarizeParams{datasetId=$datasetId, summarizeData=$summarizeData, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 old mode 100644 new mode 100755 index d8e97538..0e747c50 --- 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 @@ -3,282 +3,668 @@ 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.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +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 com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Partially update a dataset object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ class DatasetUpdateParams -constructor( - private val datasetId: String, - private val name: String, - private val description: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun datasetId(): String = datasetId - - fun name(): String = name - - fun description(): Optional = Optional.ofNullable(description) - - @JvmSynthetic - internal fun getBody(): DatasetUpdateBody { - return DatasetUpdateBody( - name, - description, - additionalBodyProperties, - ) +private constructor( + private val datasetId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + + /** + * 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 = body.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 = body.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 = body.name() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): DatasetUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [DatasetUpdateParams]. */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [DatasetUpdateParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> datasetId - else -> "" + @JvmSynthetic + internal fun from(datasetUpdateParams: DatasetUpdateParams) = apply { + datasetId = datasetUpdateParams.datasetId + body = datasetUpdateParams.body.toBuilder() + additionalHeaders = datasetUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = datasetUpdateParams.additionalQueryParams.toBuilder() } - } - @JsonDeserialize(builder = DatasetUpdateBody.Builder::class) - @NoAutoDetect - class DatasetUpdateBody - internal constructor( - private val name: String?, - private val description: String?, - private val additionalProperties: Map, - ) { + /** Dataset id */ + fun datasetId(datasetId: String?) = apply { this.datasetId = datasetId } + + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [description] + * - [metadata] + * - [name] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } - private var hashCode: Int = 0 + /** Textual description of the dataset */ + 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 dataset */ + 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 dataset. Within a project, dataset names are unique */ - @JsonProperty("name") fun name(): String? = name + fun name(name: String?) = apply { body.name(name) } - /** Textual description of the dataset */ - @JsonProperty("description") fun description(): String? = description + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** + * 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) } - fun toBuilder() = Builder().from(this) + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - return other is DatasetUpdateBody && - this.name == other.name && - this.description == other.description && - this.additionalProperties == other.additionalProperties + 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) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - description, - additionalProperties, - ) + 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) } - return hashCode + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - override fun toString() = - "DatasetUpdateBody{name=$name, description=$description, additionalProperties=$additionalProperties}" + 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 [DatasetUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): DatasetUpdateParams = + DatasetUpdateParams( + datasetId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Body]. */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Body]. */ + class Builder internal constructor() { - private var name: String? = null - private var description: String? = null + 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(datasetUpdateBody: DatasetUpdateBody) = apply { - this.name = datasetUpdateBody.name - this.description = datasetUpdateBody.description - additionalProperties(datasetUpdateBody.additionalProperties) + 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 */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } + fun name(name: String?) = name(JsonField.ofNullable(name)) - /** Textual description of the dataset */ - @JsonProperty("description") - fun description(description: String) = apply { this.description = description } + /** 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() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): DatasetUpdateBody = - DatasetUpdateBody( - checkNotNull(name) { "`name` is required but was not set" }, - description, - additionalProperties.toUnmodifiable(), - ) - } - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun _additionalQueryParams(): Map> = additionalQueryParams + /** + * 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()) + } - fun _additionalHeaders(): Map> = additionalHeaders + private var validated: Boolean = false - fun _additionalBodyProperties(): Map = additionalBodyProperties + fun validate(): Body = apply { + if (validated) { + return@apply + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + description() + metadata().ifPresent { it.validate() } + name() + validated = true } - return other is DatasetUpdateParams && - this.datasetId == other.datasetId && - this.name == other.name && - this.description == other.description && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - override fun hashCode(): Int { - return Objects.hash( - datasetId, - name, - description, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + /** + * Returns a 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 toString() = - "DatasetUpdateParams{datasetId=$datasetId, name=$name, description=$description, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun toBuilder() = Builder().from(this) + return other is Body && + description == other.description && + metadata == other.metadata && + name == other.name && + additionalProperties == other.additionalProperties + } - companion object { + private val hashCode: Int by lazy { + Objects.hash(description, metadata, name, additionalProperties) + } - @JvmStatic fun builder() = Builder() + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{description=$description, metadata=$metadata, name=$name, additionalProperties=$additionalProperties}" } - @NoAutoDetect - class Builder { + /** User-controlled metadata about the dataset */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { - private var datasetId: String? = null - private var name: String? = null - private var description: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties - @JvmSynthetic - internal fun from(datasetUpdateParams: DatasetUpdateParams) = apply { - this.datasetId = datasetUpdateParams.datasetId - this.name = datasetUpdateParams.name - this.description = datasetUpdateParams.description - additionalQueryParams(datasetUpdateParams.additionalQueryParams) - additionalHeaders(datasetUpdateParams.additionalHeaders) - additionalBodyProperties(datasetUpdateParams.additionalBodyProperties) + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() } - /** Dataset id */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + /** A builder for [Metadata]. */ + class Builder internal constructor() { - /** Name of the dataset. Within a project, dataset names are unique */ - fun name(name: String) = apply { this.name = name } + private var additionalProperties: MutableMap = mutableMapOf() - /** Textual description of the dataset */ - fun description(description: String) = apply { this.description = description } + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } + private var validated: Boolean = false - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun validate(): Metadata = apply { + if (validated) { + return@apply + } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + validated = true } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + /** + * Returns 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() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - fun build(): DatasetUpdateParams = - DatasetUpdateParams( - checkNotNull(datasetId) { "`datasetId` is required but was not set" }, - checkNotNull(name) { "`name` is required but was not set" }, - description, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DatasetUpdateParams && + datasetId == other.datasetId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = + Objects.hash(datasetId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "DatasetUpdateParams{datasetId=$datasetId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 new file mode 100644 index 00000000..354ddd66 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVar.kt @@ -0,0 +1,508 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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 + +class EnvVar +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * 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 id of the object the environment variable is scoped for + * + * @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 type of the object the environment variable is scoped for + * + * @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 = objectType.getRequired("object_type") + + /** + * Date of environment variable creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Date the environment variable was last used + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun used(): Optional = used.getOptional("used") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [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 + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [used]. + * + * Unlike [used], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("used") @ExcludeMissing fun _used(): JsonField = used + + @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 [EnvVar]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVar]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var used: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(envVar: EnvVar) = apply { + id = envVar.id + name = envVar.name + objectId = envVar.objectId + objectType = envVar.objectType + created = envVar.created + used = envVar.used + additionalProperties = envVar.additionalProperties.toMutableMap() + } + + /** Unique identifier for the environment variable */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** 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 id of the object the environment variable is scoped for */ + 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 type of the object the environment variable is scoped for */ + fun objectType(objectType: ObjectType) = objectType(JsonField.of(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 { this.objectType = objectType } + + /** Date of environment variable creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Date the environment variable was last used */ + fun used(used: OffsetDateTime?) = used(JsonField.ofNullable(used)) + + /** Alias for calling [Builder.used] with `used.orElse(null)`. */ + fun used(used: Optional) = used(used.getOrNull()) + + /** + * Sets [Builder.used] to an arbitrary JSON value. + * + * You should usually call [Builder.used] with a well-typed [OffsetDateTime] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun used(used: JsonField) = apply { this.used = used } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [EnvVar]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): EnvVar = + EnvVar( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + created, + used, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ORGANIZATION = of("organization") + + @JvmField val PROJECT = of("project") + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = ObjectType(JsonField.of(value)) + } + + /** An enum containing [ObjectType]'s known values. */ + enum class Known { + ORGANIZATION, + PROJECT, + FUNCTION, + } + + /** + * An enum containing [ObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ORGANIZATION, + PROJECT, + FUNCTION, + /** + * An enum member indicating that [ObjectType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ORGANIZATION -> Value.ORGANIZATION + PROJECT -> Value.PROJECT + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + ORGANIZATION -> Known.ORGANIZATION + PROJECT -> Known.PROJECT + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown ObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EnvVar && + id == other.id && + name == other.name && + objectId == other.objectId && + objectType == other.objectType && + created == other.created && + used == other.used && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, name, objectId, objectType, created, used, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "EnvVar{id=$id, name=$name, objectId=$objectId, objectType=$objectType, created=$created, used=$used, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..df2d5196 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarCreateParams.kt @@ -0,0 +1,773 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.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.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 + +/** + * Create a new env_var. If there is an existing env_var with the same name as the one specified in + * the request, will return the existing env_var unmodified + */ +class EnvVarCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.name() + + /** + * The id of the object the environment variable is scoped for + * + * @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 = body.objectId() + + /** + * The type of the object the environment variable is scoped for + * + * @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 = body.objectType() + + /** + * 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 = body.value() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _value(): JsonField = body._value() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 id of the object the environment variable is scoped for + * + * @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 type of the object the environment variable is scoped for + * + * @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 = objectType.getRequired("object_type") + + /** + * 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 [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 + + /** + * 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() + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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 value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + objectId = body.objectId + objectType = body.objectType + 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 id of the object the environment variable is scoped for */ + 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 type of the object the environment variable is scoped for */ + fun objectType(objectType: ObjectType) = objectType(JsonField.of(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 { + this.objectType = objectType + } + + /** 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() + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + value, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + objectId() + objectType().validate() + 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + objectId == other.objectId && + objectType == other.objectType && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, objectId, objectType, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + 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 */ + class ObjectType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ORGANIZATION = of("organization") + + @JvmField val PROJECT = of("project") + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = ObjectType(JsonField.of(value)) + } + + /** An enum containing [ObjectType]'s known values. */ + enum class Known { + ORGANIZATION, + PROJECT, + FUNCTION, + } + + /** + * An enum containing [ObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ORGANIZATION, + PROJECT, + FUNCTION, + /** + * An enum member indicating that [ObjectType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ORGANIZATION -> Value.ORGANIZATION + PROJECT -> Value.PROJECT + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + ORGANIZATION -> Known.ORGANIZATION + PROJECT -> Known.PROJECT + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown ObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EnvVarCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "EnvVarCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..12fb3736 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete an env_var object by its id */ +class EnvVarDeleteParams +private constructor( + private val envVarId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** EnvVar id */ + fun envVarId(): Optional = Optional.ofNullable(envVarId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): EnvVarDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EnvVarDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVarDeleteParams]. */ + class Builder internal constructor() { + + private var envVarId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(envVarDeleteParams: EnvVarDeleteParams) = apply { + envVarId = envVarDeleteParams.envVarId + additionalHeaders = envVarDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = envVarDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = envVarDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** EnvVar id */ + fun envVarId(envVarId: String?) = apply { this.envVarId = envVarId } + + /** Alias for calling [Builder.envVarId] with `envVarId.orElse(null)`. */ + fun envVarId(envVarId: Optional) = envVarId(envVarId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [EnvVarDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): EnvVarDeleteParams = + EnvVarDeleteParams( + envVarId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is EnvVarDeleteParams && + envVarId == other.envVarId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(envVarId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "EnvVarDeleteParams{envVarId=$envVarId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100644 index 00000000..8bdc76be --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListParams.kt @@ -0,0 +1,360 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all env_vars. The env_vars are sorted by creation date, with the most recently-created + * env_vars coming first + */ +class EnvVarListParams +private constructor( + private val envVarName: String?, + private val ids: Ids?, + private val limit: Long?, + private val objectId: String?, + private val objectType: EnvVarObjectType?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Name of the env_var to search for */ + fun envVarName(): Optional = Optional.ofNullable(envVarName) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** The id of the object the environment variable is scoped for */ + fun objectId(): Optional = Optional.ofNullable(objectId) + + /** The type of the object the environment variable is scoped for */ + fun objectType(): Optional = Optional.ofNullable(objectType) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): EnvVarListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EnvVarListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVarListParams]. */ + class Builder internal constructor() { + + private var envVarName: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var objectId: String? = null + private var objectType: EnvVarObjectType? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(envVarListParams: EnvVarListParams) = apply { + envVarName = envVarListParams.envVarName + ids = envVarListParams.ids + limit = envVarListParams.limit + objectId = envVarListParams.objectId + objectType = envVarListParams.objectType + additionalHeaders = envVarListParams.additionalHeaders.toBuilder() + additionalQueryParams = envVarListParams.additionalQueryParams.toBuilder() + } + + /** Name of the env_var to search for */ + fun envVarName(envVarName: String?) = apply { this.envVarName = envVarName } + + /** Alias for calling [Builder.envVarName] with `envVarName.orElse(null)`. */ + fun envVarName(envVarName: Optional) = envVarName(envVarName.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** The id of the object the environment variable is scoped for */ + fun objectId(objectId: String?) = apply { this.objectId = objectId } + + /** Alias for calling [Builder.objectId] with `objectId.orElse(null)`. */ + fun objectId(objectId: Optional) = objectId(objectId.getOrNull()) + + /** The type of the object the environment variable is scoped for */ + fun objectType(objectType: EnvVarObjectType?) = apply { this.objectType = objectType } + + /** Alias for calling [Builder.objectType] with `objectType.orElse(null)`. */ + fun objectType(objectType: Optional) = objectType(objectType.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [EnvVarListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): EnvVarListParams = + EnvVarListParams( + envVarName, + ids, + limit, + objectId, + objectType, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EnvVarListParams && + envVarName == other.envVarName && + ids == other.ids && + limit == other.limit && + objectId == other.objectId && + objectType == other.objectType && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + envVarName, + ids, + limit, + objectId, + objectType, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "EnvVarListParams{envVarName=$envVarName, ids=$ids, limit=$limit, objectId=$objectId, objectType=$objectType, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..395976a1 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarListResponse.kt @@ -0,0 +1,193 @@ +// 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 EnvVarListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 env_var 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 [EnvVarListResponse]. + * + * The following fields are required: + * ```java + * .objects() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVarListResponse]. */ + class Builder internal constructor() { + + private var objects: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(envVarListResponse: EnvVarListResponse) = apply { + objects = envVarListResponse.objects.map { it.toMutableList() } + additionalProperties = envVarListResponse.additionalProperties.toMutableMap() + } + + /** A list of env_var 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 [EnvVar] to [objects]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addObject(object_: EnvVar) = 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 [EnvVarListResponse]. + * + * 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(): EnvVarListResponse = + EnvVarListResponse( + checkRequired("objects", objects).map { it.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 + } + + return other is EnvVarListResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "EnvVarListResponse{objects=$objects, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..11f78ac3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarObjectType.kt @@ -0,0 +1,141 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.errors.BraintrustInvalidDataException +import com.fasterxml.jackson.annotation.JsonCreator + +/** The type of the object the environment variable is scoped for */ +class EnvVarObjectType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ORGANIZATION = of("organization") + + @JvmField val PROJECT = of("project") + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = EnvVarObjectType(JsonField.of(value)) + } + + /** An enum containing [EnvVarObjectType]'s known values. */ + enum class Known { + ORGANIZATION, + PROJECT, + FUNCTION, + } + + /** + * An enum containing [EnvVarObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [EnvVarObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ORGANIZATION, + PROJECT, + FUNCTION, + /** + * An enum member indicating that [EnvVarObjectType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + ORGANIZATION -> Value.ORGANIZATION + PROJECT -> Value.PROJECT + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + ORGANIZATION -> Known.ORGANIZATION + PROJECT -> Known.PROJECT + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown EnvVarObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + 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 + } + + return other is EnvVarObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} 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 new file mode 100644 index 00000000..96dd3de5 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarReplaceParams.kt @@ -0,0 +1,773 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.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.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 + +/** + * Create or replace env_var. If there is an existing env_var with the same name as the one + * specified in the request, will replace the existing env_var with the provided fields + */ +class EnvVarReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.name() + + /** + * The id of the object the environment variable is scoped for + * + * @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 = body.objectId() + + /** + * The type of the object the environment variable is scoped for + * + * @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 = body.objectType() + + /** + * 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 = body.value() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _value(): JsonField = body._value() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 id of the object the environment variable is scoped for + * + * @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 type of the object the environment variable is scoped for + * + * @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 = objectType.getRequired("object_type") + + /** + * 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 [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 + + /** + * 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() + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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 value: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + objectId = body.objectId + objectType = body.objectType + 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 id of the object the environment variable is scoped for */ + 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 type of the object the environment variable is scoped for */ + fun objectType(objectType: ObjectType) = objectType(JsonField.of(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 { + this.objectType = objectType + } + + /** 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() + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + value, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + objectId() + objectType().validate() + 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 (objectId.asKnown().isPresent) 1 else 0) + + (objectType.asKnown().getOrNull()?.validity() ?: 0) + + (if (value.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + objectId == other.objectId && + objectType == other.objectType && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, objectId, objectType, value, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + 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 */ + class ObjectType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ORGANIZATION = of("organization") + + @JvmField val PROJECT = of("project") + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = ObjectType(JsonField.of(value)) + } + + /** An enum containing [ObjectType]'s known values. */ + enum class Known { + ORGANIZATION, + PROJECT, + FUNCTION, + } + + /** + * An enum containing [ObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ORGANIZATION, + PROJECT, + FUNCTION, + /** + * An enum member indicating that [ObjectType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ORGANIZATION -> Value.ORGANIZATION + PROJECT -> Value.PROJECT + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + ORGANIZATION -> Known.ORGANIZATION + PROJECT -> Known.PROJECT + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown ObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EnvVarReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "EnvVarReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..2f008ae3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParams.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get an env_var object by its id */ +class EnvVarRetrieveParams +private constructor( + private val envVarId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** EnvVar id */ + fun envVarId(): Optional = Optional.ofNullable(envVarId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): EnvVarRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [EnvVarRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVarRetrieveParams]. */ + class Builder internal constructor() { + + private var envVarId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(envVarRetrieveParams: EnvVarRetrieveParams) = apply { + envVarId = envVarRetrieveParams.envVarId + additionalHeaders = envVarRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = envVarRetrieveParams.additionalQueryParams.toBuilder() + } + + /** EnvVar id */ + fun envVarId(envVarId: String?) = apply { this.envVarId = envVarId } + + /** Alias for calling [Builder.envVarId] with `envVarId.orElse(null)`. */ + fun envVarId(envVarId: Optional) = envVarId(envVarId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [EnvVarRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): EnvVarRetrieveParams = + EnvVarRetrieveParams(envVarId, additionalHeaders.build(), additionalQueryParams.build()) + } + + 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 + } + + return other is EnvVarRetrieveParams && + envVarId == other.envVarId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(envVarId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "EnvVarRetrieveParams{envVarId=$envVarId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..39a55172 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EnvVarUpdateParams.kt @@ -0,0 +1,510 @@ +// 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.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.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 + +/** + * Partially update an env_var object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ +class EnvVarUpdateParams +private constructor( + private val envVarId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** EnvVar id */ + fun envVarId(): Optional = Optional.ofNullable(envVarId) + + /** + * 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 = body.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 = body.value() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [value]. + * + * Unlike [value], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _value(): JsonField = body._value() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [EnvVarUpdateParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [EnvVarUpdateParams]. */ + class Builder internal constructor() { + + private var envVarId: 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(envVarUpdateParams: EnvVarUpdateParams) = apply { + envVarId = envVarUpdateParams.envVarId + body = envVarUpdateParams.body.toBuilder() + additionalHeaders = envVarUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = envVarUpdateParams.additionalQueryParams.toBuilder() + } + + /** EnvVar id */ + fun envVarId(envVarId: String?) = apply { this.envVarId = envVarId } + + /** Alias for calling [Builder.envVarId] with `envVarId.orElse(null)`. */ + fun envVarId(envVarId: Optional) = envVarId(envVarId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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) } + + /** + * 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 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 [EnvVarUpdateParams]. + * + * 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(): EnvVarUpdateParams = + EnvVarUpdateParams( + envVarId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 other is Body && + name == other.name && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, value, additionalProperties) } + + 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 + } + + return other is EnvVarUpdateParams && + envVarId == other.envVarId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(envVarId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "EnvVarUpdateParams{envVarId=$envVarId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..3ad43206 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/EvalCreateParams.kt @@ -0,0 +1,8570 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Launch an evaluation. This is the API-equivalent of the `Eval` function that is built into the + * Braintrust SDK. In the Eval API, you provide pointers to a dataset, task function, and scoring + * functions. The API will then run the evaluation, create an experiment, and return the results + * along with a link to the experiment. To learn more about evals, see the + * [Evals guide](https://www.braintrust.dev/docs/guides/evals). + */ +class EvalCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.data() + + /** + * 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 = body.projectId() + + /** + * 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 = body.scores() + + /** + * 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 = body.task() + + /** + * 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 = body.baseExperimentId() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun experimentName(): Optional = body.experimentName() + + /** + * 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 = body.gitMetadataSettings() + + /** + * 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 = body.isPublic() + + /** + * 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 = body.maxConcurrency() + + /** + * 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 = body.metadata() + + /** + * 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 = body.parent() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stream(): Optional = body.stream() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun trialCount(): Optional = body.trialCount() + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _data(): JsonField = body._data() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [scores]. + * + * Unlike [scores], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _scores(): JsonField> = body._scores() + + /** + * Returns the raw JSON value of [task]. + * + * Unlike [task], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _task(): JsonField = body._task() + + /** + * Returns the raw JSON value of [baseExperimentId]. + * + * Unlike [baseExperimentId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _baseExperimentId(): JsonField = body._baseExperimentId() + + /** + * Returns the raw JSON value of [baseExperimentName]. + * + * Unlike [baseExperimentName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _baseExperimentName(): JsonField = body._baseExperimentName() + + /** + * Returns the raw JSON value of [experimentName]. + * + * Unlike [experimentName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _experimentName(): JsonField = body._experimentName() + + /** + * Returns the raw JSON value of [gitMetadataSettings]. + * + * Unlike [gitMetadataSettings], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _gitMetadataSettings(): JsonField = body._gitMetadataSettings() + + /** + * Returns the raw JSON value of [isPublic]. + * + * Unlike [isPublic], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _isPublic(): JsonField = body._isPublic() + + /** + * Returns the raw JSON value of [maxConcurrency]. + * + * Unlike [maxConcurrency], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxConcurrency(): JsonField = body._maxConcurrency() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _parent(): JsonField = body._parent() + + /** + * Returns the raw JSON value of [repoInfo]. + * + * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _repoInfo(): JsonField = body._repoInfo() + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _stream(): JsonField = body._stream() + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _timeout(): JsonField = body._timeout() + + /** + * Returns the raw JSON value of [trialCount]. + * + * Unlike [trialCount], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _trialCount(): JsonField = body._trialCount() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [EvalCreateParams]. + * + * The following fields are required: + * ```java + * .data() + * .projectId() + * .scores() + * .task() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** + * 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: + * - [data] + * - [projectId] + * - [scores] + * - [task] + * - [baseExperimentId] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** The dataset to use */ + fun data(data: Data) = apply { body.data(data) } + + /** + * 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 { 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) } + + /** + * 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) } + + /** The functions to score the eval on */ + fun scores(scores: List) = apply { body.scores(scores) } + + /** + * 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 { body.scores(scores) } + + /** + * Adds a single [Score] to [scores]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + 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) } + + /** + * 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) } + + /** 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) } + + /** + * 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) + } + + /** Alias for calling [Builder.baseExperimentId] with `baseExperimentId.orElse(null)`. */ + fun baseExperimentId(baseExperimentId: Optional) = + baseExperimentId(baseExperimentId.getOrNull()) + + /** + * 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) + } + + /** + * 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 [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 { + body.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) = apply { body.experimentName(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 { + body.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?) = apply { + body.gitMetadataSettings(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 { + body.gitMetadataSettings(gitMetadataSettings) + } + + /** Whether the experiment should be public. Defaults to false. */ + fun isPublic(isPublic: Boolean?) = apply { body.isPublic(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 { body.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?) = apply { body.maxConcurrency(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 { + body.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) = apply { body.metadata(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 { body.metadata(metadata) } + + /** Options for tracing the evaluation */ + 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) } + + /** 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) } + + /** + * 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. + * + * 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 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]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun timeout(timeout: Double) = timeout(timeout as Double?) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun timeout(timeout: JsonField) = apply { body.timeout(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]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun trialCount(trialCount: Double) = trialCount(trialCount as Double?) + + /** Alias for calling [Builder.trialCount] with `trialCount.orElse(null)`. */ + fun trialCount(trialCount: Optional) = trialCount(trialCount.getOrNull()) + + /** + * 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) } + + 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 [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()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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, + ) { + + @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(), + ) + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [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 [scores]. + * + * Unlike [scores], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("scores") @ExcludeMissing fun _scores(): JsonField> = scores + + /** + * 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 + + /** + * 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 + + /** + * 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 + + /** + * 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 the raw JSON value of [gitMetadataSettings]. + * + * Unlike [gitMetadataSettings], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("git_metadata_settings") + @ExcludeMissing + fun _gitMetadataSettings(): JsonField = gitMetadataSettings + + /** + * 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 + + /** + * 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 + + /** + * 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 [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + + /** + * 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 + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream + + /** + * Returns the raw JSON value of [timeout]. + * + * Unlike [timeout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("timeout") @ExcludeMissing fun _timeout(): JsonField = timeout + + /** + * Returns the raw JSON value of [trialCount]. + * + * Unlike [trialCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("trial_count") + @ExcludeMissing + fun _trialCount(): JsonField = trialCount + + @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 + * .data() + * .projectId() + * .scores() + * .task() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + 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() + + @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() + } + + /** The dataset to use */ + fun data(data: Data) = data(JsonField.of(data)) + + /** + * 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 [data] with `Data.ofDatasetId(datasetId)`. */ + fun data(datasetId: Data.DatasetId) = data(Data.ofDatasetId(datasetId)) + + /** Alias for calling [data] with `Data.ofProjectDatasetName(projectDatasetName)`. */ + fun data(projectDatasetName: Data.ProjectDatasetName) = + data(Data.ofProjectDatasetName(projectDatasetName)) + + /** Alias for calling [data] with `Data.ofDatasetRows(datasetRows)`. */ + fun data(datasetRows: Data.DatasetRows) = data(Data.ofDatasetRows(datasetRows)) + + /** Unique identifier for the project to run the eval in */ + 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 functions to score the eval on */ + fun scores(scores: List) = scores(JsonField.of(scores)) + + /** + * 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() } + } + + /** + * 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) + } + } + + /** Alias for calling [addScore] with `Score.ofFunctionId(functionId)`. */ + fun addScore(functionId: Score.FunctionId) = addScore(Score.ofFunctionId(functionId)) + + /** Alias for calling [addScore] with `Score.ofProjectSlug(projectSlug)`. */ + fun addScore(projectSlug: Score.ProjectSlug) = + addScore(Score.ofProjectSlug(projectSlug)) + + /** Alias for calling [addScore] with `Score.ofGlobalFunction(globalFunction)`. */ + fun addScore(globalFunction: Score.GlobalFunction) = + addScore(Score.ofGlobalFunction(globalFunction)) + + /** 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.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 } + + /** Alias for calling [task] with `Task.ofFunctionId(functionId)`. */ + fun task(functionId: Task.FunctionId) = task(Task.ofFunctionId(functionId)) + + /** Alias for calling [task] with `Task.ofProjectSlug(projectSlug)`. */ + fun task(projectSlug: Task.ProjectSlug) = task(Task.ofProjectSlug(projectSlug)) + + /** Alias for calling [task] with `Task.ofGlobalFunction(globalFunction)`. */ + fun task(globalFunction: Task.GlobalFunction) = + task(Task.ofGlobalFunction(globalFunction)) + + /** Alias for calling [task] with `Task.ofPromptSessionId(promptSessionId)`. */ + fun task(promptSessionId: Task.PromptSessionId) = + task(Task.ofPromptSessionId(promptSessionId)) + + /** Alias for calling [task] with `Task.ofInlineCode(inlineCode)`. */ + fun task(inlineCode: Task.InlineCode) = task(Task.ofInlineCode(inlineCode)) + + /** Alias for calling [task] with `Task.ofInlinePrompt(inlinePrompt)`. */ + fun task(inlinePrompt: Task.InlinePrompt) = task(Task.ofInlinePrompt(inlinePrompt)) + + /** + * 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)) + + /** + * Alias for calling [Builder.baseExperimentId] with `baseExperimentId.orElse(null)`. + */ + fun baseExperimentId(baseExperimentId: Optional) = + baseExperimentId(baseExperimentId.getOrNull()) + + /** + * 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)) + + /** + * Alias for [Builder.timeout]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun timeout(timeout: Double) = timeout(timeout as Double?) + + /** Alias for calling [Builder.timeout] with `timeout.orElse(null)`. */ + fun timeout(timeout: Optional) = timeout(timeout.getOrNull()) + + /** + * Sets [Builder.timeout] to an arbitrary JSON value. + * + * You should usually call [Builder.timeout] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun timeout(timeout: JsonField) = apply { this.timeout = timeout } + + /** + * 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)) + + /** + * Alias for [Builder.trialCount]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun trialCount(trialCount: Double) = trialCount(trialCount as Double?) + + /** Alias for calling [Builder.trialCount] with `trialCount.orElse(null)`. */ + fun trialCount(trialCount: Optional) = trialCount(trialCount.getOrNull()) + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + 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 isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return 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 + } + + 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, + ) + } + + override fun hashCode(): Int = hashCode + + 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 */ + @JsonDeserialize(using = Data.Deserializer::class) + @JsonSerialize(using = Data.Serializer::class) + class Data + private constructor( + private val datasetId: DatasetId? = null, + private val projectDatasetName: ProjectDatasetName? = null, + private val datasetRows: DatasetRows? = null, + private val _json: JsonValue? = null, + ) { + + /** Dataset id */ + fun datasetId(): Optional = Optional.ofNullable(datasetId) + + /** Project and dataset name */ + fun projectDatasetName(): Optional = + Optional.ofNullable(projectDatasetName) + + /** Dataset rows */ + fun datasetRows(): Optional = Optional.ofNullable(datasetRows) + + fun isDatasetId(): Boolean = datasetId != null + + fun isProjectDatasetName(): Boolean = projectDatasetName != null + + fun isDatasetRows(): Boolean = datasetRows != null + + /** Dataset id */ + fun asDatasetId(): DatasetId = datasetId.getOrThrow("datasetId") + + /** Project and dataset name */ + fun asProjectDatasetName(): ProjectDatasetName = + projectDatasetName.getOrThrow("projectDatasetName") + + /** Dataset rows */ + fun asDatasetRows(): DatasetRows = datasetRows.getOrThrow("datasetRows") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitDatasetId(datasetId: DatasetId) { + datasetId.validate() + } + + override fun visitProjectDatasetName(projectDatasetName: ProjectDatasetName) { + projectDatasetName.validate() + } + + override fun visitDatasetRows(datasetRows: DatasetRows) { + datasetRows.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 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 + } + + return other is Data && + datasetId == other.datasetId && + projectDatasetName == other.projectDatasetName && + datasetRows == other.datasetRows + } + + override fun hashCode(): Int = Objects.hash(datasetId, projectDatasetName, datasetRows) + + override fun toString(): String = + when { + datasetId != null -> "Data{datasetId=$datasetId}" + projectDatasetName != null -> "Data{projectDatasetName=$projectDatasetName}" + datasetRows != null -> "Data{datasetRows=$datasetRows}" + _json != null -> "Data{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Data") + } + + companion object { + + /** Dataset id */ + @JvmStatic fun ofDatasetId(datasetId: DatasetId) = Data(datasetId = datasetId) + + /** Project and dataset name */ + @JvmStatic + fun ofProjectDatasetName(projectDatasetName: ProjectDatasetName) = + Data(projectDatasetName = projectDatasetName) + + /** Dataset rows */ + @JvmStatic fun ofDatasetRows(datasetRows: DatasetRows) = Data(datasetRows = datasetRows) + } + + /** An interface that defines how to map each variant of [Data] to a value of type [T]. */ + interface Visitor { + + /** Dataset id */ + fun visitDatasetId(datasetId: DatasetId): T + + /** Project and dataset name */ + fun visitProjectDatasetName(projectDatasetName: ProjectDatasetName): T + + /** Dataset rows */ + fun visitDatasetRows(datasetRows: DatasetRows): T + + /** + * Maps an unknown variant of [Data] to a value of type [T]. + * + * An instance of [Data] 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 Data: $json") + } + } + + internal class Deserializer : BaseDeserializer(Data::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Data { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Data::class) { + + override fun serialize( + value: Data, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.datasetId != null -> generator.writeObject(value.datasetId) + value.projectDatasetName != null -> + generator.writeObject(value.projectDatasetName) + value.datasetRows != null -> generator.writeObject(value.datasetRows) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Data") + } + } + } + + /** Dataset id */ + class DatasetId + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun datasetId(): String = datasetId.getRequired("dataset_id") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun _internalBtql(): Optional<_InternalBtql> = + _internalBtql.getOptional("_internal_btql") + + /** + * 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 [_internalBtql]. + * + * Unlike [_internalBtql], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("_internal_btql") + @ExcludeMissing + fun __internalBtql(): JsonField<_InternalBtql> = _internalBtql + + @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 [DatasetId]. + * + * The following fields are required: + * ```java + * .datasetId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DatasetId]. */ + class Builder internal constructor() { + + private var datasetId: JsonField? = null + private var _internalBtql: JsonField<_InternalBtql> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(datasetId: DatasetId) = apply { + this.datasetId = datasetId.datasetId + _internalBtql = datasetId._internalBtql + additionalProperties = datasetId.additionalProperties.toMutableMap() + } + + fun datasetId(datasetId: String) = datasetId(JsonField.of(datasetId)) + + /** + * 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 } + + fun _internalBtql(_internalBtql: _InternalBtql?) = + _internalBtql(JsonField.ofNullable(_internalBtql)) + + /** Alias for calling [Builder._internalBtql] with `_internalBtql.orElse(null)`. */ + fun _internalBtql(_internalBtql: Optional<_InternalBtql>) = + _internalBtql(_internalBtql.getOrNull()) + + /** + * Sets [Builder._internalBtql] to an arbitrary JSON value. + * + * You should usually call [Builder._internalBtql] with a well-typed [_InternalBtql] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun _internalBtql(_internalBtql: JsonField<_InternalBtql>) = apply { + this._internalBtql = _internalBtql + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DatasetId]. + * + * 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. + */ + fun build(): DatasetId = + DatasetId( + checkRequired("datasetId", datasetId), + _internalBtql, + additionalProperties.toMutableMap(), + ) + } + + 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( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [_InternalBtql]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [_InternalBtql]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(_internalBtql: _InternalBtql) = apply { + additionalProperties = _internalBtql.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 [_InternalBtql]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is _InternalBtql && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "_InternalBtql{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is DatasetId && + datasetId == other.datasetId && + _internalBtql == other._internalBtql && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(datasetId, _internalBtql, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "DatasetId{datasetId=$datasetId, _internalBtql=$_internalBtql, additionalProperties=$additionalProperties}" + } + + /** Project and dataset name */ + class ProjectDatasetName + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun datasetName(): String = datasetName.getRequired("dataset_name") + + /** + * @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 projectName(): String = projectName.getRequired("project_name") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun _internalBtql(): Optional<_InternalBtql> = + _internalBtql.getOptional("_internal_btql") + + /** + * Returns the raw JSON value of [datasetName]. + * + * Unlike [datasetName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("dataset_name") + @ExcludeMissing + fun _datasetName(): JsonField = datasetName + + /** + * Returns the raw JSON value of [projectName]. + * + * Unlike [projectName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("project_name") + @ExcludeMissing + fun _projectName(): JsonField = projectName + + /** + * Returns the raw JSON value of [_internalBtql]. + * + * Unlike [_internalBtql], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("_internal_btql") + @ExcludeMissing + fun __internalBtql(): JsonField<_InternalBtql> = _internalBtql + + @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 [ProjectDatasetName]. + * + * The following fields are required: + * ```java + * .datasetName() + * .projectName() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectDatasetName]. */ + class Builder internal constructor() { + + private var datasetName: JsonField? = null + private var projectName: JsonField? = null + private var _internalBtql: JsonField<_InternalBtql> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectDatasetName: ProjectDatasetName) = apply { + datasetName = projectDatasetName.datasetName + projectName = projectDatasetName.projectName + _internalBtql = projectDatasetName._internalBtql + additionalProperties = projectDatasetName.additionalProperties.toMutableMap() + } + + fun datasetName(datasetName: String) = datasetName(JsonField.of(datasetName)) + + /** + * Sets [Builder.datasetName] to an arbitrary JSON value. + * + * You should usually call [Builder.datasetName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun datasetName(datasetName: JsonField) = apply { + this.datasetName = datasetName + } + + fun projectName(projectName: String) = projectName(JsonField.of(projectName)) + + /** + * Sets [Builder.projectName] to an arbitrary JSON value. + * + * You should usually call [Builder.projectName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun projectName(projectName: JsonField) = apply { + this.projectName = projectName + } + + fun _internalBtql(_internalBtql: _InternalBtql?) = + _internalBtql(JsonField.ofNullable(_internalBtql)) + + /** Alias for calling [Builder._internalBtql] with `_internalBtql.orElse(null)`. */ + fun _internalBtql(_internalBtql: Optional<_InternalBtql>) = + _internalBtql(_internalBtql.getOrNull()) + + /** + * Sets [Builder._internalBtql] to an arbitrary JSON value. + * + * You should usually call [Builder._internalBtql] with a well-typed [_InternalBtql] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun _internalBtql(_internalBtql: JsonField<_InternalBtql>) = apply { + this._internalBtql = _internalBtql + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectDatasetName]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .datasetName() + * .projectName() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectDatasetName = + ProjectDatasetName( + checkRequired("datasetName", datasetName), + checkRequired("projectName", projectName), + _internalBtql, + additionalProperties.toMutableMap(), + ) + } + + 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( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [_InternalBtql]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [_InternalBtql]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(_internalBtql: _InternalBtql) = apply { + additionalProperties = _internalBtql.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 [_InternalBtql]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is _InternalBtql && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "_InternalBtql{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectDatasetName && + datasetName == other.datasetName && + projectName == other.projectName && + _internalBtql == other._internalBtql && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(datasetName, projectName, _internalBtql, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectDatasetName{datasetName=$datasetName, projectName=$projectName, _internalBtql=$_internalBtql, additionalProperties=$additionalProperties}" + } + + /** Dataset rows */ + class DatasetRows + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun data(): List = data.getRequired("data") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField> = data + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [DatasetRows]. + * + * The following fields are required: + * ```java + * .data() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [DatasetRows]. */ + class Builder internal constructor() { + + private var data: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(datasetRows: DatasetRows) = apply { + data = datasetRows.data.map { it.toMutableList() } + additionalProperties = datasetRows.additionalProperties.toMutableMap() + } + + fun data(data: List) = data(JsonField.of(data)) + + /** + * Sets [Builder.data] to an arbitrary JSON value. + * + * You should usually call [Builder.data] with a well-typed `List` 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.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [Builder.data]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addData(data: JsonValue) = apply { + this.data = + (this.data ?: JsonField.of(mutableListOf())).also { + checkKnown("data", it).add(data) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [DatasetRows]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): DatasetRows = + DatasetRows( + checkRequired("data", data).map { it.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 + } + + return other is DatasetRows && + data == other.data && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(data, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "DatasetRows{data=$data, additionalProperties=$additionalProperties}" + } + } + + /** The function to evaluate */ + @JsonDeserialize(using = Score.Deserializer::class) + @JsonSerialize(using = Score.Serializer::class) + class Score + private constructor( + private val functionId: FunctionId? = null, + private val projectSlug: ProjectSlug? = null, + private val globalFunction: GlobalFunction? = null, + private val promptSessionId: PromptSessionId? = null, + private val inlineCode: InlineCode? = null, + private val inlinePrompt: InlinePrompt? = null, + private val _json: JsonValue? = null, + ) { + + /** Function id */ + fun functionId(): Optional = Optional.ofNullable(functionId) + + /** Project name and slug */ + fun projectSlug(): Optional = Optional.ofNullable(projectSlug) + + /** Global function name */ + fun globalFunction(): Optional = Optional.ofNullable(globalFunction) + + /** Prompt session id */ + fun promptSessionId(): Optional = Optional.ofNullable(promptSessionId) + + /** Inline code function */ + fun inlineCode(): Optional = Optional.ofNullable(inlineCode) + + /** Inline prompt definition */ + fun inlinePrompt(): Optional = Optional.ofNullable(inlinePrompt) + + fun isFunctionId(): Boolean = functionId != null + + fun isProjectSlug(): Boolean = projectSlug != null + + fun isGlobalFunction(): Boolean = globalFunction != null + + fun isPromptSessionId(): Boolean = promptSessionId != null + + fun isInlineCode(): Boolean = inlineCode != null + + fun isInlinePrompt(): Boolean = inlinePrompt != null + + /** Function id */ + fun asFunctionId(): FunctionId = functionId.getOrThrow("functionId") + + /** Project name and slug */ + fun asProjectSlug(): ProjectSlug = projectSlug.getOrThrow("projectSlug") + + /** Global function name */ + fun asGlobalFunction(): GlobalFunction = globalFunction.getOrThrow("globalFunction") + + /** Prompt session id */ + fun asPromptSessionId(): PromptSessionId = promptSessionId.getOrThrow("promptSessionId") + + /** Inline code function */ + fun asInlineCode(): InlineCode = inlineCode.getOrThrow("inlineCode") + + /** Inline prompt definition */ + fun asInlinePrompt(): InlinePrompt = inlinePrompt.getOrThrow("inlinePrompt") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + functionId != null -> visitor.visitFunctionId(functionId) + projectSlug != null -> visitor.visitProjectSlug(projectSlug) + globalFunction != null -> visitor.visitGlobalFunction(globalFunction) + promptSessionId != null -> visitor.visitPromptSessionId(promptSessionId) + inlineCode != null -> visitor.visitInlineCode(inlineCode) + inlinePrompt != null -> visitor.visitInlinePrompt(inlinePrompt) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Score = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitFunctionId(functionId: FunctionId) { + functionId.validate() + } + + override fun visitProjectSlug(projectSlug: ProjectSlug) { + projectSlug.validate() + } + + override fun visitGlobalFunction(globalFunction: GlobalFunction) { + globalFunction.validate() + } + + override fun visitPromptSessionId(promptSessionId: PromptSessionId) { + promptSessionId.validate() + } + + override fun visitInlineCode(inlineCode: InlineCode) { + inlineCode.validate() + } + + override fun visitInlinePrompt(inlinePrompt: InlinePrompt) { + inlinePrompt.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 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 + } + + return other is Score && + functionId == other.functionId && + projectSlug == other.projectSlug && + globalFunction == other.globalFunction && + promptSessionId == other.promptSessionId && + inlineCode == other.inlineCode && + inlinePrompt == other.inlinePrompt + } + + override fun hashCode(): Int = + Objects.hash( + functionId, + projectSlug, + globalFunction, + promptSessionId, + inlineCode, + inlinePrompt, + ) + + override fun toString(): String = + when { + functionId != null -> "Score{functionId=$functionId}" + projectSlug != null -> "Score{projectSlug=$projectSlug}" + globalFunction != null -> "Score{globalFunction=$globalFunction}" + promptSessionId != null -> "Score{promptSessionId=$promptSessionId}" + inlineCode != null -> "Score{inlineCode=$inlineCode}" + inlinePrompt != null -> "Score{inlinePrompt=$inlinePrompt}" + _json != null -> "Score{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Score") + } + + companion object { + + /** Function id */ + @JvmStatic fun ofFunctionId(functionId: FunctionId) = Score(functionId = functionId) + + /** Project name and slug */ + @JvmStatic + fun ofProjectSlug(projectSlug: ProjectSlug) = Score(projectSlug = projectSlug) + + /** Global function name */ + @JvmStatic + fun ofGlobalFunction(globalFunction: GlobalFunction) = + Score(globalFunction = globalFunction) + + /** Prompt session id */ + @JvmStatic + fun ofPromptSessionId(promptSessionId: PromptSessionId) = + Score(promptSessionId = promptSessionId) + + /** Inline code function */ + @JvmStatic fun ofInlineCode(inlineCode: InlineCode) = Score(inlineCode = inlineCode) + + /** Inline prompt definition */ + @JvmStatic + fun ofInlinePrompt(inlinePrompt: InlinePrompt) = Score(inlinePrompt = inlinePrompt) + } + + /** An interface that defines how to map each variant of [Score] to a value of type [T]. */ + interface Visitor { + + /** Function id */ + fun visitFunctionId(functionId: FunctionId): T + + /** Project name and slug */ + fun visitProjectSlug(projectSlug: ProjectSlug): T + + /** Global function name */ + fun visitGlobalFunction(globalFunction: GlobalFunction): T + + /** Prompt session id */ + fun visitPromptSessionId(promptSessionId: PromptSessionId): T + + /** Inline code function */ + fun visitInlineCode(inlineCode: InlineCode): T + + /** Inline prompt definition */ + fun visitInlinePrompt(inlinePrompt: InlinePrompt): T + + /** + * Maps an unknown variant of [Score] to a value of type [T]. + * + * An instance of [Score] 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 Score: $json") + } + } + + internal class Deserializer : BaseDeserializer(Score::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Score { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Score::class) { + + override fun serialize( + value: Score, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.functionId != null -> generator.writeObject(value.functionId) + value.projectSlug != null -> generator.writeObject(value.projectSlug) + value.globalFunction != null -> generator.writeObject(value.globalFunction) + value.promptSessionId != null -> generator.writeObject(value.promptSessionId) + value.inlineCode != null -> generator.writeObject(value.inlineCode) + value.inlinePrompt != null -> generator.writeObject(value.inlinePrompt) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Score") + } + } + } + + /** Function id */ + class FunctionId + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 functionId(): String = functionId.getRequired("function_id") + + /** + * The version of the function + * + * @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") + + /** + * Returns the raw JSON value of [functionId]. + * + * Unlike [functionId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_id") + @ExcludeMissing + fun _functionId(): JsonField = functionId + + /** + * 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 + + @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 [FunctionId]. + * + * The following fields are required: + * ```java + * .functionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionId]. */ + class Builder internal constructor() { + + private var functionId: JsonField? = null + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionId: FunctionId) = apply { + this.functionId = functionId.functionId + version = functionId.version + additionalProperties = functionId.additionalProperties.toMutableMap() + } + + /** The ID of the function */ + fun functionId(functionId: String) = functionId(JsonField.of(functionId)) + + /** + * Sets [Builder.functionId] to an arbitrary JSON value. + * + * You should usually call [Builder.functionId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun functionId(functionId: JsonField) = apply { + this.functionId = functionId + } + + /** The version of the function */ + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionId]. + * + * 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(): FunctionId = + FunctionId( + checkRequired("functionId", functionId), + version, + 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 + } + + return other is FunctionId && + functionId == other.functionId && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(functionId, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionId{functionId=$functionId, version=$version, additionalProperties=$additionalProperties}" + } + + /** Project name and slug */ + class ProjectSlug + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 projectName(): String = projectName.getRequired("project_name") + + /** + * The slug of the function + * + * @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") + + /** + * The version of the function + * + * @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") + + /** + * Returns the raw JSON value of [projectName]. + * + * Unlike [projectName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("project_name") + @ExcludeMissing + fun _projectName(): JsonField = projectName + + /** + * 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 [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + + @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 [ProjectSlug]. + * + * The following fields are required: + * ```java + * .projectName() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectSlug]. */ + class Builder internal constructor() { + + private var projectName: JsonField? = null + private var slug: JsonField? = null + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectSlug: ProjectSlug) = apply { + projectName = projectSlug.projectName + slug = projectSlug.slug + version = projectSlug.version + additionalProperties = projectSlug.additionalProperties.toMutableMap() + } + + /** The name of the project containing the function */ + fun projectName(projectName: String) = projectName(JsonField.of(projectName)) + + /** + * Sets [Builder.projectName] to an arbitrary JSON value. + * + * You should usually call [Builder.projectName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun projectName(projectName: JsonField) = apply { + this.projectName = projectName + } + + /** The slug of the function */ + 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 } + + /** The version of the function */ + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectSlug]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .projectName() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectSlug = + ProjectSlug( + checkRequired("projectName", projectName), + checkRequired("slug", slug), + version, + 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 + } + + return other is ProjectSlug && + projectName == other.projectName && + slug == other.slug && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(projectName, slug, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectSlug{projectName=$projectName, slug=$slug, version=$version, additionalProperties=$additionalProperties}" + } + + /** Global function name */ + class GlobalFunction + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 globalFunction(): String = globalFunction.getRequired("global_function") + + /** + * Returns the raw JSON value of [globalFunction]. + * + * Unlike [globalFunction], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("global_function") + @ExcludeMissing + fun _globalFunction(): JsonField = globalFunction + + @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 [GlobalFunction]. + * + * The following fields are required: + * ```java + * .globalFunction() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GlobalFunction]. */ + class Builder internal constructor() { + + private var globalFunction: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(globalFunction: GlobalFunction) = apply { + this.globalFunction = globalFunction.globalFunction + additionalProperties = globalFunction.additionalProperties.toMutableMap() + } + + /** + * The name of the global function. Currently, the global namespace includes the + * functions in autoevals + */ + fun globalFunction(globalFunction: String) = + globalFunction(JsonField.of(globalFunction)) + + /** + * Sets [Builder.globalFunction] to an arbitrary JSON value. + * + * You should usually call [Builder.globalFunction] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun globalFunction(globalFunction: JsonField) = apply { + this.globalFunction = globalFunction + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [GlobalFunction]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .globalFunction() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GlobalFunction = + GlobalFunction( + checkRequired("globalFunction", globalFunction), + 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 + } + + return other is GlobalFunction && + globalFunction == other.globalFunction && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(globalFunction, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GlobalFunction{globalFunction=$globalFunction, additionalProperties=$additionalProperties}" + } + + /** Prompt session id */ + class PromptSessionId + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 promptSessionFunctionId(): String = + promptSessionFunctionId.getRequired("prompt_session_function_id") + + /** + * The ID of the prompt session + * + * @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 promptSessionId(): String = promptSessionId.getRequired("prompt_session_id") + + /** + * The version of the function + * + * @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") + + /** + * Returns the raw JSON value of [promptSessionFunctionId]. + * + * Unlike [promptSessionFunctionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("prompt_session_function_id") + @ExcludeMissing + fun _promptSessionFunctionId(): JsonField = promptSessionFunctionId + + /** + * Returns the raw JSON value of [promptSessionId]. + * + * Unlike [promptSessionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("prompt_session_id") + @ExcludeMissing + fun _promptSessionId(): JsonField = promptSessionId + + /** + * 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 + + @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 [PromptSessionId]. + * + * The following fields are required: + * ```java + * .promptSessionFunctionId() + * .promptSessionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptSessionId]. */ + class Builder internal constructor() { + + private var promptSessionFunctionId: JsonField? = null + private var promptSessionId: JsonField? = null + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(promptSessionId: PromptSessionId) = apply { + promptSessionFunctionId = promptSessionId.promptSessionFunctionId + this.promptSessionId = promptSessionId.promptSessionId + version = promptSessionId.version + additionalProperties = promptSessionId.additionalProperties.toMutableMap() + } + + /** The ID of the function in the prompt session */ + fun promptSessionFunctionId(promptSessionFunctionId: String) = + promptSessionFunctionId(JsonField.of(promptSessionFunctionId)) + + /** + * Sets [Builder.promptSessionFunctionId] to an arbitrary JSON value. + * + * You should usually call [Builder.promptSessionFunctionId] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun promptSessionFunctionId(promptSessionFunctionId: JsonField) = apply { + this.promptSessionFunctionId = promptSessionFunctionId + } + + /** The ID of the prompt session */ + fun promptSessionId(promptSessionId: String) = + promptSessionId(JsonField.of(promptSessionId)) + + /** + * Sets [Builder.promptSessionId] to an arbitrary JSON value. + * + * You should usually call [Builder.promptSessionId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun promptSessionId(promptSessionId: JsonField) = apply { + this.promptSessionId = promptSessionId + } + + /** The version of the function */ + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [PromptSessionId]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .promptSessionFunctionId() + * .promptSessionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PromptSessionId = + PromptSessionId( + checkRequired("promptSessionFunctionId", promptSessionFunctionId), + checkRequired("promptSessionId", promptSessionId), + version, + 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 + } + + return other is PromptSessionId && + promptSessionFunctionId == other.promptSessionFunctionId && + promptSessionId == other.promptSessionId && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + promptSessionFunctionId, + promptSessionId, + version, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PromptSessionId{promptSessionFunctionId=$promptSessionFunctionId, promptSessionId=$promptSessionId, version=$version, additionalProperties=$additionalProperties}" + } + + /** Inline code function */ + class InlineCode + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 code(): String = code.getRequired("code") + + /** + * @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 inlineContext(): InlineContext = inlineContext.getRequired("inline_context") + + /** + * The name of the inline code function + * + * @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 [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + + /** + * Returns the raw JSON value of [inlineContext]. + * + * Unlike [inlineContext], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("inline_context") + @ExcludeMissing + fun _inlineContext(): JsonField = inlineContext + + /** + * 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 [InlineCode]. + * + * The following fields are required: + * ```java + * .code() + * .inlineContext() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InlineCode]. */ + class Builder internal constructor() { + + private var code: JsonField? = null + private var inlineContext: JsonField? = null + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(inlineCode: InlineCode) = apply { + code = inlineCode.code + inlineContext = inlineCode.inlineContext + name = inlineCode.name + additionalProperties = inlineCode.additionalProperties.toMutableMap() + } + + /** The inline code to execute */ + fun code(code: String) = code(JsonField.of(code)) + + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun code(code: JsonField) = apply { this.code = code } + + fun inlineContext(inlineContext: InlineContext) = + inlineContext(JsonField.of(inlineContext)) + + /** + * Sets [Builder.inlineContext] to an arbitrary JSON value. + * + * You should usually call [Builder.inlineContext] with a well-typed [InlineContext] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun inlineContext(inlineContext: JsonField) = apply { + this.inlineContext = inlineContext + } + + /** The name of the inline code function */ + 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 [InlineCode]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * .inlineContext() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InlineCode = + InlineCode( + checkRequired("code", code), + checkRequired("inlineContext", inlineContext), + name, + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun runtime(): Runtime = runtime.getRequired("runtime") + + /** + * @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 version(): String = version.getRequired("version") + + /** + * Returns the raw JSON value of [runtime]. + * + * Unlike [runtime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("runtime") + @ExcludeMissing + fun _runtime(): JsonField = runtime + + /** + * 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 + + @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 [InlineContext]. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InlineContext]. */ + class Builder internal constructor() { + + private var runtime: JsonField? = null + private var version: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(inlineContext: InlineContext) = apply { + runtime = inlineContext.runtime + version = inlineContext.version + additionalProperties = inlineContext.additionalProperties.toMutableMap() + } + + fun runtime(runtime: Runtime) = runtime(JsonField.of(runtime)) + + /** + * Sets [Builder.runtime] to an arbitrary JSON value. + * + * You should usually call [Builder.runtime] with a well-typed [Runtime] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun runtime(runtime: JsonField) = apply { this.runtime = runtime } + + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InlineContext]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InlineContext = + InlineContext( + checkRequired("runtime", runtime), + checkRequired("version", version), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val NODE = of("node") + + @JvmField val PYTHON = of("python") + + @JvmStatic fun of(value: String) = Runtime(JsonField.of(value)) + } + + /** An enum containing [Runtime]'s known values. */ + enum class Known { + NODE, + PYTHON, + } + + /** + * An enum containing [Runtime]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Runtime] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + NODE, + PYTHON, + /** + * An enum member indicating that [Runtime] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + NODE -> Value.NODE + PYTHON -> Value.PYTHON + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a + * not a known member. + */ + fun known(): Known = + when (this) { + NODE -> Known.NODE + PYTHON -> Known.PYTHON + else -> throw BraintrustInvalidDataException("Unknown Runtime: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does + * not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Runtime && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InlineContext && + runtime == other.runtime && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(runtime, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InlineContext{runtime=$runtime, version=$version, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InlineCode && + code == other.code && + inlineContext == other.inlineContext && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(code, inlineContext, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InlineCode{code=$code, inlineContext=$inlineContext, name=$name, additionalProperties=$additionalProperties}" + } + + /** Inline prompt definition */ + class InlinePrompt + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = inlinePrompt.getOptional("inline_prompt") + + /** + * The name of the inline 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") + + /** + * Returns the raw JSON value of [inlinePrompt]. + * + * Unlike [inlinePrompt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("inline_prompt") + @ExcludeMissing + fun _inlinePrompt(): JsonField = inlinePrompt + + /** + * 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 [InlinePrompt]. + * + * The following fields are required: + * ```java + * .inlinePrompt() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InlinePrompt]. */ + class Builder internal constructor() { + + private var inlinePrompt: JsonField? = null + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(inlinePrompt: InlinePrompt) = apply { + this.inlinePrompt = inlinePrompt.inlinePrompt + name = inlinePrompt.name + additionalProperties = inlinePrompt.additionalProperties.toMutableMap() + } + + /** The prompt, model, and its parameters */ + fun inlinePrompt(inlinePrompt: PromptData?) = + inlinePrompt(JsonField.ofNullable(inlinePrompt)) + + /** Alias for calling [Builder.inlinePrompt] with `inlinePrompt.orElse(null)`. */ + fun inlinePrompt(inlinePrompt: Optional) = + inlinePrompt(inlinePrompt.getOrNull()) + + /** + * Sets [Builder.inlinePrompt] to an arbitrary JSON value. + * + * You should usually call [Builder.inlinePrompt] with a well-typed [PromptData] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun inlinePrompt(inlinePrompt: JsonField) = apply { + this.inlinePrompt = inlinePrompt + } + + /** The name of the inline 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 } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InlinePrompt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .inlinePrompt() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InlinePrompt = + InlinePrompt( + checkRequired("inlinePrompt", inlinePrompt), + name, + 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 + } + + return other is InlinePrompt && + inlinePrompt == other.inlinePrompt && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(inlinePrompt, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InlinePrompt{inlinePrompt=$inlinePrompt, name=$name, additionalProperties=$additionalProperties}" + } + } + + /** The function to evaluate */ + @JsonDeserialize(using = Task.Deserializer::class) + @JsonSerialize(using = Task.Serializer::class) + class Task + private constructor( + private val functionId: FunctionId? = null, + private val projectSlug: ProjectSlug? = null, + private val globalFunction: GlobalFunction? = null, + private val promptSessionId: PromptSessionId? = null, + private val inlineCode: InlineCode? = null, + private val inlinePrompt: InlinePrompt? = null, + private val _json: JsonValue? = null, + ) { + + /** Function id */ + fun functionId(): Optional = Optional.ofNullable(functionId) + + /** Project name and slug */ + fun projectSlug(): Optional = Optional.ofNullable(projectSlug) + + /** Global function name */ + fun globalFunction(): Optional = Optional.ofNullable(globalFunction) + + /** Prompt session id */ + fun promptSessionId(): Optional = Optional.ofNullable(promptSessionId) + + /** Inline code function */ + fun inlineCode(): Optional = Optional.ofNullable(inlineCode) + + /** Inline prompt definition */ + fun inlinePrompt(): Optional = Optional.ofNullable(inlinePrompt) + + fun isFunctionId(): Boolean = functionId != null + + fun isProjectSlug(): Boolean = projectSlug != null + + fun isGlobalFunction(): Boolean = globalFunction != null + + fun isPromptSessionId(): Boolean = promptSessionId != null + + fun isInlineCode(): Boolean = inlineCode != null + + fun isInlinePrompt(): Boolean = inlinePrompt != null + + /** Function id */ + fun asFunctionId(): FunctionId = functionId.getOrThrow("functionId") + + /** Project name and slug */ + fun asProjectSlug(): ProjectSlug = projectSlug.getOrThrow("projectSlug") + + /** Global function name */ + fun asGlobalFunction(): GlobalFunction = globalFunction.getOrThrow("globalFunction") + + /** Prompt session id */ + fun asPromptSessionId(): PromptSessionId = promptSessionId.getOrThrow("promptSessionId") + + /** Inline code function */ + fun asInlineCode(): InlineCode = inlineCode.getOrThrow("inlineCode") + + /** Inline prompt definition */ + fun asInlinePrompt(): InlinePrompt = inlinePrompt.getOrThrow("inlinePrompt") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + functionId != null -> visitor.visitFunctionId(functionId) + projectSlug != null -> visitor.visitProjectSlug(projectSlug) + globalFunction != null -> visitor.visitGlobalFunction(globalFunction) + promptSessionId != null -> visitor.visitPromptSessionId(promptSessionId) + inlineCode != null -> visitor.visitInlineCode(inlineCode) + inlinePrompt != null -> visitor.visitInlinePrompt(inlinePrompt) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Task = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitFunctionId(functionId: FunctionId) { + functionId.validate() + } + + override fun visitProjectSlug(projectSlug: ProjectSlug) { + projectSlug.validate() + } + + override fun visitGlobalFunction(globalFunction: GlobalFunction) { + globalFunction.validate() + } + + override fun visitPromptSessionId(promptSessionId: PromptSessionId) { + promptSessionId.validate() + } + + override fun visitInlineCode(inlineCode: InlineCode) { + inlineCode.validate() + } + + override fun visitInlinePrompt(inlinePrompt: InlinePrompt) { + inlinePrompt.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 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 + } + + return other is Task && + functionId == other.functionId && + projectSlug == other.projectSlug && + globalFunction == other.globalFunction && + promptSessionId == other.promptSessionId && + inlineCode == other.inlineCode && + inlinePrompt == other.inlinePrompt + } + + override fun hashCode(): Int = + Objects.hash( + functionId, + projectSlug, + globalFunction, + promptSessionId, + inlineCode, + inlinePrompt, + ) + + override fun toString(): String = + when { + functionId != null -> "Task{functionId=$functionId}" + projectSlug != null -> "Task{projectSlug=$projectSlug}" + globalFunction != null -> "Task{globalFunction=$globalFunction}" + promptSessionId != null -> "Task{promptSessionId=$promptSessionId}" + inlineCode != null -> "Task{inlineCode=$inlineCode}" + inlinePrompt != null -> "Task{inlinePrompt=$inlinePrompt}" + _json != null -> "Task{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Task") + } + + companion object { + + /** Function id */ + @JvmStatic fun ofFunctionId(functionId: FunctionId) = Task(functionId = functionId) + + /** Project name and slug */ + @JvmStatic fun ofProjectSlug(projectSlug: ProjectSlug) = Task(projectSlug = projectSlug) + + /** Global function name */ + @JvmStatic + fun ofGlobalFunction(globalFunction: GlobalFunction) = + Task(globalFunction = globalFunction) + + /** Prompt session id */ + @JvmStatic + fun ofPromptSessionId(promptSessionId: PromptSessionId) = + Task(promptSessionId = promptSessionId) + + /** Inline code function */ + @JvmStatic fun ofInlineCode(inlineCode: InlineCode) = Task(inlineCode = inlineCode) + + /** Inline prompt definition */ + @JvmStatic + fun ofInlinePrompt(inlinePrompt: InlinePrompt) = Task(inlinePrompt = inlinePrompt) + } + + /** An interface that defines how to map each variant of [Task] to a value of type [T]. */ + interface Visitor { + + /** Function id */ + fun visitFunctionId(functionId: FunctionId): T + + /** Project name and slug */ + fun visitProjectSlug(projectSlug: ProjectSlug): T + + /** Global function name */ + fun visitGlobalFunction(globalFunction: GlobalFunction): T + + /** Prompt session id */ + fun visitPromptSessionId(promptSessionId: PromptSessionId): T + + /** Inline code function */ + fun visitInlineCode(inlineCode: InlineCode): T + + /** Inline prompt definition */ + fun visitInlinePrompt(inlinePrompt: InlinePrompt): T + + /** + * Maps an unknown variant of [Task] to a value of type [T]. + * + * An instance of [Task] 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 Task: $json") + } + } + + internal class Deserializer : BaseDeserializer(Task::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Task { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Task::class) { + + override fun serialize( + value: Task, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.functionId != null -> generator.writeObject(value.functionId) + value.projectSlug != null -> generator.writeObject(value.projectSlug) + value.globalFunction != null -> generator.writeObject(value.globalFunction) + value.promptSessionId != null -> generator.writeObject(value.promptSessionId) + value.inlineCode != null -> generator.writeObject(value.inlineCode) + value.inlinePrompt != null -> generator.writeObject(value.inlinePrompt) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Task") + } + } + } + + /** Function id */ + class FunctionId + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 functionId(): String = functionId.getRequired("function_id") + + /** + * The version of the function + * + * @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") + + /** + * Returns the raw JSON value of [functionId]. + * + * Unlike [functionId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_id") + @ExcludeMissing + fun _functionId(): JsonField = functionId + + /** + * 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 + + @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 [FunctionId]. + * + * The following fields are required: + * ```java + * .functionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionId]. */ + class Builder internal constructor() { + + private var functionId: JsonField? = null + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionId: FunctionId) = apply { + this.functionId = functionId.functionId + version = functionId.version + additionalProperties = functionId.additionalProperties.toMutableMap() + } + + /** The ID of the function */ + fun functionId(functionId: String) = functionId(JsonField.of(functionId)) + + /** + * Sets [Builder.functionId] to an arbitrary JSON value. + * + * You should usually call [Builder.functionId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun functionId(functionId: JsonField) = apply { + this.functionId = functionId + } + + /** The version of the function */ + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionId]. + * + * 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(): FunctionId = + FunctionId( + checkRequired("functionId", functionId), + version, + 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 + } + + return other is FunctionId && + functionId == other.functionId && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(functionId, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionId{functionId=$functionId, version=$version, additionalProperties=$additionalProperties}" + } + + /** Project name and slug */ + class ProjectSlug + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 projectName(): String = projectName.getRequired("project_name") + + /** + * The slug of the function + * + * @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") + + /** + * The version of the function + * + * @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") + + /** + * Returns the raw JSON value of [projectName]. + * + * Unlike [projectName], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("project_name") + @ExcludeMissing + fun _projectName(): JsonField = projectName + + /** + * 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 [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + + @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 [ProjectSlug]. + * + * The following fields are required: + * ```java + * .projectName() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectSlug]. */ + class Builder internal constructor() { + + private var projectName: JsonField? = null + private var slug: JsonField? = null + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectSlug: ProjectSlug) = apply { + projectName = projectSlug.projectName + slug = projectSlug.slug + version = projectSlug.version + additionalProperties = projectSlug.additionalProperties.toMutableMap() + } + + /** The name of the project containing the function */ + fun projectName(projectName: String) = projectName(JsonField.of(projectName)) + + /** + * Sets [Builder.projectName] to an arbitrary JSON value. + * + * You should usually call [Builder.projectName] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun projectName(projectName: JsonField) = apply { + this.projectName = projectName + } + + /** The slug of the function */ + 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 } + + /** The version of the function */ + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectSlug]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .projectName() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectSlug = + ProjectSlug( + checkRequired("projectName", projectName), + checkRequired("slug", slug), + version, + 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 + } + + return other is ProjectSlug && + projectName == other.projectName && + slug == other.slug && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(projectName, slug, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectSlug{projectName=$projectName, slug=$slug, version=$version, additionalProperties=$additionalProperties}" + } + + /** Global function name */ + class GlobalFunction + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 globalFunction(): String = globalFunction.getRequired("global_function") + + /** + * Returns the raw JSON value of [globalFunction]. + * + * Unlike [globalFunction], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("global_function") + @ExcludeMissing + fun _globalFunction(): JsonField = globalFunction + + @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 [GlobalFunction]. + * + * The following fields are required: + * ```java + * .globalFunction() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GlobalFunction]. */ + class Builder internal constructor() { + + private var globalFunction: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(globalFunction: GlobalFunction) = apply { + this.globalFunction = globalFunction.globalFunction + additionalProperties = globalFunction.additionalProperties.toMutableMap() + } + + /** + * The name of the global function. Currently, the global namespace includes the + * functions in autoevals + */ + fun globalFunction(globalFunction: String) = + globalFunction(JsonField.of(globalFunction)) + + /** + * Sets [Builder.globalFunction] to an arbitrary JSON value. + * + * You should usually call [Builder.globalFunction] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun globalFunction(globalFunction: JsonField) = apply { + this.globalFunction = globalFunction + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [GlobalFunction]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .globalFunction() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GlobalFunction = + GlobalFunction( + checkRequired("globalFunction", globalFunction), + 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 + } + + return other is GlobalFunction && + globalFunction == other.globalFunction && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(globalFunction, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GlobalFunction{globalFunction=$globalFunction, additionalProperties=$additionalProperties}" + } + + /** Prompt session id */ + class PromptSessionId + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 promptSessionFunctionId(): String = + promptSessionFunctionId.getRequired("prompt_session_function_id") + + /** + * The ID of the prompt session + * + * @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 promptSessionId(): String = promptSessionId.getRequired("prompt_session_id") + + /** + * The version of the function + * + * @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") + + /** + * Returns the raw JSON value of [promptSessionFunctionId]. + * + * Unlike [promptSessionFunctionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("prompt_session_function_id") + @ExcludeMissing + fun _promptSessionFunctionId(): JsonField = promptSessionFunctionId + + /** + * Returns the raw JSON value of [promptSessionId]. + * + * Unlike [promptSessionId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("prompt_session_id") + @ExcludeMissing + fun _promptSessionId(): JsonField = promptSessionId + + /** + * 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 + + @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 [PromptSessionId]. + * + * The following fields are required: + * ```java + * .promptSessionFunctionId() + * .promptSessionId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptSessionId]. */ + class Builder internal constructor() { + + private var promptSessionFunctionId: JsonField? = null + private var promptSessionId: JsonField? = null + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(promptSessionId: PromptSessionId) = apply { + promptSessionFunctionId = promptSessionId.promptSessionFunctionId + this.promptSessionId = promptSessionId.promptSessionId + version = promptSessionId.version + additionalProperties = promptSessionId.additionalProperties.toMutableMap() + } + + /** The ID of the function in the prompt session */ + fun promptSessionFunctionId(promptSessionFunctionId: String) = + promptSessionFunctionId(JsonField.of(promptSessionFunctionId)) + + /** + * Sets [Builder.promptSessionFunctionId] to an arbitrary JSON value. + * + * You should usually call [Builder.promptSessionFunctionId] with a well-typed + * [String] value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun promptSessionFunctionId(promptSessionFunctionId: JsonField) = apply { + this.promptSessionFunctionId = promptSessionFunctionId + } + + /** The ID of the prompt session */ + fun promptSessionId(promptSessionId: String) = + promptSessionId(JsonField.of(promptSessionId)) + + /** + * Sets [Builder.promptSessionId] to an arbitrary JSON value. + * + * You should usually call [Builder.promptSessionId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun promptSessionId(promptSessionId: JsonField) = apply { + this.promptSessionId = promptSessionId + } + + /** The version of the function */ + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [PromptSessionId]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .promptSessionFunctionId() + * .promptSessionId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PromptSessionId = + PromptSessionId( + checkRequired("promptSessionFunctionId", promptSessionFunctionId), + checkRequired("promptSessionId", promptSessionId), + version, + 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 + } + + return other is PromptSessionId && + promptSessionFunctionId == other.promptSessionFunctionId && + promptSessionId == other.promptSessionId && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + promptSessionFunctionId, + promptSessionId, + version, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PromptSessionId{promptSessionFunctionId=$promptSessionFunctionId, promptSessionId=$promptSessionId, version=$version, additionalProperties=$additionalProperties}" + } + + /** Inline code function */ + class InlineCode + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 code(): String = code.getRequired("code") + + /** + * @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 inlineContext(): InlineContext = inlineContext.getRequired("inline_context") + + /** + * The name of the inline code function + * + * @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 [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + + /** + * Returns the raw JSON value of [inlineContext]. + * + * Unlike [inlineContext], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("inline_context") + @ExcludeMissing + fun _inlineContext(): JsonField = inlineContext + + /** + * 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 [InlineCode]. + * + * The following fields are required: + * ```java + * .code() + * .inlineContext() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InlineCode]. */ + class Builder internal constructor() { + + private var code: JsonField? = null + private var inlineContext: JsonField? = null + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(inlineCode: InlineCode) = apply { + code = inlineCode.code + inlineContext = inlineCode.inlineContext + name = inlineCode.name + additionalProperties = inlineCode.additionalProperties.toMutableMap() + } + + /** The inline code to execute */ + fun code(code: String) = code(JsonField.of(code)) + + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun code(code: JsonField) = apply { this.code = code } + + fun inlineContext(inlineContext: InlineContext) = + inlineContext(JsonField.of(inlineContext)) + + /** + * Sets [Builder.inlineContext] to an arbitrary JSON value. + * + * You should usually call [Builder.inlineContext] with a well-typed [InlineContext] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun inlineContext(inlineContext: JsonField) = apply { + this.inlineContext = inlineContext + } + + /** The name of the inline code function */ + 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 [InlineCode]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * .inlineContext() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InlineCode = + InlineCode( + checkRequired("code", code), + checkRequired("inlineContext", inlineContext), + name, + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun runtime(): Runtime = runtime.getRequired("runtime") + + /** + * @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 version(): String = version.getRequired("version") + + /** + * Returns the raw JSON value of [runtime]. + * + * Unlike [runtime], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("runtime") + @ExcludeMissing + fun _runtime(): JsonField = runtime + + /** + * 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 + + @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 [InlineContext]. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InlineContext]. */ + class Builder internal constructor() { + + private var runtime: JsonField? = null + private var version: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(inlineContext: InlineContext) = apply { + runtime = inlineContext.runtime + version = inlineContext.version + additionalProperties = inlineContext.additionalProperties.toMutableMap() + } + + fun runtime(runtime: Runtime) = runtime(JsonField.of(runtime)) + + /** + * Sets [Builder.runtime] to an arbitrary JSON value. + * + * You should usually call [Builder.runtime] with a well-typed [Runtime] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun runtime(runtime: JsonField) = apply { this.runtime = runtime } + + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InlineContext]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InlineContext = + InlineContext( + checkRequired("runtime", runtime), + checkRequired("version", version), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val NODE = of("node") + + @JvmField val PYTHON = of("python") + + @JvmStatic fun of(value: String) = Runtime(JsonField.of(value)) + } + + /** An enum containing [Runtime]'s known values. */ + enum class Known { + NODE, + PYTHON, + } + + /** + * An enum containing [Runtime]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Runtime] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + NODE, + PYTHON, + /** + * An enum member indicating that [Runtime] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + NODE -> Value.NODE + PYTHON -> Value.PYTHON + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a + * not a known member. + */ + fun known(): Known = + when (this) { + NODE -> Known.NODE + PYTHON -> Known.PYTHON + else -> throw BraintrustInvalidDataException("Unknown Runtime: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does + * not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Runtime && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InlineContext && + runtime == other.runtime && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(runtime, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InlineContext{runtime=$runtime, version=$version, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InlineCode && + code == other.code && + inlineContext == other.inlineContext && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(code, inlineContext, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InlineCode{code=$code, inlineContext=$inlineContext, name=$name, additionalProperties=$additionalProperties}" + } + + /** Inline prompt definition */ + class InlinePrompt + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = inlinePrompt.getOptional("inline_prompt") + + /** + * The name of the inline 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") + + /** + * Returns the raw JSON value of [inlinePrompt]. + * + * Unlike [inlinePrompt], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("inline_prompt") + @ExcludeMissing + fun _inlinePrompt(): JsonField = inlinePrompt + + /** + * 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 [InlinePrompt]. + * + * The following fields are required: + * ```java + * .inlinePrompt() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InlinePrompt]. */ + class Builder internal constructor() { + + private var inlinePrompt: JsonField? = null + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(inlinePrompt: InlinePrompt) = apply { + this.inlinePrompt = inlinePrompt.inlinePrompt + name = inlinePrompt.name + additionalProperties = inlinePrompt.additionalProperties.toMutableMap() + } + + /** The prompt, model, and its parameters */ + fun inlinePrompt(inlinePrompt: PromptData?) = + inlinePrompt(JsonField.ofNullable(inlinePrompt)) + + /** Alias for calling [Builder.inlinePrompt] with `inlinePrompt.orElse(null)`. */ + fun inlinePrompt(inlinePrompt: Optional) = + inlinePrompt(inlinePrompt.getOrNull()) + + /** + * Sets [Builder.inlinePrompt] to an arbitrary JSON value. + * + * You should usually call [Builder.inlinePrompt] with a well-typed [PromptData] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun inlinePrompt(inlinePrompt: JsonField) = apply { + this.inlinePrompt = inlinePrompt + } + + /** The name of the inline 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 } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InlinePrompt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .inlinePrompt() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InlinePrompt = + InlinePrompt( + checkRequired("inlinePrompt", inlinePrompt), + name, + 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 + } + + return other is InlinePrompt && + inlinePrompt == other.inlinePrompt && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(inlinePrompt, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InlinePrompt{inlinePrompt=$inlinePrompt, name=$name, additionalProperties=$additionalProperties}" + } + } + + /** + * Optional settings for collecting git metadata. By default, will collect all git metadata + * fields allowed in org-level settings. + */ + class GitMetadataSettings + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun collect(): Collect = collect.getRequired("collect") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun fields(): Optional> = fields.getOptional("fields") + + /** + * Returns the raw JSON value of [collect]. + * + * Unlike [collect], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("collect") @ExcludeMissing fun _collect(): JsonField = collect + + /** + * Returns the raw JSON value of [fields]. + * + * Unlike [fields], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("fields") @ExcludeMissing fun _fields(): JsonField> = fields + + @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 [GitMetadataSettings]. + * + * The following fields are required: + * ```java + * .collect() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GitMetadataSettings]. */ + class Builder internal constructor() { + + private var collect: JsonField? = null + private var fields: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(gitMetadataSettings: GitMetadataSettings) = apply { + collect = gitMetadataSettings.collect + fields = gitMetadataSettings.fields.map { it.toMutableList() } + additionalProperties = gitMetadataSettings.additionalProperties.toMutableMap() + } + + fun collect(collect: Collect) = collect(JsonField.of(collect)) + + /** + * Sets [Builder.collect] to an arbitrary JSON value. + * + * You should usually call [Builder.collect] with a well-typed [Collect] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun collect(collect: JsonField) = apply { this.collect = collect } + + fun fields(fields: List) = fields(JsonField.of(fields)) + + /** + * Sets [Builder.fields] to an arbitrary JSON value. + * + * You should usually call [Builder.fields] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun fields(fields: JsonField>) = apply { + this.fields = fields.map { it.toMutableList() } + } + + /** + * Adds a single [Field] to [fields]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addField(field: Field) = apply { + fields = + (fields ?: JsonField.of(mutableListOf())).also { + checkKnown("fields", it).add(field) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [GitMetadataSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .collect() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GitMetadataSettings = + GitMetadataSettings( + checkRequired("collect", collect), + (fields ?: JsonMissing.of()).map { it.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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ALL = of("all") + + @JvmField val NONE = of("none") + + @JvmField val SOME = of("some") + + @JvmStatic fun of(value: String) = Collect(JsonField.of(value)) + } + + /** An enum containing [Collect]'s known values. */ + enum class Known { + ALL, + NONE, + SOME, + } + + /** + * An enum containing [Collect]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Collect] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ALL, + NONE, + SOME, + /** + * An enum member indicating that [Collect] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ALL -> Value.ALL + NONE -> Value.NONE + SOME -> Value.SOME + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + ALL -> Known.ALL + NONE -> Known.NONE + SOME -> Known.SOME + else -> throw BraintrustInvalidDataException("Unknown Collect: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Collect && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Field @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val COMMIT = of("commit") + + @JvmField val BRANCH = of("branch") + + @JvmField val TAG = of("tag") + + @JvmField val DIRTY = of("dirty") + + @JvmField val AUTHOR_NAME = of("author_name") + + @JvmField val AUTHOR_EMAIL = of("author_email") + + @JvmField val COMMIT_MESSAGE = of("commit_message") + + @JvmField val COMMIT_TIME = of("commit_time") + + @JvmField val GIT_DIFF = of("git_diff") + + @JvmStatic fun of(value: String) = Field(JsonField.of(value)) + } + + /** An enum containing [Field]'s known values. */ + enum class Known { + COMMIT, + BRANCH, + TAG, + DIRTY, + AUTHOR_NAME, + AUTHOR_EMAIL, + COMMIT_MESSAGE, + COMMIT_TIME, + GIT_DIFF, + } + + /** + * An enum containing [Field]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Field] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + COMMIT, + BRANCH, + TAG, + DIRTY, + AUTHOR_NAME, + AUTHOR_EMAIL, + COMMIT_MESSAGE, + COMMIT_TIME, + GIT_DIFF, + /** + * An enum member indicating that [Field] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + COMMIT -> Value.COMMIT + BRANCH -> Value.BRANCH + TAG -> Value.TAG + DIRTY -> Value.DIRTY + AUTHOR_NAME -> Value.AUTHOR_NAME + AUTHOR_EMAIL -> Value.AUTHOR_EMAIL + COMMIT_MESSAGE -> Value.COMMIT_MESSAGE + COMMIT_TIME -> Value.COMMIT_TIME + GIT_DIFF -> Value.GIT_DIFF + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + COMMIT -> Known.COMMIT + BRANCH -> Known.BRANCH + TAG -> Known.TAG + DIRTY -> Known.DIRTY + AUTHOR_NAME -> Known.AUTHOR_NAME + AUTHOR_EMAIL -> Known.AUTHOR_EMAIL + COMMIT_MESSAGE -> Known.COMMIT_MESSAGE + COMMIT_TIME -> Known.COMMIT_TIME + GIT_DIFF -> Known.GIT_DIFF + else -> throw BraintrustInvalidDataException("Unknown Field: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Field && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GitMetadataSettings && + collect == other.collect && + fields == other.fields && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(collect, fields, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GitMetadataSettings{collect=$collect, fields=$fields, additionalProperties=$additionalProperties}" + } + + /** + * Optional experiment-level metadata to store about the evaluation. You can later use this to + * slice & dice across experiments. + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + /** Options for tracing the evaluation */ + @JsonDeserialize(using = Parent.Deserializer::class) + @JsonSerialize(using = Parent.Serializer::class) + class Parent + private constructor( + private val spanParentStruct: SpanParentStruct? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + /** Span parent properties */ + fun spanParentStruct(): Optional = Optional.ofNullable(spanParentStruct) + + /** The parent's span identifier, created by calling `.export()` on a span */ + fun string(): Optional = Optional.ofNullable(string) + + fun isSpanParentStruct(): Boolean = spanParentStruct != null + + fun isString(): Boolean = string != null + + /** Span parent properties */ + fun asSpanParentStruct(): SpanParentStruct = spanParentStruct.getOrThrow("spanParentStruct") + + /** The parent's span identifier, created by calling `.export()` on a span */ + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Parent = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitSpanParentStruct(spanParentStruct: SpanParentStruct) { + spanParentStruct.validate() + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 + } + + return other is Parent && + spanParentStruct == other.spanParentStruct && + string == other.string + } + + override fun hashCode(): Int = Objects.hash(spanParentStruct, string) + + override fun toString(): String = + when { + spanParentStruct != null -> "Parent{spanParentStruct=$spanParentStruct}" + string != null -> "Parent{string=$string}" + _json != null -> "Parent{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Parent") + } + + companion object { + + /** Span parent properties */ + @JvmStatic + fun ofSpanParentStruct(spanParentStruct: SpanParentStruct) = + Parent(spanParentStruct = spanParentStruct) + + /** The parent's span identifier, created by calling `.export()` on a span */ + @JvmStatic fun ofString(string: String) = Parent(string = string) + } + + /** An interface that defines how to map each variant of [Parent] to a value of type [T]. */ + interface Visitor { + + /** Span parent properties */ + fun visitSpanParentStruct(spanParentStruct: SpanParentStruct): T + + /** The parent's span identifier, created by calling `.export()` on a span */ + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Parent] to a value of type [T]. + * + * An instance of [Parent] 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 Parent: $json") + } + } + + internal class Deserializer : BaseDeserializer(Parent::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Parent { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Parent::class) { + + override fun serialize( + value: Parent, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.spanParentStruct != null -> generator.writeObject(value.spanParentStruct) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Parent") + } + } + } + + /** Span parent properties */ + class SpanParentStruct + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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") + + /** + * @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 = objectType.getRequired("object_type") + + /** + * Include these properties in every span created under this parent + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun propagatedEvent(): Optional = + propagatedEvent.getOptional("propagated_event") + + /** + * Identifiers for the row to to log a subspan under + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun rowIds(): Optional = rowIds.getOptional("row_ids") + + /** + * 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 + + /** + * Returns the raw JSON value of [propagatedEvent]. + * + * Unlike [propagatedEvent], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("propagated_event") + @ExcludeMissing + fun _propagatedEvent(): JsonField = propagatedEvent + + /** + * Returns the raw JSON value of [rowIds]. + * + * Unlike [rowIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SpanParentStruct]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanParentStruct]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var propagatedEvent: JsonField = JsonMissing.of() + private var rowIds: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(spanParentStruct: SpanParentStruct) = apply { + objectId = spanParentStruct.objectId + objectType = spanParentStruct.objectType + propagatedEvent = spanParentStruct.propagatedEvent + rowIds = spanParentStruct.rowIds + additionalProperties = spanParentStruct.additionalProperties.toMutableMap() + } + + /** The id of the container object you are logging 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 } + + fun objectType(objectType: ObjectType) = objectType(JsonField.of(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 { + this.objectType = objectType + } + + /** Include these properties in every span created under this parent */ + fun propagatedEvent(propagatedEvent: PropagatedEvent?) = + propagatedEvent(JsonField.ofNullable(propagatedEvent)) + + /** + * Alias for calling [Builder.propagatedEvent] with `propagatedEvent.orElse(null)`. + */ + fun propagatedEvent(propagatedEvent: Optional) = + propagatedEvent(propagatedEvent.getOrNull()) + + /** + * Sets [Builder.propagatedEvent] to an arbitrary JSON value. + * + * You should usually call [Builder.propagatedEvent] with a well-typed + * [PropagatedEvent] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun propagatedEvent(propagatedEvent: JsonField) = apply { + this.propagatedEvent = propagatedEvent + } + + /** Identifiers for the row to to log a subspan under */ + fun rowIds(rowIds: RowIds?) = rowIds(JsonField.ofNullable(rowIds)) + + /** Alias for calling [Builder.rowIds] with `rowIds.orElse(null)`. */ + fun rowIds(rowIds: Optional) = rowIds(rowIds.getOrNull()) + + /** + * Sets [Builder.rowIds] to an arbitrary JSON value. + * + * You should usually call [Builder.rowIds] with a well-typed [RowIds] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun rowIds(rowIds: JsonField) = apply { this.rowIds = rowIds } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SpanParentStruct]. + * + * 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(): SpanParentStruct = + SpanParentStruct( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + propagatedEvent, + rowIds, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROJECT_LOGS = of("project_logs") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val PLAYGROUND_LOGS = of("playground_logs") + + @JvmStatic fun of(value: String) = ObjectType(JsonField.of(value)) + } + + /** An enum containing [ObjectType]'s known values. */ + enum class Known { + PROJECT_LOGS, + EXPERIMENT, + PLAYGROUND_LOGS, + } + + /** + * An enum containing [ObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROJECT_LOGS, + EXPERIMENT, + PLAYGROUND_LOGS, + /** + * An enum member indicating that [ObjectType] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROJECT_LOGS -> Value.PROJECT_LOGS + EXPERIMENT -> Value.EXPERIMENT + PLAYGROUND_LOGS -> Value.PLAYGROUND_LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + PROJECT_LOGS -> Known.PROJECT_LOGS + EXPERIMENT -> Known.EXPERIMENT + PLAYGROUND_LOGS -> Known.PLAYGROUND_LOGS + else -> throw BraintrustInvalidDataException("Unknown ObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Include these properties in every span created under this parent */ + class PropagatedEvent + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PropagatedEvent]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PropagatedEvent]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(propagatedEvent: PropagatedEvent) = apply { + additionalProperties = propagatedEvent.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 [PropagatedEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PropagatedEvent = + 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 + } + + return other is PropagatedEvent && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PropagatedEvent{additionalProperties=$additionalProperties}" + } + + /** Identifiers for the row to to log a subspan under */ + class RowIds + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The root_span_id of the row + * + * @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 rootSpanId(): String = rootSpanId.getRequired("root_span_id") + + /** + * The span_id of the row + * + * @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 spanId(): String = spanId.getRequired("span_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("root_span_id") + @ExcludeMissing + fun _rootSpanId(): JsonField = rootSpanId + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RowIds]. + * + * The following fields are required: + * ```java + * .id() + * .rootSpanId() + * .spanId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RowIds]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var rootSpanId: JsonField? = null + private var spanId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(rowIds: RowIds) = apply { + id = rowIds.id + rootSpanId = rowIds.rootSpanId + spanId = rowIds.spanId + additionalProperties = rowIds.additionalProperties.toMutableMap() + } + + /** The id of the row */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The root_span_id of the row */ + fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { + this.rootSpanId = rootSpanId + } + + /** The span_id of the row */ + fun spanId(spanId: String) = spanId(JsonField.of(spanId)) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RowIds]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .rootSpanId() + * .spanId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RowIds = + RowIds( + checkRequired("id", id), + checkRequired("rootSpanId", rootSpanId), + checkRequired("spanId", spanId), + 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 + } + + return other is RowIds && + id == other.id && + rootSpanId == other.rootSpanId && + spanId == other.spanId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, rootSpanId, spanId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RowIds{id=$id, rootSpanId=$rootSpanId, spanId=$spanId, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanParentStruct && + objectId == other.objectId && + objectType == other.objectType && + propagatedEvent == other.propagatedEvent && + rowIds == other.rowIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(objectId, objectType, propagatedEvent, rowIds, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SpanParentStruct{objectId=$objectId, objectType=$objectType, propagatedEvent=$propagatedEvent, rowIds=$rowIds, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is EvalCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "EvalCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 old mode 100644 new mode 100755 index c749d389..9753c326 --- 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,780 +6,823 @@ 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.toUnmodifiable +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 com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@JsonDeserialize(builder = Experiment.Builder::class) -@NoAutoDetect class Experiment +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val id: JsonField, - private val projectId: JsonField, private val name: JsonField, - private val description: JsonField, - private val created: JsonField, - private val repoInfo: JsonField, - private val commit: JsonField, + private val projectId: JsonField, + private val public_: JsonField, private val baseExpId: JsonField, - private val deletedAt: JsonField, + private val commit: JsonField, + private val created: JsonField, private val datasetId: JsonField, private val datasetVersion: JsonField, - private val public_: JsonField, - private val userId: JsonField, + private val deletedAt: JsonField, + private val description: JsonField, private val metadata: JsonField, - private val additionalProperties: Map, + private val repoInfo: JsonField, + private val userId: JsonField, + private val additionalProperties: MutableMap, ) { - private var validated: Boolean = false - - private var hashCode: Int = 0 + @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 */ + /** + * Unique identifier for the experiment + * + * @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 id(): String = id.getRequired("id") - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(): String = projectId.getRequired("project_id") - - /** Name of the experiment. Within a project, experiment names are unique */ + /** + * Name of the experiment. Within a project, experiment 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") - /** Textual description of the experiment */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** Date of experiment creation */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) + /** + * Unique identifier for the project that the experiment 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") - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(): Optional = Optional.ofNullable(repoInfo.getNullable("repo_info")) + /** + * 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 or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun public_(): Boolean = public_.getRequired("public") - /** Commit, taken directly from `repo_info.commit` */ - fun commit(): Optional = Optional.ofNullable(commit.getNullable("commit")) + /** + * 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") - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(): Optional = Optional.ofNullable(baseExpId.getNullable("base_exp_id")) + /** + * Commit, taken directly from `repo_info.commit` + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun commit(): Optional = commit.getOptional("commit") - /** Date of experiment deletion, or null if the experiment is still active */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) + /** + * Date of experiment creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") - /** Identifier of the linked dataset, or null if the experiment is not linked to a dataset */ - fun datasetId(): Optional = Optional.ofNullable(datasetId.getNullable("dataset_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 = - Optional.ofNullable(datasetVersion.getNullable("dataset_version")) + fun datasetVersion(): Optional = datasetVersion.getOptional("dataset_version") /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody inside - * or outside the organization + * Date of experiment deletion, or null if the experiment is still active + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). */ - fun public_(): Boolean = public_.getRequired("public") + fun deletedAt(): Optional = deletedAt.getOptional("deleted_at") - /** Identifies the user who created the experiment */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - /** User-controlled metadata about the experiment */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** Unique identifier for the experiment */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId + /** + * 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") - /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") @ExcludeMissing fun _name() = name + /** + * 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") - /** Textual description of the experiment */ - @JsonProperty("description") @ExcludeMissing fun _description() = description + /** + * 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") - /** Date of experiment creation */ - @JsonProperty("created") @ExcludeMissing fun _created() = created + /** + * Identifies the user who created the experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") - /** Metadata about the state of the repo when the experiment was created */ - @JsonProperty("repo_info") @ExcludeMissing fun _repoInfo() = repoInfo + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id - /** Commit, taken directly from `repo_info.commit` */ - @JsonProperty("commit") @ExcludeMissing fun _commit() = commit + /** + * 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 - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") @ExcludeMissing fun _baseExpId() = baseExpId + /** + * 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 - /** Date of experiment deletion, or null if the experiment is still active */ - @JsonProperty("deleted_at") @ExcludeMissing fun _deletedAt() = deletedAt + /** + * 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_ - /** Identifier of the linked dataset, or null if the experiment is not linked to a dataset */ - @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId() = datasetId + /** + * 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 /** - * 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. + * Returns the raw JSON value of [commit]. + * + * Unlike [commit], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("dataset_version") @ExcludeMissing fun _datasetVersion() = datasetVersion + @JsonProperty("commit") @ExcludeMissing fun _commit(): JsonField = commit /** - * 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 [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("public") @ExcludeMissing fun _public_() = public_ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created - /** Identifies the user who created the experiment */ - @JsonProperty("user_id") @ExcludeMissing fun _userId() = userId + /** + * 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 - /** User-controlled metadata about the experiment */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata + /** + * 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 - @JsonAnyGetter + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun _deletedAt(): JsonField = deletedAt - fun validate(): Experiment = apply { - if (!validated) { - id() - projectId() - name() - description() - created() - repoInfo().map { it.validate() } - commit() - baseExpId() - deletedAt() - datasetId() - datasetVersion() - public_() - userId() - metadata().map { it.validate() } - validated = true - } - } + /** + * 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 - fun toBuilder() = Builder().from(this) + /** + * 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 - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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 - return other is Experiment && - this.id == other.id && - this.projectId == other.projectId && - this.name == other.name && - this.description == other.description && - this.created == other.created && - this.repoInfo == other.repoInfo && - this.commit == other.commit && - this.baseExpId == other.baseExpId && - this.deletedAt == other.deletedAt && - this.datasetId == other.datasetId && - this.datasetVersion == other.datasetVersion && - this.public_ == other.public_ && - this.userId == other.userId && - this.metadata == other.metadata && - this.additionalProperties == other.additionalProperties - } + /** + * 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 - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - projectId, - name, - description, - created, - repoInfo, - commit, - baseExpId, - deletedAt, - datasetId, - datasetVersion, - public_, - userId, - metadata, - additionalProperties, - ) - } - return hashCode + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - override fun toString() = - "Experiment{id=$id, projectId=$projectId, name=$name, description=$description, created=$created, repoInfo=$repoInfo, commit=$commit, baseExpId=$baseExpId, deletedAt=$deletedAt, datasetId=$datasetId, datasetVersion=$datasetVersion, public_=$public_, userId=$userId, metadata=$metadata, additionalProperties=$additionalProperties}" + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [Experiment]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .public_() + * ``` + */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Experiment]. */ + class Builder internal constructor() { - private var id: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var description: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var repoInfo: JsonField = JsonMissing.of() - private var commit: JsonField = JsonMissing.of() + private var id: JsonField? = null + private var name: JsonField? = null + private var projectId: JsonField? = null + private var public_: JsonField? = null private var baseExpId: JsonField = JsonMissing.of() - private var deletedAt: JsonField = JsonMissing.of() + private var commit: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() private var datasetId: JsonField = JsonMissing.of() private var datasetVersion: JsonField = JsonMissing.of() - private var public_: JsonField = JsonMissing.of() - private var userId: JsonField = JsonMissing.of() + private var deletedAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() private var metadata: JsonField = JsonMissing.of() + private var repoInfo: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(experiment: Experiment) = apply { - this.id = experiment.id - this.projectId = experiment.projectId - this.name = experiment.name - this.description = experiment.description - this.created = experiment.created - this.repoInfo = experiment.repoInfo - this.commit = experiment.commit - this.baseExpId = experiment.baseExpId - this.deletedAt = experiment.deletedAt - this.datasetId = experiment.datasetId - this.datasetVersion = experiment.datasetVersion - this.public_ = experiment.public_ - this.userId = experiment.userId - this.metadata = experiment.metadata - additionalProperties(experiment.additionalProperties) + id = experiment.id + name = experiment.name + projectId = experiment.projectId + public_ = experiment.public_ + baseExpId = experiment.baseExpId + commit = experiment.commit + created = experiment.created + datasetId = experiment.datasetId + datasetVersion = experiment.datasetVersion + deletedAt = experiment.deletedAt + description = experiment.description + metadata = experiment.metadata + repoInfo = experiment.repoInfo + userId = experiment.userId + additionalProperties = experiment.additionalProperties.toMutableMap() } /** Unique identifier for the experiment */ fun id(id: String) = id(JsonField.of(id)) - /** Unique identifier for the experiment */ - @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } /** Name of the experiment. Within a project, experiment names are unique */ fun name(name: String) = name(JsonField.of(name)) - /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") - @ExcludeMissing + /** + * 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 experiment */ - fun description(description: String) = description(JsonField.of(description)) + /** Unique identifier for the project that the experiment belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - /** Textual description of the experiment */ - @JsonProperty("description") - @ExcludeMissing - fun description(description: JsonField) = apply { this.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 } - /** Date of experiment creation */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) + /** + * 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.of(public_)) - /** Date of experiment creation */ - @JsonProperty("created") - @ExcludeMissing - fun created(created: JsonField) = apply { this.created = created } + /** + * 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.of(repoInfo)) + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = baseExpId(JsonField.ofNullable(baseExpId)) - /** Metadata about the state of the repo when the experiment was created */ - @JsonProperty("repo_info") - @ExcludeMissing - fun repoInfo(repoInfo: JsonField) = apply { this.repoInfo = repoInfo } + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) - /** Commit, taken directly from `repo_info.commit` */ - fun commit(commit: String) = commit(JsonField.of(commit)) + /** + * 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 } /** Commit, taken directly from `repo_info.commit` */ - @JsonProperty("commit") - @ExcludeMissing - fun commit(commit: JsonField) = apply { this.commit = commit } + fun commit(commit: String?) = commit(JsonField.ofNullable(commit)) - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(baseExpId: String) = baseExpId(JsonField.of(baseExpId)) + /** Alias for calling [Builder.commit] with `commit.orElse(null)`. */ + fun commit(commit: Optional) = commit(commit.getOrNull()) - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") - @ExcludeMissing - fun baseExpId(baseExpId: JsonField) = apply { this.baseExpId = baseExpId } + /** + * Sets [Builder.commit] to an arbitrary JSON value. + * + * You should usually call [Builder.commit] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun commit(commit: JsonField) = apply { this.commit = commit } - /** Date of experiment deletion, or null if the experiment is still active */ - fun deletedAt(deletedAt: OffsetDateTime) = deletedAt(JsonField.of(deletedAt)) + /** Date of experiment creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) - /** Date of experiment deletion, or null if the experiment is still active */ - @JsonProperty("deleted_at") - @ExcludeMissing - fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun datasetId(datasetId: String) = datasetId(JsonField.of(datasetId)) + fun created(created: JsonField) = apply { this.created = created } /** * Identifier of the linked dataset, or null if the experiment is not linked to a dataset */ - @JsonProperty("dataset_id") - @ExcludeMissing + 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.of(datasetVersion)) + fun datasetVersion(datasetVersion: String?) = + datasetVersion(JsonField.ofNullable(datasetVersion)) + + /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ + fun datasetVersion(datasetVersion: Optional) = + datasetVersion(datasetVersion.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. + * 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. */ - @JsonProperty("dataset_version") - @ExcludeMissing fun datasetVersion(datasetVersion: JsonField) = apply { this.datasetVersion = datasetVersion } + /** Date of experiment deletion, or null if the experiment is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization + * 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 public_(public_: Boolean) = public_(JsonField.of(public_)) + fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } + + /** 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()) /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization + * 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. */ - @JsonProperty("public") - @ExcludeMissing - fun public_(public_: JsonField) = apply { this.public_ = public_ } + fun description(description: JsonField) = apply { this.description = description } - /** Identifies the user who created the experiment */ - fun userId(userId: String) = userId(JsonField.of(userId)) + /** 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 } + + /** 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 } /** Identifies the user who created the experiment */ - @JsonProperty("user_id") - @ExcludeMissing - fun userId(userId: JsonField) = apply { this.userId = userId } + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) - /** User-controlled metadata about the experiment */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) - /** User-controlled metadata about the experiment */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Experiment]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .public_() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Experiment = Experiment( - id, - projectId, - name, - description, - created, - repoInfo, - commit, + checkRequired("id", id), + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("public_", public_), baseExpId, - deletedAt, + commit, + created, datasetId, datasetVersion, - public_, - userId, + deletedAt, + description, metadata, - additionalProperties.toUnmodifiable(), + repoInfo, + userId, + 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 */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect class Metadata + @JsonCreator private constructor( - private val additionalProperties: Map, + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map ) { - private var validated: Boolean = false - - private var hashCode: Int = 0 - @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - fun toBuilder() = Builder().from(this) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Metadata]. */ + class Builder internal constructor() { private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) + additionalProperties = metadata.additionalProperties.toMutableMap() } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** Metadata about the state of the repo when the experiment was created */ - @JsonDeserialize(builder = RepoInfo.Builder::class) - @NoAutoDetect - class RepoInfo - private constructor( - private val commit: JsonField, - private val branch: JsonField, - private val tag: JsonField, - private val dirty: JsonField, - private val authorName: JsonField, - private val authorEmail: JsonField, - private val commitMessage: JsonField, - private val commitTime: JsonField, - private val gitDiff: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** SHA of most recent commit */ - fun commit(): Optional = Optional.ofNullable(commit.getNullable("commit")) - - /** Name of the branch the most recent commit belongs to */ - fun branch(): Optional = Optional.ofNullable(branch.getNullable("branch")) + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - /** Name of the tag on the most recent commit */ - fun tag(): Optional = Optional.ofNullable(tag.getNullable("tag")) - - /** Whether or not the repo had uncommitted changes when snapshotted */ - fun dirty(): Optional = Optional.ofNullable(dirty.getNullable("dirty")) - - /** Name of the author of the most recent commit */ - fun authorName(): Optional = - Optional.ofNullable(authorName.getNullable("author_name")) - - /** Email of the author of the most recent commit */ - fun authorEmail(): Optional = - Optional.ofNullable(authorEmail.getNullable("author_email")) - - /** Most recent commit message */ - fun commitMessage(): Optional = - Optional.ofNullable(commitMessage.getNullable("commit_message")) - - /** Time of the most recent commit */ - fun commitTime(): Optional = - Optional.ofNullable(commitTime.getNullable("commit_time")) - - /** - * If the repo was dirty when run, this includes the diff between the current state of the - * repo and the most recent commit. - */ - fun gitDiff(): Optional = Optional.ofNullable(gitDiff.getNullable("git_diff")) - - /** SHA of most recent commit */ - @JsonProperty("commit") @ExcludeMissing fun _commit() = commit - - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") @ExcludeMissing fun _branch() = branch - - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") @ExcludeMissing fun _tag() = tag + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") @ExcludeMissing fun _dirty() = dirty + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") @ExcludeMissing fun _authorName() = authorName + private var validated: Boolean = false - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") @ExcludeMissing fun _authorEmail() = authorEmail + fun validate(): Metadata = apply { + if (validated) { + return@apply + } - /** Most recent commit message */ - @JsonProperty("commit_message") @ExcludeMissing fun _commitMessage() = commitMessage + validated = true + } - /** Time of the most recent commit */ - @JsonProperty("commit_time") @ExcludeMissing fun _commitTime() = commitTime + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * If the repo was dirty when run, this includes the diff between the current state of the - * repo and the most recent commit. + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. */ - @JsonProperty("git_diff") @ExcludeMissing fun _gitDiff() = gitDiff - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): RepoInfo = apply { - if (!validated) { - commit() - branch() - tag() - dirty() - authorName() - authorEmail() - commitMessage() - commitTime() - gitDiff() - validated = true - } - } - - fun toBuilder() = Builder().from(this) + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } override fun equals(other: Any?): Boolean { if (this === other) { return true } - return other is RepoInfo && - this.commit == other.commit && - this.branch == other.branch && - this.tag == other.tag && - this.dirty == other.dirty && - this.authorName == other.authorName && - this.authorEmail == other.authorEmail && - this.commitMessage == other.commitMessage && - this.commitTime == other.commitTime && - this.gitDiff == other.gitDiff && - this.additionalProperties == other.additionalProperties + return other is Metadata && additionalProperties == other.additionalProperties } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties, - ) - } - return hashCode - } + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } - override fun toString() = - "RepoInfo{commit=$commit, branch=$branch, tag=$tag, dirty=$dirty, authorName=$authorName, authorEmail=$authorEmail, commitMessage=$commitMessage, commitTime=$commitTime, gitDiff=$gitDiff, additionalProperties=$additionalProperties}" + override fun hashCode(): Int = hashCode - companion object { + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - class Builder { - - private var commit: JsonField = JsonMissing.of() - private var branch: JsonField = JsonMissing.of() - private var tag: JsonField = JsonMissing.of() - private var dirty: JsonField = JsonMissing.of() - private var authorName: JsonField = JsonMissing.of() - private var authorEmail: JsonField = JsonMissing.of() - private var commitMessage: JsonField = JsonMissing.of() - private var commitTime: JsonField = JsonMissing.of() - private var gitDiff: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(repoInfo: RepoInfo) = apply { - this.commit = repoInfo.commit - this.branch = repoInfo.branch - this.tag = repoInfo.tag - this.dirty = repoInfo.dirty - this.authorName = repoInfo.authorName - this.authorEmail = repoInfo.authorEmail - this.commitMessage = repoInfo.commitMessage - this.commitTime = repoInfo.commitTime - this.gitDiff = repoInfo.gitDiff - additionalProperties(repoInfo.additionalProperties) - } - - /** SHA of most recent commit */ - fun commit(commit: String) = commit(JsonField.of(commit)) - - /** SHA of most recent commit */ - @JsonProperty("commit") - @ExcludeMissing - fun commit(commit: JsonField) = apply { this.commit = commit } - - /** Name of the branch the most recent commit belongs to */ - fun branch(branch: String) = branch(JsonField.of(branch)) - - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") - @ExcludeMissing - fun branch(branch: JsonField) = apply { this.branch = branch } - - /** Name of the tag on the most recent commit */ - fun tag(tag: String) = tag(JsonField.of(tag)) - - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") - @ExcludeMissing - fun tag(tag: JsonField) = apply { this.tag = tag } - - /** Whether or not the repo had uncommitted changes when snapshotted */ - fun dirty(dirty: Boolean) = dirty(JsonField.of(dirty)) - - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") - @ExcludeMissing - fun dirty(dirty: JsonField) = apply { this.dirty = dirty } - - /** Name of the author of the most recent commit */ - fun authorName(authorName: String) = authorName(JsonField.of(authorName)) - - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") - @ExcludeMissing - fun authorName(authorName: JsonField) = apply { this.authorName = authorName } - - /** Email of the author of the most recent commit */ - fun authorEmail(authorEmail: String) = authorEmail(JsonField.of(authorEmail)) - - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") - @ExcludeMissing - fun authorEmail(authorEmail: JsonField) = apply { - this.authorEmail = authorEmail - } - - /** Most recent commit message */ - fun commitMessage(commitMessage: String) = commitMessage(JsonField.of(commitMessage)) - - /** Most recent commit message */ - @JsonProperty("commit_message") - @ExcludeMissing - fun commitMessage(commitMessage: JsonField) = apply { - this.commitMessage = commitMessage - } - - /** Time of the most recent commit */ - fun commitTime(commitTime: String) = commitTime(JsonField.of(commitTime)) - - /** Time of the most recent commit */ - @JsonProperty("commit_time") - @ExcludeMissing - fun commitTime(commitTime: JsonField) = apply { this.commitTime = commitTime } - - /** - * If the repo was dirty when run, this includes the diff between the current state of - * the repo and the most recent commit. - */ - fun gitDiff(gitDiff: String) = gitDiff(JsonField.of(gitDiff)) - - /** - * If the repo was dirty when run, this includes the diff between the current state of - * the repo and the most recent commit. - */ - @JsonProperty("git_diff") - @ExcludeMissing - fun gitDiff(gitDiff: JsonField) = apply { this.gitDiff = gitDiff } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + return other is Experiment && + id == other.id && + name == other.name && + projectId == other.projectId && + public_ == other.public_ && + baseExpId == other.baseExpId && + commit == other.commit && + created == other.created && + datasetId == other.datasetId && + datasetVersion == other.datasetVersion && + deletedAt == other.deletedAt && + description == other.description && + metadata == other.metadata && + repoInfo == other.repoInfo && + userId == other.userId && + additionalProperties == other.additionalProperties + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + projectId, + public_, + baseExpId, + commit, + created, + datasetId, + datasetVersion, + deletedAt, + description, + metadata, + repoInfo, + userId, + additionalProperties, + ) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + override fun hashCode(): Int = hashCode - fun build(): RepoInfo = - RepoInfo( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties.toUnmodifiable(), - ) - } - } + override fun toString() = + "Experiment{id=$id, name=$name, projectId=$projectId, public_=$public_, baseExpId=$baseExpId, commit=$commit, created=$created, datasetId=$datasetId, datasetVersion=$datasetVersion, deletedAt=$deletedAt, description=$description, metadata=$metadata, repoInfo=$repoInfo, userId=$userId, additionalProperties=$additionalProperties}" } 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 old mode 100644 new mode 100755 index 906e8ab3..1566b32d --- 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 @@ -3,722 +3,1257 @@ 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.toUnmodifiable -import com.braintrustdata.api.models.* +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.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 com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Create a new experiment. If there is an existing experiment in the project with the same name as + * the one specified in the request, will return the existing experiment unmodified + */ class ExperimentCreateParams -constructor( - private val projectId: String, - private val baseExpId: String?, - private val datasetId: String?, - private val datasetVersion: String?, - private val description: String?, - private val metadata: Metadata?, - private val name: String?, - private val public_: Boolean?, - private val repoInfo: RepoInfo?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Unique identifier for the project that the experiment 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 = body.projectId() + + /** + * 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 = body.baseExpId() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun datasetVersion(): Optional = body.datasetVersion() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun ensureNew(): Optional = body.ensureNew() + + /** + * 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 = body.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 = body.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 = body.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 = body.repoInfo() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [baseExpId]. + * + * Unlike [baseExpId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _baseExpId(): JsonField = body._baseExpId() + + /** + * Returns the raw JSON value of [datasetId]. + * + * Unlike [datasetId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _datasetId(): JsonField = body._datasetId() + + /** + * Returns the raw JSON value of [datasetVersion]. + * + * Unlike [datasetVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _datasetVersion(): JsonField = body._datasetVersion() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [ensureNew]. + * + * Unlike [ensureNew], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _ensureNew(): JsonField = body._ensureNew() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [public_]. + * + * Unlike [public_], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _public_(): JsonField = body._public_() + + /** + * Returns the raw JSON value of [repoInfo]. + * + * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _repoInfo(): JsonField = body._repoInfo() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun projectId(): String = projectId + fun toBuilder() = Builder().from(this) - fun baseExpId(): Optional = Optional.ofNullable(baseExpId) + companion object { - fun datasetId(): Optional = Optional.ofNullable(datasetId) + /** + * Returns a mutable builder for constructing an instance of [ExperimentCreateParams]. + * + * The following fields are required: + * ```java + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - fun datasetVersion(): Optional = Optional.ofNullable(datasetVersion) + /** A builder for [ExperimentCreateParams]. */ + class Builder internal constructor() { - fun description(): Optional = Optional.ofNullable(description) + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - fun metadata(): Optional = Optional.ofNullable(metadata) + @JvmSynthetic + internal fun from(experimentCreateParams: ExperimentCreateParams) = apply { + body = experimentCreateParams.body.toBuilder() + additionalHeaders = experimentCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentCreateParams.additionalQueryParams.toBuilder() + } - fun name(): Optional = Optional.ofNullable(name) + /** + * 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: + * - [projectId] + * - [baseExpId] + * - [datasetId] + * - [datasetVersion] + * - [description] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } - fun public_(): Optional = Optional.ofNullable(public_) + /** Unique identifier for the project that the experiment belongs under */ + fun projectId(projectId: String) = apply { body.projectId(projectId) } - fun repoInfo(): Optional = Optional.ofNullable(repoInfo) + /** + * 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) } - @JvmSynthetic - internal fun getBody(): ExperimentCreateBody { - return ExperimentCreateBody( - projectId, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalBodyProperties, - ) - } + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = apply { body.baseExpId(baseExpId) } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - @JsonDeserialize(builder = ExperimentCreateBody.Builder::class) - @NoAutoDetect - class ExperimentCreateBody - internal constructor( - private val projectId: String?, - private val baseExpId: String?, - private val datasetId: String?, - private val datasetVersion: String?, - private val description: String?, - private val metadata: Metadata?, - private val name: String?, - private val public_: Boolean?, - private val repoInfo: RepoInfo?, - private val additionalProperties: Map, - ) { + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) - private var hashCode: Int = 0 + /** + * 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) } - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") fun projectId(): String? = projectId + /** + * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + */ + fun datasetId(datasetId: String?) = apply { body.datasetId(datasetId) } - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") fun baseExpId(): String? = baseExpId + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + * 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. */ - @JsonProperty("dataset_id") fun datasetId(): String? = datasetId + 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. */ - @JsonProperty("dataset_version") fun datasetVersion(): String? = datasetVersion + 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 */ - @JsonProperty("description") fun description(): String? = description + 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) } + + /** + * 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?) = apply { body.ensureNew(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 { body.ensureNew(ensureNew) } /** User-controlled metadata about the experiment */ - @JsonProperty("metadata") fun metadata(): Metadata? = 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) } /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") fun name(): String? = name + 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 */ - @JsonProperty("public") fun public_(): Boolean? = public_ + 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 */ - @JsonProperty("repo_info") fun repoInfo(): RepoInfo? = repoInfo + fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - fun toBuilder() = Builder().from(this) + /** + * 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) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - return other is ExperimentCreateBody && - this.projectId == other.projectId && - this.baseExpId == other.baseExpId && - this.datasetId == other.datasetId && - this.datasetVersion == other.datasetVersion && - this.description == other.description && - this.metadata == other.metadata && - this.name == other.name && - this.public_ == other.public_ && - this.repoInfo == other.repoInfo && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - projectId, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalProperties, - ) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - return hashCode + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - override fun toString() = - "ExperimentCreateBody{projectId=$projectId, baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalProperties=$additionalProperties}" + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - class Builder { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var projectId: String? = null - private var baseExpId: String? = null - private var datasetId: String? = null - private var datasetVersion: String? = null - private var description: String? = null - private var metadata: Metadata? = null - private var name: String? = null - private var public_: Boolean? = null - private var repoInfo: RepoInfo? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(experimentCreateBody: ExperimentCreateBody) = apply { - this.projectId = experimentCreateBody.projectId - this.baseExpId = experimentCreateBody.baseExpId - this.datasetId = experimentCreateBody.datasetId - this.datasetVersion = experimentCreateBody.datasetVersion - this.description = experimentCreateBody.description - this.metadata = experimentCreateBody.metadata - this.name = experimentCreateBody.name - this.public_ = experimentCreateBody.public_ - this.repoInfo = experimentCreateBody.repoInfo - additionalProperties(experimentCreateBody.additionalProperties) - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") - fun projectId(projectId: String) = apply { this.projectId = projectId } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") - fun baseExpId(baseExpId: String) = apply { this.baseExpId = baseExpId } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a - * dataset - */ - @JsonProperty("dataset_id") - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** - * 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. - */ - @JsonProperty("dataset_version") - fun datasetVersion(datasetVersion: String) = apply { - this.datasetVersion = datasetVersion - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Textual description of the experiment */ - @JsonProperty("description") - fun description(description: String) = apply { this.description = description } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** User-controlled metadata about the experiment */ - @JsonProperty("metadata") - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - */ - @JsonProperty("public") fun public_(public_: Boolean) = apply { this.public_ = public_ } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** Metadata about the state of the repo when the experiment was created */ - @JsonProperty("repo_info") - fun repoInfo(repoInfo: RepoInfo) = apply { this.repoInfo = repoInfo } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun build(): ExperimentCreateBody = - ExperimentCreateBody( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalProperties.toUnmodifiable(), - ) + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - } - fun _additionalQueryParams(): Map> = additionalQueryParams + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - fun _additionalHeaders(): Map> = additionalHeaders + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun _additionalBodyProperties(): Map = additionalBodyProperties + 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 other is ExperimentCreateParams && - this.projectId == other.projectId && - this.baseExpId == other.baseExpId && - this.datasetId == other.datasetId && - this.datasetVersion == other.datasetVersion && - this.description == other.description && - this.metadata == other.metadata && - this.name == other.name && - this.public_ == other.public_ && - this.repoInfo == other.repoInfo && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties + /** + * 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(), + ) } - override fun hashCode(): Int { - return Objects.hash( + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, + mutableMapOf(), ) - } - - override fun toString() = - "ExperimentCreateParams{projectId=$projectId, baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" - - fun toBuilder() = Builder().from(this) - companion object { - - @JvmStatic fun builder() = Builder() - } - - @NoAutoDetect - class Builder { - - private var projectId: String? = null - private var baseExpId: String? = null - private var datasetId: String? = null - private var datasetVersion: String? = null - private var description: String? = null - private var metadata: Metadata? = null - private var name: String? = null - private var public_: Boolean? = null - private var repoInfo: RepoInfo? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentCreateParams: ExperimentCreateParams) = apply { - this.projectId = experimentCreateParams.projectId - this.baseExpId = experimentCreateParams.baseExpId - this.datasetId = experimentCreateParams.datasetId - this.datasetVersion = experimentCreateParams.datasetVersion - this.description = experimentCreateParams.description - this.metadata = experimentCreateParams.metadata - this.name = experimentCreateParams.name - this.public_ = experimentCreateParams.public_ - this.repoInfo = experimentCreateParams.repoInfo - additionalQueryParams(experimentCreateParams.additionalQueryParams) - additionalHeaders(experimentCreateParams.additionalHeaders) - additionalBodyProperties(experimentCreateParams.additionalBodyProperties) - } - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + /** + * Unique identifier for the project that the experiment 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") - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(baseExpId: String) = apply { this.baseExpId = baseExpId } + /** + * 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(datasetId: String) = apply { this.datasetId = datasetId } + 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(datasetVersion: String) = apply { this.datasetVersion = datasetVersion } + fun datasetVersion(): Optional = datasetVersion.getOptional("dataset_version") - /** Textual description of the experiment */ - fun description(description: String) = apply { this.description = description } + /** + * 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 */ - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } + /** + * 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 ensureNew(): Optional = ensureNew.getOptional("ensure_new") - /** Name of the experiment. Within a project, experiment names are unique */ - fun name(name: String) = apply { this.name = name } + /** + * 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_(public_: Boolean) = apply { this.public_ = public_ } + fun public_(): Optional = public_.getOptional("public") - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo) = apply { this.repoInfo = repoInfo } + /** + * 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 additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } + /** + * 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 - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + /** + * 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 - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + /** + * 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 - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + /** + * 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 - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + /** + * 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 - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + /** + * Returns the raw JSON value of [ensureNew]. + * + * Unlike [ensureNew], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("ensure_new") @ExcludeMissing fun _ensureNew(): JsonField = ensureNew - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } + /** + * 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 - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + /** + * 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 - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } + /** + * 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_ - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + /** + * 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 - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .projectId() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(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() } - fun build(): ExperimentCreateParams = - ExperimentCreateParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } + /** Unique identifier for the project that the experiment belongs under */ + fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - /** User-controlled metadata about the experiment */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { + /** + * 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 } - private var hashCode: Int = 0 + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = baseExpId(JsonField.ofNullable(baseExpId)) - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) - fun toBuilder() = Builder().from(this) + /** + * 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 } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + /** + * 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 } - return other is Metadata && this.additionalProperties == other.additionalProperties - } + /** 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()) - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) + /** + * 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 } - return hashCode - } - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + /** + * 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)) - companion object { + /** + * Alias for [Builder.ensureNew]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun ensureNew(ensureNew: Boolean) = ensureNew(ensureNew as Boolean?) - @JvmStatic fun builder() = Builder() - } + /** Alias for calling [Builder.ensureNew] with `ensureNew.orElse(null)`. */ + fun ensureNew(ensureNew: Optional) = ensureNew(ensureNew.getOrNull()) - class Builder { + /** + * 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 } - private var additionalProperties: MutableMap = mutableMapOf() + /** User-controlled metadata about the experiment */ + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } + /** 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() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** Metadata about the state of the repo when the experiment was created */ - @JsonDeserialize(builder = RepoInfo.Builder::class) - @NoAutoDetect - class RepoInfo - private constructor( - private val commit: String?, - private val branch: String?, - private val tag: String?, - private val dirty: Boolean?, - private val authorName: String?, - private val authorEmail: String?, - private val commitMessage: String?, - private val commitTime: String?, - private val gitDiff: String?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** SHA of most recent commit */ - @JsonProperty("commit") fun commit(): String? = commit + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") fun branch(): String? = branch - - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") fun tag(): String? = tag + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") fun dirty(): Boolean? = dirty + /** + * 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(), + ) + } - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") fun authorName(): String? = authorName + private var validated: Boolean = false - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") fun authorEmail(): String? = authorEmail + fun validate(): Body = apply { + if (validated) { + return@apply + } - /** Most recent commit message */ - @JsonProperty("commit_message") fun commitMessage(): String? = commitMessage + projectId() + baseExpId() + datasetId() + datasetVersion() + description() + ensureNew() + metadata().ifPresent { it.validate() } + name() + public_() + repoInfo().ifPresent { it.validate() } + validated = true + } - /** Time of the most recent commit */ - @JsonProperty("commit_time") fun commitTime(): String? = commitTime + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * If the repo was dirty when run, this includes the diff between the current state of the - * repo and the most recent commit. + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. */ - @JsonProperty("git_diff") fun gitDiff(): String? = gitDiff - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) + @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) override fun equals(other: Any?): Boolean { if (this === other) { return true } - return other is RepoInfo && - this.commit == other.commit && - this.branch == other.branch && - this.tag == other.tag && - this.dirty == other.dirty && - this.authorName == other.authorName && - this.authorEmail == other.authorEmail && - this.commitMessage == other.commitMessage && - this.commitTime == other.commitTime && - this.gitDiff == other.gitDiff && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties, - ) - } - return hashCode + return 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + projectId, + baseExpId, + datasetId, + datasetVersion, + description, + ensureNew, + metadata, + name, + public_, + repoInfo, + additionalProperties, + ) } + override fun hashCode(): Int = hashCode + override fun toString() = - "RepoInfo{commit=$commit, branch=$branch, tag=$tag, dirty=$dirty, authorName=$authorName, authorEmail=$authorEmail, commitMessage=$commitMessage, commitTime=$commitTime, gitDiff=$gitDiff, additionalProperties=$additionalProperties}" + "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 */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Metadata]. */ + class Builder internal constructor() { - private var commit: String? = null - private var branch: String? = null - private var tag: String? = null - private var dirty: Boolean? = null - private var authorName: String? = null - private var authorEmail: String? = null - private var commitMessage: String? = null - private var commitTime: String? = null - private var gitDiff: String? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(repoInfo: RepoInfo) = apply { - this.commit = repoInfo.commit - this.branch = repoInfo.branch - this.tag = repoInfo.tag - this.dirty = repoInfo.dirty - this.authorName = repoInfo.authorName - this.authorEmail = repoInfo.authorEmail - this.commitMessage = repoInfo.commitMessage - this.commitTime = repoInfo.commitTime - this.gitDiff = repoInfo.gitDiff - additionalProperties(repoInfo.additionalProperties) + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() } - /** SHA of most recent commit */ - @JsonProperty("commit") fun commit(commit: String) = apply { this.commit = commit } - - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") fun branch(branch: String) = apply { this.branch = branch } - - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") fun tag(tag: String) = apply { this.tag = tag } - - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") fun dirty(dirty: Boolean) = apply { this.dirty = dirty } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") - fun authorName(authorName: String) = apply { this.authorName = authorName } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") - fun authorEmail(authorEmail: String) = apply { this.authorEmail = authorEmail } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - /** Most recent commit message */ - @JsonProperty("commit_message") - fun commitMessage(commitMessage: String) = apply { this.commitMessage = commitMessage } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - /** Time of the most recent commit */ - @JsonProperty("commit_time") - fun commitTime(commitTime: String) = apply { this.commitTime = commitTime } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } /** - * If the repo was dirty when run, this includes the diff between the current state of - * the repo and the most recent commit. + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. */ - @JsonProperty("git_diff") - fun gitDiff(gitDiff: String) = apply { this.gitDiff = gitDiff } + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) + /** + * Returns 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 } - fun build(): RepoInfo = - RepoInfo( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties.toUnmodifiable(), - ) + return other is Metadata && additionalProperties == other.additionalProperties } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExperimentCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ExperimentCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index e3e57b22..20855f56 --- 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,141 +3,173 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Delete an experiment object by its id */ class ExperimentDeleteParams -constructor( - private val experimentId: String, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, +private constructor( + private val experimentId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, -) { +) : Params { - fun experimentId(): String = experimentId - - @JvmSynthetic - internal fun getBody(): Optional> { - return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentDeleteParams && - this.experimentId == other.experimentId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - override fun hashCode(): Int { - return Objects.hash( - experimentId, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "ExperimentDeleteParams{experimentId=$experimentId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ExperimentDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ExperimentDeleteParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ExperimentDeleteParams]. */ + class Builder internal constructor() { private var experimentId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(experimentDeleteParams: ExperimentDeleteParams) = apply { - this.experimentId = experimentDeleteParams.experimentId - additionalQueryParams(experimentDeleteParams.additionalQueryParams) - additionalHeaders(experimentDeleteParams.additionalHeaders) - additionalBodyProperties(experimentDeleteParams.additionalBodyProperties) + experimentId = experimentDeleteParams.experimentId + additionalHeaders = experimentDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + experimentDeleteParams.additionalBodyProperties.toMutableMap() } /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(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 putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + putAllAdditionalBodyProperties(additionalBodyProperties) } fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + additionalBodyProperties.put(key, value) } fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = @@ -145,12 +177,61 @@ constructor( this.additionalBodyProperties.putAll(additionalBodyProperties) } + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [ExperimentDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ExperimentDeleteParams = ExperimentDeleteParams( - checkNotNull(experimentId) { "`experimentId` is required but was not set" }, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), + experimentId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), ) } + + 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 + } + + return other is ExperimentDeleteParams && + experimentId == other.experimentId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash( + experimentId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) + + override fun toString() = + "ExperimentDeleteParams{experimentId=$experimentId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } 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 new file mode 100755 index 00000000..a62525d4 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentEvent.kt @@ -0,0 +1,1957 @@ +// 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.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ExperimentEvent +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The transaction id of an event is unique to the network operation that processed the event + * insertion. Transaction ids are monotonically increasing over time and can be used to retrieve + * a versioned snapshot of the experiment (see the `version` parameter) + * + * @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 _xactId(): String = _xactId.getRequired("_xact_id") + + /** + * The timestamp the experiment event was created + * + * @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 created(): OffsetDateTime = created.getRequired("created") + + /** + * Unique identifier for the experiment + * + * @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 experimentId(): String = experimentId.getRequired("experiment_id") + + /** + * Unique identifier for the project that the experiment 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 unique identifier for the trace this experiment event belongs 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 rootSpanId(): String = rootSpanId.getRequired("root_span_id") + + /** + * A unique identifier used to link different experiment events together as part of a full + * trace. See the [tracing guide](https://www.braintrust.dev/docs/guides/tracing) for full + * details on tracing + * + * @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 spanId(): String = spanId.getRequired("span_id") + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun context(): Optional = context.getOptional("context") + + /** The error that occurred, if any. */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does not + * compare `output` to `expected` for you, since there are so many different ways to do that + * correctly. Instead, these values are just used to help you navigate your experiments while + * digging into analyses. However, we may later use these values to re-score outputs or + * fine-tune your models + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** + * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). + * Later on, Braintrust will use the `input` to know whether two test cases are the same between + * experiments, so they should not contain experiment-specific state. A simple rule of thumb is + * that if you run the same experiment twice, the `input` should be identical + */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonValue = input + + /** + * Whether this span is a root span + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isRoot(): Optional = isRoot.getOptional("is_root") + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + * + * @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") + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * experiment event. Use "start" and "end" to track the time span over which the experiment + * event was produced + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metrics(): Optional = metrics.getOptional("metrics") + + /** + * Indicates the event was copied from another object. + * + * @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 output of your application, including post-processing (an arbitrary, JSON serializable + * object), that allows you to determine whether the result is correct or not. For example, in + * an app that generates SQL queries, the `output` should be the _result_ of the SQL query + * generated by the model, not the query itself, because there may be multiple valid queries + * that answer a single question + */ + @JsonProperty("output") @ExcludeMissing fun _output(): JsonValue = output + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare experiments + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scores(): Optional = scores.getOptional("scores") + + /** + * Human-identifying attributes of the span, such as name, type, etc. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 + * span of a trace, and should most often contain just one parent element for subspans + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanParents(): Optional> = spanParents.getOptional("span_parents") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_xactId]. + * + * Unlike [_xactId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_xact_id") @ExcludeMissing fun __xactId(): JsonField = _xactId + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [experimentId]. + * + * Unlike [experimentId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("experiment_id") + @ExcludeMissing + fun _experimentId(): JsonField = experimentId + + /** + * 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 [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId(): JsonField = rootSpanId + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + + /** + * Returns the raw JSON value of [context]. + * + * Unlike [context], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("context") @ExcludeMissing fun _context(): JsonField = context + + /** + * Returns the raw JSON value of [isRoot]. + * + * Unlike [isRoot], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("is_root") @ExcludeMissing fun _isRoot(): JsonField = isRoot + + /** + * 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 [metrics]. + * + * Unlike [metrics], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metrics") @ExcludeMissing fun _metrics(): JsonField = metrics + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [spanAttributes]. + * + * Unlike [spanAttributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_attributes") + @ExcludeMissing + fun _spanAttributes(): JsonField = spanAttributes + + /** + * Returns the raw JSON value of [spanParents]. + * + * Unlike [spanParents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_parents") + @ExcludeMissing + fun _spanParents(): JsonField> = spanParents + + /** + * 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 [ExperimentEvent]. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .created() + * .experimentId() + * .projectId() + * .rootSpanId() + * .spanId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExperimentEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var _xactId: JsonField? = null + private var created: JsonField? = null + private var experimentId: JsonField? = null + private var projectId: JsonField? = null + private var rootSpanId: JsonField? = null + private var spanId: JsonField? = null + private var context: JsonField = JsonMissing.of() + private var error: JsonValue = JsonMissing.of() + private var expected: JsonValue = JsonMissing.of() + private var input: JsonValue = JsonMissing.of() + private var isRoot: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var metrics: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var output: JsonValue = JsonMissing.of() + private var scores: JsonField = JsonMissing.of() + private var spanAttributes: JsonField = JsonMissing.of() + private var spanParents: JsonField>? = null + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(experimentEvent: ExperimentEvent) = apply { + id = experimentEvent.id + _xactId = experimentEvent._xactId + created = experimentEvent.created + experimentId = experimentEvent.experimentId + projectId = experimentEvent.projectId + rootSpanId = experimentEvent.rootSpanId + spanId = experimentEvent.spanId + context = experimentEvent.context + error = experimentEvent.error + expected = experimentEvent.expected + input = experimentEvent.input + isRoot = experimentEvent.isRoot + metadata = experimentEvent.metadata + metrics = experimentEvent.metrics + origin = experimentEvent.origin + output = experimentEvent.output + scores = experimentEvent.scores + spanAttributes = experimentEvent.spanAttributes + spanParents = experimentEvent.spanParents.map { it.toMutableList() } + tags = experimentEvent.tags.map { it.toMutableList() } + additionalProperties = experimentEvent.additionalProperties.toMutableMap() + } + + /** + * A unique identifier for the experiment event. If you don't provide one, BrainTrust will + * generate one for you + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The transaction id of an event is unique to the network operation that processed the + * event insertion. Transaction ids are monotonically increasing over time and can be used + * to retrieve a versioned snapshot of the experiment (see the `version` parameter) + */ + fun _xactId(_xactId: String) = _xactId(JsonField.of(_xactId)) + + /** + * Sets [Builder._xactId] to an arbitrary JSON value. + * + * You should usually call [Builder._xactId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } + + /** The timestamp the experiment event was created */ + fun created(created: OffsetDateTime) = created(JsonField.of(created)) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Unique identifier for the experiment */ + fun experimentId(experimentId: String) = experimentId(JsonField.of(experimentId)) + + /** + * Sets [Builder.experimentId] to an arbitrary JSON value. + * + * You should usually call [Builder.experimentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun experimentId(experimentId: JsonField) = apply { + this.experimentId = experimentId + } + + /** 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 } + + /** A unique identifier for the trace this experiment event belongs to */ + fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } + + /** + * A unique identifier used to link different experiment events together as part of a full + * trace. See the [tracing guide](https://www.braintrust.dev/docs/guides/tracing) for full + * details on tracing + */ + fun spanId(spanId: String) = spanId(JsonField.of(spanId)) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + /** + * 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 + */ + fun context(context: Context?) = context(JsonField.ofNullable(context)) + + /** Alias for calling [Builder.context] with `context.orElse(null)`. */ + fun context(context: Optional) = context(context.getOrNull()) + + /** + * Sets [Builder.context] to an arbitrary JSON value. + * + * You should usually call [Builder.context] with a well-typed [Context] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun context(context: JsonField) = apply { this.context = context } + + /** The error that occurred, if any. */ + fun error(error: JsonValue) = apply { this.error = error } + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does + * not compare `output` to `expected` for you, since there are so many different ways to do + * that correctly. Instead, these values are just used to help you navigate your experiments + * while digging into analyses. However, we may later use these values to re-score outputs + * or fine-tune your models + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). + * Later on, Braintrust will use the `input` to know whether two test cases are the same + * between experiments, so they should not contain experiment-specific state. A simple rule + * of thumb is that if you run the same experiment twice, the `input` should be identical + */ + fun input(input: JsonValue) = apply { this.input = input } + + /** Whether this span is a root span */ + fun isRoot(isRoot: Boolean?) = isRoot(JsonField.ofNullable(isRoot)) + + /** + * Alias for [Builder.isRoot]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isRoot(isRoot: Boolean) = isRoot(isRoot as Boolean?) + + /** Alias for calling [Builder.isRoot] with `isRoot.orElse(null)`. */ + fun isRoot(isRoot: Optional) = isRoot(isRoot.getOrNull()) + + /** + * Sets [Builder.isRoot] to an arbitrary JSON value. + * + * You should usually call [Builder.isRoot] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun isRoot(isRoot: JsonField) = apply { this.isRoot = isRoot } + + /** + * 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 example, you could log the `prompt`, example's `id`, or anything else that would be + * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, + * but its keys must be strings + */ + 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 } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * experiment event. Use "start" and "end" to track the time span over which the experiment + * event was produced + */ + fun metrics(metrics: Metrics?) = metrics(JsonField.ofNullable(metrics)) + + /** Alias for calling [Builder.metrics] with `metrics.orElse(null)`. */ + fun metrics(metrics: Optional) = metrics(metrics.getOrNull()) + + /** + * Sets [Builder.metrics] to an arbitrary JSON value. + * + * You should usually call [Builder.metrics] with a well-typed [Metrics] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun metrics(metrics: JsonField) = apply { this.metrics = metrics } + + /** Indicates the event was copied from another object. */ + fun origin(origin: ObjectReference?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [ObjectReference] 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 } + + /** + * The output of your application, including post-processing (an arbitrary, JSON + * serializable object), that allows you to determine whether the result is correct or not. + * For example, in an app that generates SQL queries, the `output` should be the _result_ of + * the SQL query generated by the model, not the query itself, because there may be multiple + * valid queries that answer a single question + */ + fun output(output: JsonValue) = apply { this.output = output } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a + * variety of signals that help you determine how accurate the outputs are compared to what + * you expect and diagnose failures. For example, a summarization app might have one score + * that tells you how accurate the summary is, and another that measures the word similarity + * between the generated and grouth truth summary. The word similarity score could help you + * determine whether the summarization was covering similar concepts or not. You can use + * these scores to help you sort, filter, and compare experiments + */ + fun scores(scores: Scores?) = scores(JsonField.ofNullable(scores)) + + /** Alias for calling [Builder.scores] with `scores.orElse(null)`. */ + fun scores(scores: Optional) = scores(scores.getOrNull()) + + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed [Scores] 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 } + + /** Human-identifying attributes of the span, such as name, type, etc. */ + fun spanAttributes(spanAttributes: SpanAttributes?) = + spanAttributes(JsonField.ofNullable(spanAttributes)) + + /** Alias for calling [Builder.spanAttributes] with `spanAttributes.orElse(null)`. */ + fun spanAttributes(spanAttributes: Optional) = + spanAttributes(spanAttributes.getOrNull()) + + /** + * Sets [Builder.spanAttributes] to an arbitrary JSON value. + * + * You should usually call [Builder.spanAttributes] with a well-typed [SpanAttributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanAttributes(spanAttributes: JsonField) = apply { + this.spanAttributes = spanAttributes + } + + /** + * An array of the parent `span_ids` of this experiment event. This should be empty for the + * root span of a trace, and should most often contain just one parent element for subspans + */ + fun spanParents(spanParents: List?) = spanParents(JsonField.ofNullable(spanParents)) + + /** Alias for calling [Builder.spanParents] with `spanParents.orElse(null)`. */ + fun spanParents(spanParents: Optional>) = spanParents(spanParents.getOrNull()) + + /** + * Sets [Builder.spanParents] to an arbitrary JSON value. + * + * You should usually call [Builder.spanParents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanParents(spanParents: JsonField>) = apply { + this.spanParents = spanParents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [spanParents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSpanParent(spanParent: String) = apply { + spanParents = + (spanParents ?: JsonField.of(mutableListOf())).also { + checkKnown("spanParents", it).add(spanParent) + } + } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ExperimentEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .created() + * .experimentId() + * .projectId() + * .rootSpanId() + * .spanId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ExperimentEvent = + ExperimentEvent( + checkRequired("id", id), + checkRequired("_xactId", _xactId), + checkRequired("created", created), + checkRequired("experimentId", experimentId), + checkRequired("projectId", projectId), + checkRequired("rootSpanId", rootSpanId), + checkRequired("spanId", spanId), + context, + error, + expected, + input, + isRoot, + metadata, + metrics, + origin, + output, + scores, + spanAttributes, + (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, + (tags ?: JsonMissing.of()).map { it.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 + */ + class Context + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = callerFilename.getOptional("caller_filename") + + /** + * The function in code which created the experiment event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun callerFunctionname(): Optional = + callerFunctionname.getOptional("caller_functionname") + + /** + * Line of 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 callerLineno(): Optional = callerLineno.getOptional("caller_lineno") + + /** + * Returns the raw JSON value of [callerFilename]. + * + * Unlike [callerFilename], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_filename") + @ExcludeMissing + fun _callerFilename(): JsonField = callerFilename + + /** + * Returns the raw JSON value of [callerFunctionname]. + * + * Unlike [callerFunctionname], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonField = callerFunctionname + + /** + * Returns the raw JSON value of [callerLineno]. + * + * Unlike [callerLineno], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_lineno") + @ExcludeMissing + fun _callerLineno(): JsonField = callerLineno + + @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 [Context]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Context]. */ + class Builder internal constructor() { + + private var callerFilename: JsonField = JsonMissing.of() + private var callerFunctionname: JsonField = JsonMissing.of() + private var callerLineno: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(context: Context) = apply { + callerFilename = context.callerFilename + callerFunctionname = context.callerFunctionname + callerLineno = context.callerLineno + additionalProperties = context.additionalProperties.toMutableMap() + } + + /** Name of the file in code where the experiment event was created */ + fun callerFilename(callerFilename: String?) = + callerFilename(JsonField.ofNullable(callerFilename)) + + /** Alias for calling [Builder.callerFilename] with `callerFilename.orElse(null)`. */ + fun callerFilename(callerFilename: Optional) = + callerFilename(callerFilename.getOrNull()) + + /** + * Sets [Builder.callerFilename] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFilename] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFilename(callerFilename: JsonField) = apply { + this.callerFilename = callerFilename + } + + /** The function in code which created the experiment event */ + fun callerFunctionname(callerFunctionname: String?) = + callerFunctionname(JsonField.ofNullable(callerFunctionname)) + + /** + * Alias for calling [Builder.callerFunctionname] with + * `callerFunctionname.orElse(null)`. + */ + fun callerFunctionname(callerFunctionname: Optional) = + callerFunctionname(callerFunctionname.getOrNull()) + + /** + * Sets [Builder.callerFunctionname] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFunctionname] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFunctionname(callerFunctionname: JsonField) = apply { + this.callerFunctionname = callerFunctionname + } + + /** Line of code where the experiment event was created */ + fun callerLineno(callerLineno: Long?) = callerLineno(JsonField.ofNullable(callerLineno)) + + /** + * Alias for [Builder.callerLineno]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun callerLineno(callerLineno: Long) = callerLineno(callerLineno as Long?) + + /** Alias for calling [Builder.callerLineno] with `callerLineno.orElse(null)`. */ + fun callerLineno(callerLineno: Optional) = callerLineno(callerLineno.getOrNull()) + + /** + * Sets [Builder.callerLineno] to an arbitrary JSON value. + * + * You should usually call [Builder.callerLineno] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerLineno(callerLineno: JsonField) = apply { + this.callerLineno = callerLineno + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Context]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Context = + Context( + callerFilename, + callerFunctionname, + callerLineno, + 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 + } + + return other is Context && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(callerFilename, callerFunctionname, callerLineno, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Context{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" + } + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + */ + class Metadata + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = model.getOptional("model") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + @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 [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var model: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + model = metadata.model + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + /** The model used for this example */ + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(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 + } + + return other is Metadata && + model == other.model && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(model, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{model=$model, additionalProperties=$additionalProperties}" + } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * experiment event. Use "start" and "end" to track the time span over which the experiment + * event was produced + */ + class Metrics + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + fun _callerFilename(): JsonValue = callerFilename + + /** This metric is deprecated */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonValue = callerFunctionname + + /** This metric is deprecated */ + @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno(): JsonValue = callerLineno + + /** + * The number of tokens in the completion generated by the model (only set if this is an LLM + * span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun completionTokens(): Optional = completionTokens.getOptional("completion_tokens") + + /** + * A unix timestamp recording when the section of code which produced the experiment event + * finished + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun end(): Optional = end.getOptional("end") + + /** + * The number of tokens in the prompt used to generate the experiment event (only set if + * this is an LLM span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptTokens(): Optional = promptTokens.getOptional("prompt_tokens") + + /** + * A unix timestamp recording when the section of code which produced the experiment event + * started + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun start(): Optional = start.getOptional("start") + + /** + * The total number of tokens in the input and output of the experiment event. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tokens(): Optional = tokens.getOptional("tokens") + + /** + * Returns the raw JSON value of [completionTokens]. + * + * Unlike [completionTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("completion_tokens") + @ExcludeMissing + fun _completionTokens(): JsonField = completionTokens + + /** + * Returns the raw JSON value of [end]. + * + * Unlike [end], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end + + /** + * Returns the raw JSON value of [promptTokens]. + * + * Unlike [promptTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("prompt_tokens") + @ExcludeMissing + fun _promptTokens(): JsonField = promptTokens + + /** + * Returns the raw JSON value of [start]. + * + * Unlike [start], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start + + /** + * Returns the raw JSON value of [tokens]. + * + * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metrics]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metrics]. */ + class Builder internal constructor() { + + private var callerFilename: JsonValue = JsonMissing.of() + private var callerFunctionname: JsonValue = JsonMissing.of() + private var callerLineno: JsonValue = JsonMissing.of() + private var completionTokens: JsonField = JsonMissing.of() + private var end: JsonField = JsonMissing.of() + private var promptTokens: JsonField = JsonMissing.of() + private var start: JsonField = JsonMissing.of() + private var tokens: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metrics: Metrics) = apply { + callerFilename = metrics.callerFilename + callerFunctionname = metrics.callerFunctionname + callerLineno = metrics.callerLineno + completionTokens = metrics.completionTokens + end = metrics.end + promptTokens = metrics.promptTokens + start = metrics.start + tokens = metrics.tokens + additionalProperties = metrics.additionalProperties.toMutableMap() + } + + /** This metric is deprecated */ + fun callerFilename(callerFilename: JsonValue) = apply { + this.callerFilename = callerFilename + } + + /** This metric is deprecated */ + fun callerFunctionname(callerFunctionname: JsonValue) = apply { + this.callerFunctionname = callerFunctionname + } + + /** This metric is deprecated */ + fun callerLineno(callerLineno: JsonValue) = apply { this.callerLineno = callerLineno } + + /** + * The number of tokens in the completion generated by the model (only set if this is an + * LLM span) + */ + fun completionTokens(completionTokens: Long?) = + completionTokens(JsonField.ofNullable(completionTokens)) + + /** + * Alias for [Builder.completionTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun completionTokens(completionTokens: Long) = + completionTokens(completionTokens as Long?) + + /** + * Alias for calling [Builder.completionTokens] with `completionTokens.orElse(null)`. + */ + fun completionTokens(completionTokens: Optional) = + completionTokens(completionTokens.getOrNull()) + + /** + * Sets [Builder.completionTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.completionTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun completionTokens(completionTokens: JsonField) = apply { + this.completionTokens = completionTokens + } + + /** + * A unix timestamp recording when the section of code which produced the experiment + * event finished + */ + fun end(end: Double?) = end(JsonField.ofNullable(end)) + + /** + * Alias for [Builder.end]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun end(end: Double) = end(end as Double?) + + /** Alias for calling [Builder.end] with `end.orElse(null)`. */ + fun end(end: Optional) = end(end.getOrNull()) + + /** + * Sets [Builder.end] to an arbitrary JSON value. + * + * You should usually call [Builder.end] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun end(end: JsonField) = apply { this.end = end } + + /** + * The number of tokens in the prompt used to generate the experiment event (only set if + * this is an LLM span) + */ + fun promptTokens(promptTokens: Long?) = promptTokens(JsonField.ofNullable(promptTokens)) + + /** + * Alias for [Builder.promptTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun promptTokens(promptTokens: Long) = promptTokens(promptTokens as Long?) + + /** Alias for calling [Builder.promptTokens] with `promptTokens.orElse(null)`. */ + fun promptTokens(promptTokens: Optional) = promptTokens(promptTokens.getOrNull()) + + /** + * Sets [Builder.promptTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.promptTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptTokens(promptTokens: JsonField) = apply { + this.promptTokens = promptTokens + } + + /** + * A unix timestamp recording when the section of code which produced the experiment + * event started + */ + fun start(start: Double?) = start(JsonField.ofNullable(start)) + + /** + * Alias for [Builder.start]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun start(start: Double) = start(start as Double?) + + /** Alias for calling [Builder.start] with `start.orElse(null)`. */ + fun start(start: Optional) = start(start.getOrNull()) + + /** + * Sets [Builder.start] to an arbitrary JSON value. + * + * You should usually call [Builder.start] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun start(start: JsonField) = apply { this.start = start } + + /** The total number of tokens in the input and output of the experiment event. */ + fun tokens(tokens: Long?) = tokens(JsonField.ofNullable(tokens)) + + /** + * Alias for [Builder.tokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun tokens(tokens: Long) = tokens(tokens as Long?) + + /** Alias for calling [Builder.tokens] with `tokens.orElse(null)`. */ + fun tokens(tokens: Optional) = tokens(tokens.getOrNull()) + + /** + * Sets [Builder.tokens] to an arbitrary JSON value. + * + * You should usually call [Builder.tokens] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tokens(tokens: JsonField) = apply { this.tokens = tokens } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metrics]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metrics = + Metrics( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + 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 + } + + return other is Metrics && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + completionTokens == other.completionTokens && + end == other.end && + promptTokens == other.promptTokens && + start == other.start && + tokens == other.tokens && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metrics{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, completionTokens=$completionTokens, end=$end, promptTokens=$promptTokens, start=$start, tokens=$tokens, additionalProperties=$additionalProperties}" + } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare experiments + */ + class Scores + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Scores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scores: Scores) = apply { + additionalProperties = scores.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 [Scores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Scores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Scores{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExperimentEvent && + id == other.id && + _xactId == other._xactId && + created == other.created && + experimentId == other.experimentId && + projectId == other.projectId && + rootSpanId == other.rootSpanId && + spanId == other.spanId && + context == other.context && + error == other.error && + expected == other.expected && + input == other.input && + isRoot == other.isRoot && + metadata == other.metadata && + metrics == other.metrics && + origin == other.origin && + output == other.output && + scores == other.scores && + spanAttributes == other.spanAttributes && + spanParents == other.spanParents && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _xactId, + created, + experimentId, + projectId, + rootSpanId, + spanId, + context, + error, + expected, + input, + isRoot, + metadata, + metrics, + origin, + output, + scores, + spanAttributes, + spanParents, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ExperimentEvent{id=$id, _xactId=$_xactId, created=$created, experimentId=$experimentId, projectId=$projectId, rootSpanId=$rootSpanId, spanId=$spanId, context=$context, error=$error, expected=$expected, input=$input, isRoot=$isRoot, metadata=$metadata, metrics=$metrics, origin=$origin, output=$output, scores=$scores, spanAttributes=$spanAttributes, spanParents=$spanParents, tags=$tags, additionalProperties=$additionalProperties}" +} 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 old mode 100644 new mode 100755 index 0d366e0c..391a2223 --- 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 @@ -4,631 +4,470 @@ 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.toUnmodifiable +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.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Log feedback for a set of experiment events */ class ExperimentFeedbackParams -constructor( - private val experimentId: String, - private val feedback: List, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { +private constructor( + private val experimentId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) + + /** + * 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 = body.feedback() + + /** + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _feedback(): JsonField> = body._feedback() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun experimentId(): String = experimentId + fun toBuilder() = Builder().from(this) - fun feedback(): List = feedback + companion object { - @JvmSynthetic - internal fun getBody(): ExperimentFeedbackBody { - return ExperimentFeedbackBody(feedback, additionalBodyProperties) + /** + * Returns a mutable builder for constructing an instance of [ExperimentFeedbackParams]. + * + * The following fields are required: + * ```java + * .feedback() + * ``` + */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [ExperimentFeedbackParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" + @JvmSynthetic + internal fun from(experimentFeedbackParams: ExperimentFeedbackParams) = apply { + experimentId = experimentFeedbackParams.experimentId + body = experimentFeedbackParams.body.toBuilder() + additionalHeaders = experimentFeedbackParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentFeedbackParams.additionalQueryParams.toBuilder() } - } - - @JsonDeserialize(builder = ExperimentFeedbackBody.Builder::class) - @NoAutoDetect - class ExperimentFeedbackBody - internal constructor( - private val feedback: List?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** A list of experiment feedback items */ - @JsonProperty("feedback") fun feedback(): List? = feedback - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Experiment id */ + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } - fun toBuilder() = Builder().from(this) + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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() } - return other is ExperimentFeedbackBody && - this.feedback == other.feedback && - this.additionalProperties == other.additionalProperties - } + /** A list of experiment feedback items */ + fun feedback(feedback: List) = apply { body.feedback(feedback) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(feedback, additionalProperties) - } - return hashCode + /** + * 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 { + body.feedback(feedback) } - override fun toString() = - "ExperimentFeedbackBody{feedback=$feedback, additionalProperties=$additionalProperties}" - - companion object { + /** + * Adds a single [FeedbackExperimentItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFeedback(feedback: FeedbackExperimentItem) = apply { body.addFeedback(feedback) } - @JvmStatic fun builder() = Builder() + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - class Builder { - - private var feedback: List? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentFeedbackBody: ExperimentFeedbackBody) = apply { - this.feedback = experimentFeedbackBody.feedback - additionalProperties(experimentFeedbackBody.additionalProperties) - } - - /** A list of experiment feedback items */ - @JsonProperty("feedback") - fun feedback(feedback: List) = apply { this.feedback = feedback } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun build(): ExperimentFeedbackBody = - ExperimentFeedbackBody( - checkNotNull(feedback) { "`feedback` is required but was not set" } - .toUnmodifiable(), - additionalProperties.toUnmodifiable() - ) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - return other is ExperimentFeedbackParams && - this.experimentId == other.experimentId && - this.feedback == other.feedback && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - override fun hashCode(): Int { - return Objects.hash( - experimentId, - feedback, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - override fun toString() = - "ExperimentFeedbackParams{experimentId=$experimentId, feedback=$feedback, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - fun toBuilder() = Builder().from(this) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - companion object { + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmStatic fun builder() = Builder() - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - @NoAutoDetect - class Builder { + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - private var experimentId: String? = null - private var feedback: MutableList = mutableListOf() - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(experimentFeedbackParams: ExperimentFeedbackParams) = apply { - this.experimentId = experimentFeedbackParams.experimentId - this.feedback(experimentFeedbackParams.feedback) - additionalQueryParams(experimentFeedbackParams.additionalQueryParams) - additionalHeaders(experimentFeedbackParams.additionalHeaders) - additionalBodyProperties(experimentFeedbackParams.additionalBodyProperties) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** A list of experiment feedback items */ - fun feedback(feedback: List) = apply { - this.feedback.clear() - this.feedback.addAll(feedback) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - /** A list of experiment feedback items */ - fun addFeedback(feedback: Feedback) = apply { this.feedback.add(feedback) } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + putAllAdditionalQueryParams(additionalQueryParams) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - + /** + * Returns an immutable instance of [ExperimentFeedbackParams]. + * + * 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(): ExperimentFeedbackParams = ExperimentFeedbackParams( - checkNotNull(experimentId) { "`experimentId` is required but was not set" }, - checkNotNull(feedback) { "`feedback` is required but was not set" } - .toUnmodifiable(), - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), + experimentId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } - @JsonDeserialize(builder = Feedback.Builder::class) - @NoAutoDetect - class Feedback - private constructor( - private val id: String?, - private val scores: Scores?, - private val expected: JsonValue?, - private val comment: String?, - private val metadata: Metadata?, - private val source: Source?, - private val additionalProperties: Map, - ) { + fun _body(): Body = body - private var hashCode: Int = 0 + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId ?: "" + else -> "" + } - /** - * The id of the experiment event to log feedback for. This is the row `id` returned by - * `POST /v1/experiment/{experiment_id}/insert` - */ - @JsonProperty("id") fun id(): String? = id + override fun _headers(): Headers = additionalHeaders - /** - * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into - * the existing scores for the experiment event - */ - @JsonProperty("scores") fun scores(): Scores? = scores + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val feedback: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("feedback") + @ExcludeMissing + feedback: JsonField> = JsonMissing.of() + ) : this(feedback, mutableMapOf()) /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not + * 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). */ - @JsonProperty("expected") fun expected(): JsonValue? = expected - - /** An optional comment string to log about the experiment event */ - @JsonProperty("comment") fun comment(): String? = comment + fun feedback(): List = feedback.getRequired("feedback") /** - * 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. + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("metadata") fun metadata(): Metadata? = metadata + @JsonProperty("feedback") + @ExcludeMissing + fun _feedback(): JsonField> = feedback - /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ - @JsonProperty("source") fun source(): Source? = source + @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) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Feedback && - this.id == other.id && - this.scores == other.scores && - this.expected == other.expected && - this.comment == other.comment && - this.metadata == other.metadata && - this.source == other.source && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - scores, - expected, - comment, - metadata, - source, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Feedback{id=$id, scores=$scores, expected=$expected, comment=$comment, metadata=$metadata, source=$source, additionalProperties=$additionalProperties}" - companion object { + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .feedback() + * ``` + */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Body]. */ + class Builder internal constructor() { - private var id: String? = null - private var scores: Scores? = null - private var expected: JsonValue? = null - private var comment: String? = null - private var metadata: Metadata? = null - private var source: Source? = null + private var feedback: JsonField>? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(feedback: Feedback) = apply { - this.id = feedback.id - this.scores = feedback.scores - this.expected = feedback.expected - this.comment = feedback.comment - this.metadata = feedback.metadata - this.source = feedback.source - additionalProperties(feedback.additionalProperties) + internal fun from(body: Body) = apply { + feedback = body.feedback.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() } - /** - * The id of the experiment event to log feedback for. This is the row `id` returned by - * `POST /v1/experiment/{experiment_id}/insert` - */ - @JsonProperty("id") fun id(id: String) = apply { this.id = id } - - /** - * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged - * into the existing scores for the experiment event - */ - @JsonProperty("scores") fun scores(scores: Scores) = apply { this.scores = scores } + /** A list of experiment feedback items */ + fun feedback(feedback: List) = feedback(JsonField.of(feedback)) /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not + * 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. */ - @JsonProperty("expected") - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** An optional comment string to log about the experiment event */ - @JsonProperty("comment") fun comment(comment: String) = apply { this.comment = comment } + fun feedback(feedback: JsonField>) = apply { + this.feedback = feedback.map { it.toMutableList() } + } /** - * 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. + * Adds a single [FeedbackExperimentItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("metadata") - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } - - /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ - @JsonProperty("source") fun source(source: Source) = apply { this.source = source } + 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() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Feedback = - Feedback( - checkNotNull(id) { "`id` is required but was not set" }, - scores, - expected, - comment, - metadata, - source, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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. - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + /** + * 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(), + ) + } - companion object { + private var validated: Boolean = false - @JvmStatic fun builder() = Builder() + fun validate(): Body = apply { + if (validated) { + return@apply } - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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) - } + feedback().forEach { it.validate() } + validated = true + } - fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - } /** - * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into - * the existing scores for the experiment event + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { + @JvmSynthetic + internal fun validity(): Int = + (feedback.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } + return other is Body && + feedback == other.feedback && + additionalProperties == other.additionalProperties } - class Source - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Source && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val APP = Source(JsonField.of("app")) - - @JvmField val API = Source(JsonField.of("api")) - - @JvmField val EXTERNAL = Source(JsonField.of("external")) + private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } - @JvmStatic fun of(value: String) = Source(JsonField.of(value)) - } + override fun hashCode(): Int = hashCode - enum class Known { - APP, - API, - EXTERNAL, - } + override fun toString() = + "Body{feedback=$feedback, additionalProperties=$additionalProperties}" + } - enum class Value { - APP, - API, - EXTERNAL, - _UNKNOWN, - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun value(): Value = - when (this) { - APP -> Value.APP - API -> Value.API - EXTERNAL -> Value.EXTERNAL - else -> Value._UNKNOWN - } + return other is ExperimentFeedbackParams && + experimentId == other.experimentId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } - fun known(): Known = - when (this) { - APP -> Known.APP - API -> Known.API - EXTERNAL -> Known.EXTERNAL - else -> throw BraintrustInvalidDataException("Unknown Source: $value") - } + override fun hashCode(): Int = + Objects.hash(experimentId, body, additionalHeaders, additionalQueryParams) - fun asString(): String = _value().asStringOrThrow() - } - } + override fun toString() = + "ExperimentFeedbackParams{experimentId=$experimentId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index dd696312..15a35318 --- 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,120 +2,131 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Fetch the events in an experiment. Equivalent to the POST form of the same path, but with the + * parameters in the URL query rather than in the request body. For more complex queries, use the + * `POST /btql` endpoint. + */ class ExperimentFetchParams -constructor( - private val experimentId: String, +private constructor( + private val experimentId: String?, private val limit: Long?, private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { - - fun experimentId(): String = experimentId - + private val maxXactId: String?, + private val version: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) + + /** + * 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(): Optional = Optional.ofNullable(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(): Optional = Optional.ofNullable(maxRootSpanId) - fun maxXactId(): Optional = Optional.ofNullable(maxXactId) - - fun version(): Optional = Optional.ofNullable(version) - - @JvmSynthetic - internal fun getQueryParams(): Map> { - val params = mutableMapOf>() - this.limit?.let { params.put("limit", listOf(it.toString())) } - this.maxRootSpanId?.let { params.put("max_root_span_id", listOf(it.toString())) } - this.maxXactId?.let { params.put("max_xact_id", listOf(it.toString())) } - this.version?.let { params.put("version", listOf(it.toString())) } - params.putAll(additionalQueryParams) - return params.toUnmodifiable() - } - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentFetchParams && - this.experimentId == other.experimentId && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } - - override fun hashCode(): Int { - return Objects.hash( - experimentId, - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams, - additionalHeaders, - ) - } - - override fun toString() = - "ExperimentFetchParams{experimentId=$experimentId, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + /** + * 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(): Optional = Optional.ofNullable(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(): Optional = Optional.ofNullable(version) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ExperimentFetchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ExperimentFetchParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ExperimentFetchParams]. */ + class Builder internal constructor() { private var experimentId: String? = null private var limit: Long? = null private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var maxXactId: String? = null + private var version: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(experimentFetchParams: ExperimentFetchParams) = apply { - this.experimentId = experimentFetchParams.experimentId - this.limit = experimentFetchParams.limit - this.maxRootSpanId = experimentFetchParams.maxRootSpanId - this.maxXactId = experimentFetchParams.maxXactId - this.version = experimentFetchParams.version - additionalQueryParams(experimentFetchParams.additionalQueryParams) - additionalHeaders(experimentFetchParams.additionalHeaders) + experimentId = experimentFetchParams.experimentId + limit = experimentFetchParams.limit + maxRootSpanId = experimentFetchParams.maxRootSpanId + maxXactId = experimentFetchParams.maxXactId + version = experimentFetchParams.version + additionalHeaders = experimentFetchParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentFetchParams.additionalQueryParams.toBuilder() } /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } + + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) /** + * 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, @@ -128,80 +139,224 @@ constructor( * with more individual rows than the specified limit if you are fetching events containing * traces. */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(limit: Long?) = apply { this.limit = limit } /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. */ - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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: Long) = apply { this.maxXactId = maxXactId } + fun maxRootSpanId(maxRootSpanId: String?) = apply { this.maxRootSpanId = maxRootSpanId } + + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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 version(version: Long) = apply { this.version = version } + fun maxXactId(maxXactId: String?) = apply { this.maxXactId = maxXactId } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** 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. + */ + fun version(version: String?) = apply { this.version = version } + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [ExperimentFetchParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ExperimentFetchParams = ExperimentFetchParams( - checkNotNull(experimentId) { "`experimentId` is required but was not set" }, + experimentId, limit, maxRootSpanId, maxXactId, version, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + } + + return other is ExperimentFetchParams && + experimentId == other.experimentId && + limit == other.limit && + maxRootSpanId == other.maxRootSpanId && + maxXactId == other.maxXactId && + version == other.version && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + experimentId, + limit, + maxRootSpanId, + maxXactId, + version, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ExperimentFetchParams{experimentId=$experimentId, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index 203e23d4..44326a64 --- 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 @@ -4,88 +4,226 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Fetch the events in an experiment. Equivalent to the GET form of the same path, but with the + * parameters in the request body rather than in the URL query. For more complex queries, use the + * `POST /btql` endpoint. + */ class ExperimentFetchPostParams -constructor( - private val experimentId: String, - private val filters: List?, - private val limit: Long?, - private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun experimentId(): String = experimentId - - fun filters(): Optional> = Optional.ofNullable(filters) - - fun limit(): Optional = Optional.ofNullable(limit) - - fun maxRootSpanId(): Optional = Optional.ofNullable(maxRootSpanId) - - fun maxXactId(): Optional = Optional.ofNullable(maxXactId) - - fun version(): Optional = Optional.ofNullable(version) - - @JvmSynthetic - internal fun getBody(): ExperimentFetchPostBody { - return ExperimentFetchPostBody( - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalBodyProperties, - ) +private constructor( + private val experimentId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cursor(): Optional = body.cursor() + + /** + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxRootSpanId(): Optional = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxXactId(): Optional = body.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 = body.version() + + /** + * Returns the raw JSON value of [cursor]. + * + * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _cursor(): JsonField = body._cursor() + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _limit(): JsonField = body._limit() + + /** + * Returns the raw JSON value of [maxRootSpanId]. + * + * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxRootSpanId(): JsonField = body._maxRootSpanId() + + /** + * Returns the raw JSON value of [maxXactId]. + * + * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxXactId(): JsonField = body._maxXactId() + + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _version(): JsonField = body._version() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ExperimentFetchPostParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of [ExperimentFetchPostParams]. + */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [ExperimentFetchPostParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" + @JvmSynthetic + internal fun from(experimentFetchPostParams: ExperimentFetchPostParams) = apply { + experimentId = experimentFetchPostParams.experimentId + body = experimentFetchPostParams.body.toBuilder() + additionalHeaders = experimentFetchPostParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentFetchPostParams.additionalQueryParams.toBuilder() } - } - @JsonDeserialize(builder = ExperimentFetchPostBody.Builder::class) - @NoAutoDetect - class ExperimentFetchPostBody - internal constructor( - private val filters: List?, - private val limit: Long?, - private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalProperties: Map, - ) { + /** Experiment id */ + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } + + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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 + * latest to earliest. + * + * The string can be obtained directly from the `cursor` property of the previous fetch + * query + */ + fun cursor(cursor: String?) = apply { body.cursor(cursor) } - private var hashCode: Int = 0 + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * 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. */ - @JsonProperty("filters") fun filters(): List? = filters + fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } /** + * 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, @@ -98,259 +236,282 @@ constructor( * with more individual rows than the specified limit if you are fetching events containing * traces. */ - @JsonProperty("limit") fun limit(): Long? = limit + fun limit(limit: Long?) = apply { body.limit(limit) } /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("max_root_span_id") fun maxRootSpanId(): String? = maxRootSpanId + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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. */ - @JsonProperty("max_xact_id") fun maxXactId(): Long? = maxXactId + fun limit(limit: JsonField) = apply { body.limit(limit) } /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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. */ - @JsonProperty("version") fun version(): Long? = version + fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - fun toBuilder() = Builder().from(this) + /** + * 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 { + body.maxRootSpanId(maxRootSpanId) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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?) = apply { body.maxXactId(maxXactId) } - return other is ExperimentFetchPostBody && - this.filters == other.filters && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties, - ) - } - return hashCode - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - override fun toString() = - "ExperimentFetchPostBody{filters=$filters, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" + /** + * 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 { body.maxXactId(maxXactId) } - companion object { + /** + * 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?) = apply { body.version(version) } - @JvmStatic fun builder() = Builder() - } + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) - class Builder { + /** + * 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) } - private var filters: List? = null - private var limit: Long? = null - private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - @JvmSynthetic - internal fun from(experimentFetchPostBody: ExperimentFetchPostBody) = apply { - this.filters = experimentFetchPostBody.filters - this.limit = experimentFetchPostBody.limit - this.maxRootSpanId = experimentFetchPostBody.maxRootSpanId - this.maxXactId = experimentFetchPostBody.maxXactId - this.version = experimentFetchPostBody.version - additionalProperties(experimentFetchPostBody.additionalProperties) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters - * are supported, but we may add more in the future - */ - @JsonProperty("filters") - fun filters(filters: List) = apply { this.filters = filters } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** - * 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. - */ - @JsonProperty("limit") fun limit(limit: Long) = apply { this.limit = limit } + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine - * `max_root_span_id` as the maximum of the `root_span_id` field over all rows. See the - * documentation for `limit` for an overview of paginating fetch queries. - */ - @JsonProperty("max_root_span_id") - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` - * as the maximum of the `_xact_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. - */ - @JsonProperty("max_xact_id") - fun maxXactId(maxXactId: Long) = apply { this.maxXactId = maxXactId } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * You may specify a version id to retrieve a snapshot of the 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. - */ - @JsonProperty("version") fun version(version: Long) = apply { this.version = version } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - fun build(): ExperimentFetchPostBody = - ExperimentFetchPostBody( - filters?.toUnmodifiable(), - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties.toUnmodifiable(), - ) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - } - fun _additionalQueryParams(): Map> = additionalQueryParams + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun _additionalHeaders(): Map> = additionalHeaders + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun _additionalBodyProperties(): Map = additionalBodyProperties + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - return other is ExperimentFetchPostParams && - this.experimentId == other.experimentId && - this.filters == other.filters && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - override fun hashCode(): Int { - return Objects.hash( - experimentId, - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - override fun toString() = - "ExperimentFetchPostParams{experimentId=$experimentId, filters=$filters, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun toBuilder() = Builder().from(this) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - companion object { + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - @JvmStatic fun builder() = Builder() - } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - @NoAutoDetect - class Builder { + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - private var experimentId: String? = null - private var filters: MutableList = mutableListOf() - private var limit: Long? = null - private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - @JvmSynthetic - internal fun from(experimentFetchPostParams: ExperimentFetchPostParams) = apply { - this.experimentId = experimentFetchPostParams.experimentId - this.filters(experimentFetchPostParams.filters ?: listOf()) - this.limit = experimentFetchPostParams.limit - this.maxRootSpanId = experimentFetchPostParams.maxRootSpanId - this.maxXactId = experimentFetchPostParams.maxXactId - this.version = experimentFetchPostParams.version - additionalQueryParams(experimentFetchPostParams.additionalQueryParams) - additionalHeaders(experimentFetchPostParams.additionalHeaders) - additionalBodyProperties(experimentFetchPostParams.additionalBodyProperties) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + 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) + } /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * Returns an immutable instance of [ExperimentFetchPostParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. */ - fun filters(filters: List) = apply { - this.filters.clear() - this.filters.addAll(filters) + fun build(): ExperimentFetchPostParams = + ExperimentFetchPostParams( + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun addFilter(filter: Filter) = apply { this.filters.add(filter) } + fun cursor(): Optional = cursor.getOptional("cursor") /** + * 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, @@ -362,279 +523,378 @@ 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(): Optional = limit.getOptional("limit") /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun maxRootSpanId(): Optional = maxRootSpanId.getOptional("max_root_span_id") /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxXactId(maxXactId: Long) = apply { this.maxXactId = maxXactId } + fun maxXactId(): Optional = maxXactId.getOptional("max_xact_id") /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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(version: Long) = apply { this.version = version } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } + fun version(): Optional = version.getOptional("version") - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + /** + * 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 - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + /** + * 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 removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + /** + * 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 putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } + fun toBuilder() = Builder().from(this) - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + companion object { - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) + 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() + + @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 build(): ExperimentFetchPostParams = - ExperimentFetchPostParams( - checkNotNull(experimentId) { "`experimentId` is required but was not set" }, - if (filters.size == 0) null else filters.toUnmodifiable(), - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } + /** + * 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)) - /** - * A path-lookup filter describes an equality comparison against a specific sub-field in the - * event row. For instance, if you wish to filter on the value of `c` in `{"input": {"a": {"b": - * {"c": "hello"}}}}`, pass `path=["input", "a", "b", "c"]` and `value="hello"` - */ - @JsonDeserialize(builder = Filter.Builder::class) - @NoAutoDetect - class Filter - private constructor( - private val type: Type?, - private val path: List?, - private val value: JsonValue?, - private val additionalProperties: Map, - ) { + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - private var hashCode: Int = 0 + /** + * 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 } - /** Denotes the type of filter as a path-lookup filter */ - @JsonProperty("type") fun type(): Type? = type + /** + * 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)) - /** - * List of fields describing the path to the value to be checked against. For instance, if - * you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": "hello"}}}}`, pass - * `path=["input", "a", "b", "c"]` - */ - @JsonProperty("path") fun path(): List? = path + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) - /** - * The value to compare equality-wise against the event value at the specified `path`. The - * value must be a "primitive", that is, any JSON-serializable object except for objects and - * arrays. For instance, if you wish to filter on the value of "input.a.b.c" in the object - * `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `value="hello"` - */ - @JsonProperty("value") fun value(): JsonValue? = value + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** + * 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 toBuilder() = Builder().from(this) + /** + * 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)) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - return other is Filter && - this.type == other.type && - this.path == other.path && - this.value == other.value && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - type, - path, - value, - additionalProperties, - ) + /** + * 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 } - return hashCode - } - - override fun toString() = - "Filter{type=$type, path=$path, value=$value, additionalProperties=$additionalProperties}" - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var type: Type? = null - private var path: List? = null - private var value: JsonValue? = null - private var additionalProperties: MutableMap = mutableMapOf() + /** + * 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)) - @JvmSynthetic - internal fun from(filter: Filter) = apply { - this.type = filter.type - this.path = filter.path - this.value = filter.value - additionalProperties(filter.additionalProperties) - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - /** Denotes the type of filter as a path-lookup filter */ - @JsonProperty("type") fun type(type: Type) = apply { this.type = type } + /** + * 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 } /** - * List of fields describing the path to the value to be checked against. For instance, - * if you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": - * "hello"}}}}`, pass `path=["input", "a", "b", "c"]` + * 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. */ - @JsonProperty("path") fun path(path: List) = apply { this.path = path } + fun version(version: String?) = version(JsonField.ofNullable(version)) + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) /** - * The value to compare equality-wise against the event value at the specified `path`. - * The value must be a "primitive", that is, any JSON-serializable object except for - * objects and arrays. For instance, if you wish to filter on the value of "input.a.b.c" - * in the object `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `value="hello"` + * 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. */ - @JsonProperty("value") fun value(value: JsonValue) = apply { this.value = value } + fun version(version: JsonField) = apply { this.version = version } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Filter = - Filter( - checkNotNull(type) { "`type` is required but was not set" }, - checkNotNull(path) { "`path` is required but was not set" }.toUnmodifiable(), - value, - additionalProperties.toUnmodifiable(), - ) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + /** + * 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(), + ) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + private var validated: Boolean = false - return other is Type && this.value == other.value + fun validate(): Body = apply { + if (validated) { + return@apply } - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() + cursor() + limit() + maxRootSpanId() + maxXactId() + version() + validated = true + } - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - @JvmField val PATH_LOOKUP = Type(JsonField.of("path_lookup")) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @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) - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - enum class Known { - PATH_LOOKUP, - } + return other is Body && + cursor == other.cursor && + limit == other.limit && + maxRootSpanId == other.maxRootSpanId && + maxXactId == other.maxXactId && + version == other.version && + additionalProperties == other.additionalProperties + } - enum class Value { - PATH_LOOKUP, - _UNKNOWN, - } + private val hashCode: Int by lazy { + Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) + } - fun value(): Value = - when (this) { - PATH_LOOKUP -> Value.PATH_LOOKUP - else -> Value._UNKNOWN - } + override fun hashCode(): Int = hashCode - fun known(): Known = - when (this) { - PATH_LOOKUP -> Known.PATH_LOOKUP - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } + override fun toString() = + "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" + } - fun asString(): String = _value().asStringOrThrow() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } + + return other is ExperimentFetchPostParams && + experimentId == other.experimentId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = + Objects.hash(experimentId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ExperimentFetchPostParams{experimentId=$experimentId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchPostResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchPostResponse.kt deleted file mode 100644 index f9ef0d19..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchPostResponse.kt +++ /dev/null @@ -1,1456 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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 com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.time.OffsetDateTime -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = ExperimentFetchPostResponse.Builder::class) -@NoAutoDetect -class ExperimentFetchPostResponse -private constructor( - private val events: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** A list of fetched events */ - fun events(): List = events.getRequired("events") - - /** A list of fetched events */ - @JsonProperty("events") @ExcludeMissing fun _events() = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): ExperimentFetchPostResponse = apply { - if (!validated) { - events().forEach { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentFetchPostResponse && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ExperimentFetchPostResponse{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentFetchPostResponse: ExperimentFetchPostResponse) = apply { - this.events = experimentFetchPostResponse.events - additionalProperties(experimentFetchPostResponse.additionalProperties) - } - - /** A list of fetched events */ - fun events(events: List) = events(JsonField.of(events)) - - /** A list of fetched events */ - @JsonProperty("events") - @ExcludeMissing - fun events(events: JsonField>) = apply { this.events = events } - - 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(): ExperimentFetchPostResponse = - ExperimentFetchPostResponse( - events.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } - - @JsonDeserialize(builder = Event.Builder::class) - @NoAutoDetect - class Event - private constructor( - private val id: JsonField, - private val datasetRecordId: JsonField, - private val _xactId: JsonField, - private val created: JsonField, - private val projectId: JsonField, - private val experimentId: JsonField, - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanId: JsonField, - private val spanParents: JsonField>, - private val rootSpanId: JsonField, - private val spanAttributes: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): String = id.getRequired("id") - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - fun datasetRecordId(): Optional = - Optional.ofNullable(datasetRecordId.getNullable("dataset_record_id")) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - fun _xactId(): Long = _xactId.getRequired("_xact_id") - - /** The timestamp the experiment event was created */ - fun created(): Optional = - Optional.ofNullable(created.getNullable("created")) - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(): String = projectId.getRequired("project_id") - - /** Unique identifier for the experiment */ - fun experimentId(): String = experimentId.getRequired("experiment_id") - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). - * Later on, Braintrust will use the `input` to know whether two test cases are the same - * between experiments, so they should not contain experiment-specific state. A simple rule - * of thumb is that if you run the same experiment twice, the `input` should be identical - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question - */ - fun output(): JsonValue = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate your experiments - * while digging into analyses. However, we may later use these values to re-score outputs - * or fine-tune your models - */ - fun expected(): JsonValue = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare experiments - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * experiment event. Use "start" and "end" to track the time span over which the experiment - * event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) - - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) - - /** - * A unique identifier used to link different experiment events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - fun spanId(): String = spanId.getRequired("span_id") - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for the - * root span of a trace, and should most often contain just one parent element for subspans - */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) - - /** The `span_id` of the root of the trace this experiment event belongs to */ - fun rootSpanId(): String = rootSpanId.getRequired("root_span_id") - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - @JsonProperty("dataset_record_id") @ExcludeMissing fun _datasetRecordId() = datasetRecordId - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - @JsonProperty("_xact_id") @ExcludeMissing fun __xactId() = _xactId - - /** The timestamp the experiment event was created */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId - - /** Unique identifier for the experiment */ - @JsonProperty("experiment_id") @ExcludeMissing fun _experimentId() = experimentId - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). - * Later on, Braintrust will use the `input` to know whether two test cases are the same - * between experiments, so they should not contain experiment-specific state. A simple rule - * of thumb is that if you run the same experiment twice, the `input` should be identical - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate your experiments - * while digging into analyses. However, we may later use these values to re-score outputs - * or fine-tune your models - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare experiments - */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * experiment event. Use "start" and "end" to track the time span over which the experiment - * event was produced - */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics - - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context - - /** - * A unique identifier used to link different experiment events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - @JsonProperty("span_id") @ExcludeMissing fun _spanId() = spanId - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for the - * root span of a trace, and should most often contain just one parent element for subspans - */ - @JsonProperty("span_parents") @ExcludeMissing fun _spanParents() = spanParents - - /** The `span_id` of the root of the trace this experiment event belongs to */ - @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId() = rootSpanId - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Event = apply { - if (!validated) { - id() - datasetRecordId() - _xactId() - created() - projectId() - experimentId() - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanId() - spanParents() - rootSpanId() - spanAttributes().map { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Event && - this.id == other.id && - this.datasetRecordId == other.datasetRecordId && - this._xactId == other._xactId && - this.created == other.created && - this.projectId == other.projectId && - this.experimentId == other.experimentId && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanId == other.spanId && - this.spanParents == other.spanParents && - this.rootSpanId == other.rootSpanId && - this.spanAttributes == other.spanAttributes && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - datasetRecordId, - _xactId, - created, - projectId, - experimentId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents, - rootSpanId, - spanAttributes, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Event{id=$id, datasetRecordId=$datasetRecordId, _xactId=$_xactId, created=$created, projectId=$projectId, experimentId=$experimentId, input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanId=$spanId, spanParents=$spanParents, rootSpanId=$rootSpanId, spanAttributes=$spanAttributes, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var id: JsonField = JsonMissing.of() - private var datasetRecordId: JsonField = JsonMissing.of() - private var _xactId: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var experimentId: JsonField = JsonMissing.of() - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanId: JsonField = JsonMissing.of() - private var spanParents: JsonField> = JsonMissing.of() - private var rootSpanId: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(event: Event) = apply { - this.id = event.id - this.datasetRecordId = event.datasetRecordId - this._xactId = event._xactId - this.created = event.created - this.projectId = event.projectId - this.experimentId = event.experimentId - this.input = event.input - this.output = event.output - this.expected = event.expected - this.scores = event.scores - this.metadata = event.metadata - this.metrics = event.metrics - this.context = event.context - this.spanId = event.spanId - this.spanParents = event.spanParents - this.rootSpanId = event.rootSpanId - this.spanAttributes = event.spanAttributes - additionalProperties(event.additionalProperties) - } - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - fun datasetRecordId(datasetRecordId: String) = - datasetRecordId(JsonField.of(datasetRecordId)) - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - @JsonProperty("dataset_record_id") - @ExcludeMissing - fun datasetRecordId(datasetRecordId: JsonField) = apply { - this.datasetRecordId = datasetRecordId - } - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - fun _xactId(_xactId: Long) = _xactId(JsonField.of(_xactId)) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - @JsonProperty("_xact_id") - @ExcludeMissing - fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } - - /** The timestamp the experiment event was created */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** The timestamp the experiment event was created */ - @JsonProperty("created") - @ExcludeMissing - fun created(created: JsonField) = apply { this.created = created } - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the experiment */ - fun experimentId(experimentId: String) = experimentId(JsonField.of(experimentId)) - - /** Unique identifier for the experiment */ - @JsonProperty("experiment_id") - @ExcludeMissing - fun experimentId(experimentId: JsonField) = apply { - this.experimentId = experimentId - } - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases are - * the same between experiments, so they should not contain experiment-specific state. A - * simple rule of thumb is that if you run the same experiment twice, the `input` should - * be identical - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * your experiments while digging into analyses. However, we may later use these values - * to re-score outputs or fine-tune your models - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** - * A unique identifier used to link different experiment events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - fun spanId(spanId: String) = spanId(JsonField.of(spanId)) - - /** - * A unique identifier used to link different experiment events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - @JsonProperty("span_id") - @ExcludeMissing - fun spanId(spanId: JsonField) = apply { this.spanId = spanId } - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - fun spanParents(spanParents: List) = spanParents(JsonField.of(spanParents)) - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - @JsonProperty("span_parents") - @ExcludeMissing - fun spanParents(spanParents: JsonField>) = apply { - this.spanParents = spanParents - } - - /** The `span_id` of the root of the trace this experiment event belongs to */ - fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) - - /** The `span_id` of the root of the trace this experiment event belongs to */ - @JsonProperty("root_span_id") - @ExcludeMissing - fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - 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(): Event = - Event( - id, - datasetRecordId, - _xactId, - created, - projectId, - experimentId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents.map { it.toUnmodifiable() }, - rootSpanId, - spanAttributes, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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 - */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the experiment event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the experiment event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the experiment event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") @ExcludeMissing fun _callerFilename() = callerFilename - - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } - - /** The function in code which created the experiment event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) - - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } - - /** Name of the file in code where the experiment event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) - - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } - - /** Line of code where the experiment event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) - - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } - - 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(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * experiment event. Use "start" and "end" to track the time span over which the experiment - * event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare experiments - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchResponse.kt deleted file mode 100644 index 826c93e7..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentFetchResponse.kt +++ /dev/null @@ -1,1456 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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 com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.time.OffsetDateTime -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = ExperimentFetchResponse.Builder::class) -@NoAutoDetect -class ExperimentFetchResponse -private constructor( - private val events: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** A list of fetched events */ - fun events(): List = events.getRequired("events") - - /** A list of fetched events */ - @JsonProperty("events") @ExcludeMissing fun _events() = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): ExperimentFetchResponse = apply { - if (!validated) { - events().forEach { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentFetchResponse && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ExperimentFetchResponse{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentFetchResponse: ExperimentFetchResponse) = apply { - this.events = experimentFetchResponse.events - additionalProperties(experimentFetchResponse.additionalProperties) - } - - /** A list of fetched events */ - fun events(events: List) = events(JsonField.of(events)) - - /** A list of fetched events */ - @JsonProperty("events") - @ExcludeMissing - fun events(events: JsonField>) = apply { this.events = events } - - 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(): ExperimentFetchResponse = - ExperimentFetchResponse( - events.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } - - @JsonDeserialize(builder = Event.Builder::class) - @NoAutoDetect - class Event - private constructor( - private val id: JsonField, - private val datasetRecordId: JsonField, - private val _xactId: JsonField, - private val created: JsonField, - private val projectId: JsonField, - private val experimentId: JsonField, - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanId: JsonField, - private val spanParents: JsonField>, - private val rootSpanId: JsonField, - private val spanAttributes: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): String = id.getRequired("id") - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - fun datasetRecordId(): Optional = - Optional.ofNullable(datasetRecordId.getNullable("dataset_record_id")) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - fun _xactId(): Long = _xactId.getRequired("_xact_id") - - /** The timestamp the experiment event was created */ - fun created(): Optional = - Optional.ofNullable(created.getNullable("created")) - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(): String = projectId.getRequired("project_id") - - /** Unique identifier for the experiment */ - fun experimentId(): String = experimentId.getRequired("experiment_id") - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). - * Later on, Braintrust will use the `input` to know whether two test cases are the same - * between experiments, so they should not contain experiment-specific state. A simple rule - * of thumb is that if you run the same experiment twice, the `input` should be identical - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question - */ - fun output(): JsonValue = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate your experiments - * while digging into analyses. However, we may later use these values to re-score outputs - * or fine-tune your models - */ - fun expected(): JsonValue = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare experiments - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * experiment event. Use "start" and "end" to track the time span over which the experiment - * event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) - - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) - - /** - * A unique identifier used to link different experiment events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - fun spanId(): String = spanId.getRequired("span_id") - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for the - * root span of a trace, and should most often contain just one parent element for subspans - */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) - - /** The `span_id` of the root of the trace this experiment event belongs to */ - fun rootSpanId(): String = rootSpanId.getRequired("root_span_id") - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - @JsonProperty("dataset_record_id") @ExcludeMissing fun _datasetRecordId() = datasetRecordId - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - @JsonProperty("_xact_id") @ExcludeMissing fun __xactId() = _xactId - - /** The timestamp the experiment event was created */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId - - /** Unique identifier for the experiment */ - @JsonProperty("experiment_id") @ExcludeMissing fun _experimentId() = experimentId - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). - * Later on, Braintrust will use the `input` to know whether two test cases are the same - * between experiments, so they should not contain experiment-specific state. A simple rule - * of thumb is that if you run the same experiment twice, the `input` should be identical - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate your experiments - * while digging into analyses. However, we may later use these values to re-score outputs - * or fine-tune your models - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare experiments - */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * experiment event. Use "start" and "end" to track the time span over which the experiment - * event was produced - */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics - - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context - - /** - * A unique identifier used to link different experiment events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - @JsonProperty("span_id") @ExcludeMissing fun _spanId() = spanId - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for the - * root span of a trace, and should most often contain just one parent element for subspans - */ - @JsonProperty("span_parents") @ExcludeMissing fun _spanParents() = spanParents - - /** The `span_id` of the root of the trace this experiment event belongs to */ - @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId() = rootSpanId - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Event = apply { - if (!validated) { - id() - datasetRecordId() - _xactId() - created() - projectId() - experimentId() - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanId() - spanParents() - rootSpanId() - spanAttributes().map { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Event && - this.id == other.id && - this.datasetRecordId == other.datasetRecordId && - this._xactId == other._xactId && - this.created == other.created && - this.projectId == other.projectId && - this.experimentId == other.experimentId && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanId == other.spanId && - this.spanParents == other.spanParents && - this.rootSpanId == other.rootSpanId && - this.spanAttributes == other.spanAttributes && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - datasetRecordId, - _xactId, - created, - projectId, - experimentId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents, - rootSpanId, - spanAttributes, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Event{id=$id, datasetRecordId=$datasetRecordId, _xactId=$_xactId, created=$created, projectId=$projectId, experimentId=$experimentId, input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanId=$spanId, spanParents=$spanParents, rootSpanId=$rootSpanId, spanAttributes=$spanAttributes, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var id: JsonField = JsonMissing.of() - private var datasetRecordId: JsonField = JsonMissing.of() - private var _xactId: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var experimentId: JsonField = JsonMissing.of() - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanId: JsonField = JsonMissing.of() - private var spanParents: JsonField> = JsonMissing.of() - private var rootSpanId: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(event: Event) = apply { - this.id = event.id - this.datasetRecordId = event.datasetRecordId - this._xactId = event._xactId - this.created = event.created - this.projectId = event.projectId - this.experimentId = event.experimentId - this.input = event.input - this.output = event.output - this.expected = event.expected - this.scores = event.scores - this.metadata = event.metadata - this.metrics = event.metrics - this.context = event.context - this.spanId = event.spanId - this.spanParents = event.spanParents - this.rootSpanId = event.rootSpanId - this.spanAttributes = event.spanAttributes - additionalProperties(event.additionalProperties) - } - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - fun datasetRecordId(datasetRecordId: String) = - datasetRecordId(JsonField.of(datasetRecordId)) - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - @JsonProperty("dataset_record_id") - @ExcludeMissing - fun datasetRecordId(datasetRecordId: JsonField) = apply { - this.datasetRecordId = datasetRecordId - } - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - fun _xactId(_xactId: Long) = _xactId(JsonField.of(_xactId)) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the experiment (see the `version` parameter) - */ - @JsonProperty("_xact_id") - @ExcludeMissing - fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } - - /** The timestamp the experiment event was created */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** The timestamp the experiment event was created */ - @JsonProperty("created") - @ExcludeMissing - fun created(created: JsonField) = apply { this.created = created } - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** Unique identifier for the experiment */ - fun experimentId(experimentId: String) = experimentId(JsonField.of(experimentId)) - - /** Unique identifier for the experiment */ - @JsonProperty("experiment_id") - @ExcludeMissing - fun experimentId(experimentId: JsonField) = apply { - this.experimentId = experimentId - } - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases are - * the same between experiments, so they should not contain experiment-specific state. A - * simple rule of thumb is that if you run the same experiment twice, the `input` should - * be identical - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * your experiments while digging into analyses. However, we may later use these values - * to re-score outputs or fine-tune your models - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** - * A unique identifier used to link different experiment events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - fun spanId(spanId: String) = spanId(JsonField.of(spanId)) - - /** - * A unique identifier used to link different experiment events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - @JsonProperty("span_id") - @ExcludeMissing - fun spanId(spanId: JsonField) = apply { this.spanId = spanId } - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - fun spanParents(spanParents: List) = spanParents(JsonField.of(spanParents)) - - /** - * An array of the parent `span_ids` of this experiment event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - @JsonProperty("span_parents") - @ExcludeMissing - fun spanParents(spanParents: JsonField>) = apply { - this.spanParents = spanParents - } - - /** The `span_id` of the root of the trace this experiment event belongs to */ - fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) - - /** The `span_id` of the root of the trace this experiment event belongs to */ - @JsonProperty("root_span_id") - @ExcludeMissing - fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - 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(): Event = - Event( - id, - datasetRecordId, - _xactId, - created, - projectId, - experimentId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents.map { it.toUnmodifiable() }, - rootSpanId, - spanAttributes, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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 - */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the experiment event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the experiment event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the experiment event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") @ExcludeMissing fun _callerFilename() = callerFilename - - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } - - /** The function in code which created the experiment event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) - - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } - - /** Name of the file in code where the experiment event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) - - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } - - /** Line of code where the experiment event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) - - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } - - 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(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * experiment event. Use "start" and "end" to track the time span over which the experiment - * event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare experiments - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } -} 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 old mode 100644 new mode 100755 index e96772ca..75c76af3 --- 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 @@ -2,3078 +2,469 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer 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.getOrThrow -import com.braintrustdata.api.core.toUnmodifiable +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.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Insert a set of events into the experiment */ class ExperimentInsertParams -constructor( - private val experimentId: String, - private val events: List, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun experimentId(): String = experimentId - - fun events(): List = events - - @JvmSynthetic - internal fun getBody(): ExperimentInsertBody { - return ExperimentInsertBody(events, additionalBodyProperties) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } - - @JsonDeserialize(builder = ExperimentInsertBody.Builder::class) - @NoAutoDetect - class ExperimentInsertBody - internal constructor( - private val events: List?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** A list of experiment events to insert */ - @JsonProperty("events") fun events(): List? = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentInsertBody && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ExperimentInsertBody{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: List? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentInsertBody: ExperimentInsertBody) = apply { - this.events = experimentInsertBody.events - additionalProperties(experimentInsertBody.additionalProperties) - } - - /** A list of experiment events to insert */ - @JsonProperty("events") fun events(events: List) = apply { this.events = events } - - 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(): ExperimentInsertBody = - ExperimentInsertBody( - checkNotNull(events) { "`events` is required but was not set" } - .toUnmodifiable(), - additionalProperties.toUnmodifiable() - ) - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentInsertParams && - this.experimentId == other.experimentId && - this.events == other.events && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int { - return Objects.hash( - experimentId, - events, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "ExperimentInsertParams{experimentId=$experimentId, events=$events, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" +private constructor( + private val experimentId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) + + /** + * 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 = body.events() + + /** + * Returns the raw JSON value of [events]. + * + * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _events(): JsonField> = body._events() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [ExperimentInsertParams]. + * + * The following fields are required: + * ```java + * .events() + * ``` + */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ExperimentInsertParams]. */ + class Builder internal constructor() { private var experimentId: String? = null - private var events: MutableList = mutableListOf() - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + 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(experimentInsertParams: ExperimentInsertParams) = apply { - this.experimentId = experimentInsertParams.experimentId - this.events(experimentInsertParams.events) - additionalQueryParams(experimentInsertParams.additionalQueryParams) - additionalHeaders(experimentInsertParams.additionalHeaders) - additionalBodyProperties(experimentInsertParams.additionalBodyProperties) + experimentId = experimentInsertParams.experimentId + body = experimentInsertParams.body.toBuilder() + additionalHeaders = experimentInsertParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentInsertParams.additionalQueryParams.toBuilder() } /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } - /** A list of experiment events to insert */ - fun events(events: List) = apply { - this.events.clear() - this.events.addAll(events) - } + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [events] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } /** A list of experiment events to insert */ - fun addEvent(event: Event) = apply { this.events.add(event) } + fun events(events: List) = apply { body.events(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 { body.events(events) } + + /** + * Adds a single [InsertExperimentEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: InsertExperimentEvent) = apply { body.addEvent(event) } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } fun additionalHeaders(additionalHeaders: Map>) = apply { this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + putAllAdditionalHeaders(additionalHeaders) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun build(): ExperimentInsertParams = - ExperimentInsertParams( - checkNotNull(experimentId) { "`experimentId` is required but was not set" }, - checkNotNull(events) { "`events` is required but was not set" }.toUnmodifiable(), - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } - - @JsonDeserialize(using = Event.Deserializer::class) - @JsonSerialize(using = Event.Serializer::class) - class Event - private constructor( - private val insertExperimentEventReplace: InsertExperimentEventReplace? = null, - private val insertExperimentEventMerge: InsertExperimentEventMerge? = null, - private val _json: JsonValue? = null, - ) { - - private var validated: Boolean = false - - fun insertExperimentEventReplace(): Optional = - Optional.ofNullable(insertExperimentEventReplace) - fun insertExperimentEventMerge(): Optional = - Optional.ofNullable(insertExperimentEventMerge) - - fun isInsertExperimentEventReplace(): Boolean = insertExperimentEventReplace != null - fun isInsertExperimentEventMerge(): Boolean = insertExperimentEventMerge != null - - fun asInsertExperimentEventReplace(): InsertExperimentEventReplace = - insertExperimentEventReplace.getOrThrow("insertExperimentEventReplace") - fun asInsertExperimentEventMerge(): InsertExperimentEventMerge = - insertExperimentEventMerge.getOrThrow("insertExperimentEventMerge") - - fun _json(): Optional = Optional.ofNullable(_json) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun accept(visitor: Visitor): T { - return when { - insertExperimentEventReplace != null -> - visitor.visitInsertExperimentEventReplace(insertExperimentEventReplace) - insertExperimentEventMerge != null -> - visitor.visitInsertExperimentEventMerge(insertExperimentEventMerge) - else -> visitor.unknown(_json) - } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun validate(): Event = apply { - if (!validated) { - if (insertExperimentEventReplace == null && insertExperimentEventMerge == null) { - throw BraintrustInvalidDataException("Unknown Event: $_json") - } - insertExperimentEventReplace?.validate() - insertExperimentEventMerge?.validate() - validated = true - } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - return other is Event && - this.insertExperimentEventReplace == other.insertExperimentEventReplace && - this.insertExperimentEventMerge == other.insertExperimentEventMerge + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - override fun hashCode(): Int { - return Objects.hash(insertExperimentEventReplace, insertExperimentEventMerge) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - override fun toString(): String { - return when { - insertExperimentEventReplace != null -> - "Event{insertExperimentEventReplace=$insertExperimentEventReplace}" - insertExperimentEventMerge != null -> - "Event{insertExperimentEventMerge=$insertExperimentEventMerge}" - _json != null -> "Event{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Event") - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - companion object { - - @JvmStatic - fun ofInsertExperimentEventReplace( - insertExperimentEventReplace: InsertExperimentEventReplace - ) = Event(insertExperimentEventReplace = insertExperimentEventReplace) - - @JvmStatic - fun ofInsertExperimentEventMerge( - insertExperimentEventMerge: InsertExperimentEventMerge - ) = Event(insertExperimentEventMerge = insertExperimentEventMerge) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - interface Visitor { - - fun visitInsertExperimentEventReplace( - insertExperimentEventReplace: InsertExperimentEventReplace - ): T + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - fun visitInsertExperimentEventMerge( - insertExperimentEventMerge: InsertExperimentEventMerge - ): T + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Event: $json") + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - } - class Deserializer : BaseDeserializer(Event::class) { + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - override fun ObjectCodec.deserialize(node: JsonNode): Event { - val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return Event(insertExperimentEventReplace = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Event(insertExperimentEventMerge = it, _json = json) - } + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - return Event(_json = json) - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - class Serializer : BaseSerializer(Event::class) { - - override fun serialize( - value: Event, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.insertExperimentEventReplace != null -> - generator.writeObject(value.insertExperimentEventReplace) - value.insertExperimentEventMerge != null -> - generator.writeObject(value.insertExperimentEventMerge) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Event") - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - } - @JsonDeserialize(builder = InsertExperimentEventReplace.Builder::class) - @NoAutoDetect - class InsertExperimentEventReplace - private constructor( - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanAttributes: JsonField, - private val id: JsonField, - private val datasetRecordId: JsonField, - private val _objectDelete: JsonField, - private val _isMerge: JsonField, - private val _parentId: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases are - * the same between experiments, so they should not contain experiment-specific state. A - * simple rule of thumb is that if you run the same experiment twice, the `input` should - * be identical - */ - fun input(): JsonValue = input + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question - */ - fun output(): JsonValue = output + /** + * Returns an immutable instance of [ExperimentInsertParams]. + * + * 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(): ExperimentInsertParams = + ExperimentInsertParams( + experimentId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * your experiments while digging into analyses. However, we may later use these values - * to re-score outputs or fine-tune your models - */ - fun expected(): JsonValue = expected + fun _body(): Body = body - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) + fun _pathParam(index: Int): String = + when (index) { + 0 -> experimentId ?: "" + else -> "" + } - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) + override fun _headers(): Headers = additionalHeaders - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) + override fun _queryParams(): QueryParams = additionalQueryParams - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val events: JsonField>, + private val additionalProperties: MutableMap, + ) { - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) + @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 - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - fun datasetRecordId(): Optional = - Optional.ofNullable(datasetRecordId.getNullable("dataset_record_id")) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events will - * not show up in subsequent fetches for this experiment - */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) + fun toBuilder() = Builder().from(this) - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - fun _isMerge(): Optional = - Optional.ofNullable(_isMerge.getNullable("_is_merge")) + companion object { /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical relationships - * are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). + * Returns a mutable builder for constructing an instance of [Body]. * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", - * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the - * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": - * "What comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, - * only the root span row `"abc"` will show up in the summary view. You can view the - * full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" - * row. - */ - fun _parentId(): Optional = - Optional.ofNullable(_parentId.getNullable("_parent_id")) - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases are - * the same between experiments, so they should not contain experiment-specific state. A - * simple rule of thumb is that if you run the same experiment twice, the `input` should - * be identical - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * your experiments while digging into analyses. However, we may later use these values - * to re-score outputs or fine-tune your models - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced + * The following fields are required: + * ```java + * .events() + * ``` */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics - - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context + @JvmStatic fun builder() = Builder() + } - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes + /** A builder for [Body]. */ + class Builder internal constructor() { - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id + private var events: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - @JsonProperty("dataset_record_id") - @ExcludeMissing - fun _datasetRecordId() = datasetRecordId + @JvmSynthetic + internal fun from(body: Body) = apply { + events = body.events.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events will - * not show up in subsequent fetches for this experiment - */ - @JsonProperty("_object_delete") @ExcludeMissing fun __objectDelete() = _objectDelete + /** A list of experiment events to insert */ + fun events(events: List) = events(JsonField.of(events)) /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row + * Sets [Builder.events] to an arbitrary JSON value. * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` + * 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. */ - @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge() = _isMerge + fun events(events: JsonField>) = apply { + this.events = events.map { it.toMutableList() } + } /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical relationships - * are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). + * Adds a single [InsertExperimentEvent] to [events]. * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", - * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the - * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": - * "What comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, - * only the root span row `"abc"` will show up in the summary view. You can view the - * full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" - * row. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("_parent_id") @ExcludeMissing fun __parentId() = _parentId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): InsertExperimentEventReplace = apply { - if (!validated) { - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanAttributes().map { it.validate() } - id() - datasetRecordId() - _objectDelete() - _isMerge() - _parentId() - validated = true - } + fun addEvent(event: InsertExperimentEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InsertExperimentEventReplace && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanAttributes == other.spanAttributes && - this.id == other.id && - this.datasetRecordId == other.datasetRecordId && - this._objectDelete == other._objectDelete && - this._isMerge == other._isMerge && - this._parentId == other._parentId && - this.additionalProperties == other.additionalProperties + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - datasetRecordId, - _objectDelete, - _isMerge, - _parentId, - additionalProperties, - ) - } - return hashCode + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) } - override fun toString() = - "InsertExperimentEventReplace{input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanAttributes=$spanAttributes, id=$id, datasetRecordId=$datasetRecordId, _objectDelete=$_objectDelete, _isMerge=$_isMerge, _parentId=$_parentId, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) } - class Builder { - - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var id: JsonField = JsonMissing.of() - private var datasetRecordId: JsonField = JsonMissing.of() - private var _objectDelete: JsonField = JsonMissing.of() - private var _isMerge: JsonField = JsonMissing.of() - private var _parentId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(insertExperimentEventReplace: InsertExperimentEventReplace) = - apply { - this.input = insertExperimentEventReplace.input - this.output = insertExperimentEventReplace.output - this.expected = insertExperimentEventReplace.expected - this.scores = insertExperimentEventReplace.scores - this.metadata = insertExperimentEventReplace.metadata - this.metrics = insertExperimentEventReplace.metrics - this.context = insertExperimentEventReplace.context - this.spanAttributes = insertExperimentEventReplace.spanAttributes - this.id = insertExperimentEventReplace.id - this.datasetRecordId = insertExperimentEventReplace.datasetRecordId - this._objectDelete = insertExperimentEventReplace._objectDelete - this._isMerge = insertExperimentEventReplace._isMerge - this._parentId = insertExperimentEventReplace._parentId - additionalProperties(insertExperimentEventReplace.additionalProperties) - } - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases - * are the same between experiments, so they should not contain experiment-specific - * state. A simple rule of thumb is that if you run the same experiment twice, the - * `input` should be identical - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct - * or not. For example, in an app that generates SQL queries, the `output` should be - * the _result_ of the SQL query generated by the model, not the query itself, - * because there may be multiple valid queries that answer a single question - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd - * compare to `output` to determine if your `output` value is correct or not. - * Braintrust currently does not compare `output` to `expected` for you, since there - * are so many different ways to do that correctly. Instead, these values are just - * used to help you navigate your experiments while digging into analyses. However, - * we may later use these values to re-score outputs or fine-tune your models - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare experiments - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare experiments - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the experiment event. Use "start" and "end" to track the time span over - * which the experiment event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the experiment event. Use "start" and "end" to track the time span over - * which the experiment event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - /** - * A unique identifier for the experiment event. If you don't provide one, - * BrainTrust will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the experiment event. If you don't provide one, - * BrainTrust will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id - * this experiment event is tied to - */ - fun datasetRecordId(datasetRecordId: String) = - datasetRecordId(JsonField.of(datasetRecordId)) - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id - * this experiment event is tied to - */ - @JsonProperty("dataset_record_id") - @ExcludeMissing - fun datasetRecordId(datasetRecordId: JsonField) = apply { - this.datasetRecordId = datasetRecordId - } - - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events - * will not show up in subsequent fetches for this experiment - */ - fun _objectDelete(_objectDelete: Boolean) = - _objectDelete(JsonField.of(_objectDelete)) - - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events - * will not show up in subsequent fetches for this experiment - */ - @JsonProperty("_object_delete") - @ExcludeMissing - fun _objectDelete(_objectDelete: JsonField) = apply { - this._objectDelete = _objectDelete - } - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - fun _isMerge(_isMerge: Boolean) = _isMerge(JsonField.of(_isMerge)) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - @JsonProperty("_is_merge") - @ExcludeMissing - fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } - - /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical - * relationships are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). - * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": - * "bar", "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a - * sub-span of the parent row by logging `{"_parent_id": "abc", "id": "llm_call", - * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": - * {"tokens": 1}}`. In the webapp, only the root span row `"abc"` will show up in - * the summary view. You can view the full trace hierarchy (in this case, the - * `"llm_call"` row) by clicking on the "abc" row. - */ - fun _parentId(_parentId: String) = _parentId(JsonField.of(_parentId)) - - /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical - * relationships are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). - * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": - * "bar", "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a - * sub-span of the parent row by logging `{"_parent_id": "abc", "id": "llm_call", - * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": - * {"tokens": 1}}`. In the webapp, only the root span row `"abc"` will show up in - * the summary view. You can view the full trace hierarchy (in this case, the - * `"llm_call"` row) by clicking on the "abc" row. - */ - @JsonProperty("_parent_id") - @ExcludeMissing - fun _parentId(_parentId: JsonField) = apply { this._parentId = _parentId } - - 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 removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun build(): InsertExperimentEventReplace = - InsertExperimentEventReplace( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - datasetRecordId, - _objectDelete, - _isMerge, - _parentId, - additionalProperties.toUnmodifiable(), - ) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } /** - * 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 + * 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. */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the experiment event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the experiment event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the experiment event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun _callerFilename() = callerFilename - - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } + fun build(): Body = + Body( + checkRequired("events", events).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" + private var validated: Boolean = false - companion object { + fun validate(): Body = apply { + if (validated) { + return@apply + } - @JvmStatic fun builder() = Builder() - } + events().forEach { it.validate() } + validated = true + } - class Builder { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (events.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - /** The function in code which created the experiment event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) + return other is Body && + events == other.events && + additionalProperties == other.additionalProperties + } - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } + private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } - /** Name of the file in code where the experiment event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) + override fun hashCode(): Int = hashCode - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } + override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" + } - /** Line of code where the experiment event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } + return other is ExperimentInsertParams && + experimentId == other.experimentId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + override fun hashCode(): Int = + Objects.hash(experimentId, body, additionalHeaders, additionalQueryParams) - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue - fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } - - @JsonDeserialize(builder = InsertExperimentEventMerge.Builder::class) - @NoAutoDetect - class InsertExperimentEventMerge - private constructor( - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanAttributes: JsonField, - private val id: JsonField, - private val datasetRecordId: JsonField, - private val _objectDelete: JsonField, - private val _isMerge: JsonField, - private val _mergePaths: JsonField>>, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases are - * the same between experiments, so they should not contain experiment-specific state. A - * simple rule of thumb is that if you run the same experiment twice, the `input` should - * be identical - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question - */ - fun output(): JsonValue = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * your experiments while digging into analyses. However, we may later use these values - * to re-score outputs or fine-tune your models - */ - fun expected(): JsonValue = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) - - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - fun datasetRecordId(): Optional = - Optional.ofNullable(datasetRecordId.getNullable("dataset_record_id")) - - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events will - * not show up in subsequent fetches for this experiment - */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - fun _isMerge(): Boolean = _isMerge.getRequired("_is_merge") - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only be - * specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where each - * path is a list of field names. The deep merge will not descend below any of the - * specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be - * `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, - * "output": {"d": 40}}`. In this case, due to the merge paths, we have replaced - * `input.a` and `output`, but have still deep-merged `input` and `input.c`. - */ - fun _mergePaths(): Optional>> = - Optional.ofNullable(_mergePaths.getNullable("_merge_paths")) - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases are - * the same between experiments, so they should not contain experiment-specific state. A - * simple rule of thumb is that if you run the same experiment twice, the `input` should - * be identical - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * your experiments while digging into analyses. However, we may later use these values - * to re-score outputs or fine-tune your models - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics - - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes - - /** - * A unique identifier for the experiment event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id this - * experiment event is tied to - */ - @JsonProperty("dataset_record_id") - @ExcludeMissing - fun _datasetRecordId() = datasetRecordId - - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events will - * not show up in subsequent fetches for this experiment - */ - @JsonProperty("_object_delete") @ExcludeMissing fun __objectDelete() = _objectDelete - - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge() = _isMerge - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only be - * specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where each - * path is a list of field names. The deep merge will not descend below any of the - * specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be - * `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, - * "output": {"d": 40}}`. In this case, due to the merge paths, we have replaced - * `input.a` and `output`, but have still deep-merged `input` and `input.c`. - */ - @JsonProperty("_merge_paths") @ExcludeMissing fun __mergePaths() = _mergePaths - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): InsertExperimentEventMerge = apply { - if (!validated) { - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanAttributes().map { it.validate() } - id() - datasetRecordId() - _objectDelete() - _isMerge() - _mergePaths() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InsertExperimentEventMerge && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanAttributes == other.spanAttributes && - this.id == other.id && - this.datasetRecordId == other.datasetRecordId && - this._objectDelete == other._objectDelete && - this._isMerge == other._isMerge && - this._mergePaths == other._mergePaths && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - datasetRecordId, - _objectDelete, - _isMerge, - _mergePaths, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "InsertExperimentEventMerge{input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanAttributes=$spanAttributes, id=$id, datasetRecordId=$datasetRecordId, _objectDelete=$_objectDelete, _isMerge=$_isMerge, _mergePaths=$_mergePaths, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var id: JsonField = JsonMissing.of() - private var datasetRecordId: JsonField = JsonMissing.of() - private var _objectDelete: JsonField = JsonMissing.of() - private var _isMerge: JsonField = JsonMissing.of() - private var _mergePaths: JsonField>> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(insertExperimentEventMerge: InsertExperimentEventMerge) = apply { - this.input = insertExperimentEventMerge.input - this.output = insertExperimentEventMerge.output - this.expected = insertExperimentEventMerge.expected - this.scores = insertExperimentEventMerge.scores - this.metadata = insertExperimentEventMerge.metadata - this.metrics = insertExperimentEventMerge.metrics - this.context = insertExperimentEventMerge.context - this.spanAttributes = insertExperimentEventMerge.spanAttributes - this.id = insertExperimentEventMerge.id - this.datasetRecordId = insertExperimentEventMerge.datasetRecordId - this._objectDelete = insertExperimentEventMerge._objectDelete - this._isMerge = insertExperimentEventMerge._isMerge - this._mergePaths = insertExperimentEventMerge._mergePaths - additionalProperties(insertExperimentEventMerge.additionalProperties) - } - - /** - * The arguments that uniquely define a test case (an arbitrary, JSON serializable - * object). Later on, Braintrust will use the `input` to know whether two test cases - * are the same between experiments, so they should not contain experiment-specific - * state. A simple rule of thumb is that if you run the same experiment twice, the - * `input` should be identical - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct - * or not. For example, in an app that generates SQL queries, the `output` should be - * the _result_ of the SQL query generated by the model, not the query itself, - * because there may be multiple valid queries that answer a single question - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd - * compare to `output` to determine if your `output` value is correct or not. - * Braintrust currently does not compare `output` to `expected` for you, since there - * are so many different ways to do that correctly. Instead, these values are just - * used to help you navigate your experiments while digging into analyses. However, - * we may later use these values to re-score outputs or fine-tune your models - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare experiments - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare experiments - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the experiment event. Use "start" and "end" to track the time span over - * which the experiment event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the experiment event. Use "start" and "end" to track the time span over - * which the experiment event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - /** - * A unique identifier for the experiment event. If you don't provide one, - * BrainTrust will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the experiment event. If you don't provide one, - * BrainTrust will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id - * this experiment event is tied to - */ - fun datasetRecordId(datasetRecordId: String) = - datasetRecordId(JsonField.of(datasetRecordId)) - - /** - * If the experiment is associated to a dataset, this is the event-level dataset id - * this experiment event is tied to - */ - @JsonProperty("dataset_record_id") - @ExcludeMissing - fun datasetRecordId(datasetRecordId: JsonField) = apply { - this.datasetRecordId = datasetRecordId - } - - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events - * will not show up in subsequent fetches for this experiment - */ - fun _objectDelete(_objectDelete: Boolean) = - _objectDelete(JsonField.of(_objectDelete)) - - /** - * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events - * will not show up in subsequent fetches for this experiment - */ - @JsonProperty("_object_delete") - @ExcludeMissing - fun _objectDelete(_objectDelete: JsonField) = apply { - this._objectDelete = _objectDelete - } - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - fun _isMerge(_isMerge: Boolean) = _isMerge(JsonField.of(_isMerge)) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - @JsonProperty("_is_merge") - @ExcludeMissing - fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only - * be specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where - * each path is a list of field names. The deep merge will not descend below any of - * the specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will - * be `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": - * "baz"}, "output": {"d": 40}}`. In this case, due to the merge paths, we have - * replaced `input.a` and `output`, but have still deep-merged `input` and - * `input.c`. - */ - fun _mergePaths(_mergePaths: List>) = - _mergePaths(JsonField.of(_mergePaths)) - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only - * be specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where - * each path is a list of field names. The deep merge will not descend below any of - * the specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will - * be `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": - * "baz"}, "output": {"d": 40}}`. In this case, due to the merge paths, we have - * replaced `input.a` and `output`, but have still deep-merged `input` and - * `input.c`. - */ - @JsonProperty("_merge_paths") - @ExcludeMissing - fun _mergePaths(_mergePaths: JsonField>>) = apply { - this._mergePaths = _mergePaths - } - - 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(): InsertExperimentEventMerge = - InsertExperimentEventMerge( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - datasetRecordId, - _objectDelete, - _isMerge, - _mergePaths.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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 - */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the experiment event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the experiment event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the experiment event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun _callerFilename() = callerFilename - - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } - - /** The function in code which created the experiment event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) - - /** The function in code which created the experiment event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } - - /** Name of the file in code where the experiment event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) - - /** Name of the file in code where the experiment event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } - - /** Line of code where the experiment event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) - - /** Line of code where the experiment event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } - - 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(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the experiment event. Use "start" and "end" to track the time span over which the - * experiment event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the experiment - * event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the - * experiment event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare - * experiments - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue - fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } - } + override fun toString() = + "ExperimentInsertParams{experimentId=$experimentId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentInsertResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentInsertResponse.kt deleted file mode 100644 index 671b2e20..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentInsertResponse.kt +++ /dev/null @@ -1,122 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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.Objects - -@JsonDeserialize(builder = ExperimentInsertResponse.Builder::class) -@NoAutoDetect -class ExperimentInsertResponse -private constructor( - private val rowIds: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as input - */ - fun rowIds(): List = rowIds.getRequired("row_ids") - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as input - */ - @JsonProperty("row_ids") @ExcludeMissing fun _rowIds() = rowIds - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): ExperimentInsertResponse = apply { - if (!validated) { - rowIds() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentInsertResponse && - this.rowIds == other.rowIds && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(rowIds, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ExperimentInsertResponse{rowIds=$rowIds, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var rowIds: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentInsertResponse: ExperimentInsertResponse) = apply { - this.rowIds = experimentInsertResponse.rowIds - additionalProperties(experimentInsertResponse.additionalProperties) - } - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as - * input - */ - fun rowIds(rowIds: List) = rowIds(JsonField.of(rowIds)) - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as - * input - */ - @JsonProperty("row_ids") - @ExcludeMissing - fun rowIds(rowIds: JsonField>) = apply { this.rowIds = rowIds } - - 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(): ExperimentInsertResponse = - ExperimentInsertResponse( - rowIds.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } -} 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 old mode 100644 new mode 100755 index 4af79884..6bed69f4 --- 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,196 +2,124 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +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.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull +/** @see ExperimentService.list */ class ExperimentListPage private constructor( - private val experimentService: ExperimentService, + private val service: ExperimentService, private val params: ExperimentListParams, - private val response: Response, -) { + private val response: ExperimentListPageResponse, +) : Page { - 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 items(): List = objects() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentListPage && - this.experimentService == other.experimentService && - this.params == other.params && - this.response == other.response - } - - override fun hashCode(): Int { - return Objects.hash( - experimentService, - params, - response, - ) - } - - override fun toString() = - "ExperimentListPage{experimentService=$experimentService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + override fun hasNextPage(): Boolean = items().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() - ) + fun nextPageParams(): ExperimentListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() } else { - Optional.of( - ExperimentListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() } - } - - fun getNextPage(): Optional { - return getNextPageParams().map { experimentService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of( - experimentService: ExperimentService, - params: ExperimentListParams, - response: Response - ) = - ExperimentListPage( - experimentService, - params, - response, - ) - } - @JsonDeserialize(builder = Response.Builder::class) - @NoAutoDetect - class Response - constructor( - private val objects: JsonField>, - private val additionalProperties: Map, - ) { + override fun nextPage(): ExperimentListPage = service.list(nextPageParams()) - private var validated: Boolean = false + fun autoPager(): AutoPager = AutoPager.from(this) - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The parameters that were used to request this page. */ + fun params(): ExperimentListParams = params - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) + /** The response that this page was parsed from. */ + fun response(): ExperimentListPageResponse = response - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun toBuilder() = Builder().from(this) - fun validate(): Response = apply { - if (!validated) { - objects().map { it.validate() } - validated = true - } - } + companion object { - fun toBuilder() = Builder().from(this) + /** + * 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 equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** A builder for [ExperimentListPage]. */ + class Builder internal constructor() { - return other is Response && - this.objects == other.objects && - this.additionalProperties == other.additionalProperties - } + private var service: ExperimentService? = null + private var params: ExperimentListParams? = null + private var response: ExperimentListPageResponse? = null - override fun hashCode(): Int { - return Objects.hash(objects, additionalProperties) + @JvmSynthetic + internal fun from(experimentListPage: ExperimentListPage) = apply { + service = experimentListPage.service + params = experimentListPage.params + response = experimentListPage.response } - override fun toString() = - "ExperimentListPage.Response{objects=$objects, additionalProperties=$additionalProperties}" - - companion object { + 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), + ) + } - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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)) - - @JsonProperty("objects") - fun objects(objects: JsonField>) = apply { this.objects = objects } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(objects, additionalProperties.toUnmodifiable()) - } + return other is ExperimentListPage && + service == other.service && + params == other.params && + response == other.response } - class AutoPager - constructor( - private val firstPage: ExperimentListPage, - ) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.objects().size) { - yield(page.objects()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } + override fun hashCode(): Int = Objects.hash(service, params, response) - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } + 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 old mode 100644 new mode 100755 index c195d450..f4109fe6 --- 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,206 +2,138 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +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.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize 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 +/** @see ExperimentServiceAsync.list */ class ExperimentListPageAsync private constructor( - private val experimentService: ExperimentServiceAsync, + private val service: ExperimentServiceAsync, + private val streamHandlerExecutor: Executor, private val params: ExperimentListParams, - private val response: Response, -) { + private val response: ExperimentListPageResponse, +) : PageAsync { - 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 items(): List = objects() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentListPageAsync && - this.experimentService == other.experimentService && - this.params == other.params && - this.response == other.response - } - - override fun hashCode(): Int { - return Objects.hash( - experimentService, - params, - response, - ) - } - - override fun toString() = - "ExperimentListPageAsync{experimentService=$experimentService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } + override fun hasNextPage(): Boolean = items().isNotEmpty() - return if (params.endingBefore().isPresent) { - Optional.of( - ExperimentListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) + fun nextPageParams(): ExperimentListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() } else { - Optional.of( - ExperimentListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() } - } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { experimentService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) - fun autoPager(): AutoPager = AutoPager(this) + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) - companion object { + /** The parameters that were used to request this page. */ + fun params(): ExperimentListParams = params - @JvmStatic - fun of( - experimentService: ExperimentServiceAsync, - params: ExperimentListParams, - response: Response - ) = - ExperimentListPageAsync( - experimentService, - params, - response, - ) - } + /** The response that this page was parsed from. */ + fun response(): ExperimentListPageResponse = response - @JsonDeserialize(builder = Response.Builder::class) - @NoAutoDetect - class Response - constructor( - private val objects: JsonField>, - private val additionalProperties: Map, - ) { + fun toBuilder() = Builder().from(this) - private var validated: Boolean = false + companion object { - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** + * Returns a mutable builder for constructing an instance of [ExperimentListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) + /** A builder for [ExperimentListPageAsync]. */ + class Builder internal constructor() { - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + private var service: ExperimentServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ExperimentListParams? = null + private var response: ExperimentListPageResponse? = null - fun validate(): Response = apply { - if (!validated) { - objects().map { it.validate() } - validated = true - } + @JvmSynthetic + internal fun from(experimentListPageAsync: ExperimentListPageAsync) = apply { + service = experimentListPageAsync.service + streamHandlerExecutor = experimentListPageAsync.streamHandlerExecutor + params = experimentListPageAsync.params + response = experimentListPageAsync.response } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Response && - this.objects == other.objects && - this.additionalProperties == other.additionalProperties - } + fun service(service: ExperimentServiceAsync) = apply { this.service = service } - override fun hashCode(): Int { - return Objects.hash(objects, additionalProperties) + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor } - override fun toString() = - "ExperimentListPageAsync.Response{objects=$objects, additionalProperties=$additionalProperties}" - - companion object { + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ExperimentListPageAsync = + ExperimentListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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)) - - @JsonProperty("objects") - fun objects(objects: JsonField>) = apply { this.objects = objects } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(objects, additionalProperties.toUnmodifiable()) - } + return other is ExperimentListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response } - class AutoPager - constructor( - private val firstPage: ExperimentListPageAsync, - ) { - - fun forEach(action: Predicate, executor: Executor): CompletableFuture { - fun CompletableFuture>.forEach( - action: (Experiment) -> Boolean, - executor: Executor - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.objects().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } + override fun toString() = + "ExperimentListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..4e931a3d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is ExperimentListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 old mode 100644 new mode 100755 index 92b5445b..3de2aa0c --- 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,194 +2,433 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +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.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * List out all experiments. The experiments are sorted by creation date, with the most + * recently-created experiments coming first + */ class ExperimentListParams -constructor( +private constructor( private val endingBefore: String?, private val experimentName: String?, + private val ids: Ids?, private val limit: Long?, private val orgName: String?, + private val projectId: String?, private val projectName: String?, private val startingAfter: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { - + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + /** Name of the experiment to search for */ fun experimentName(): Optional = Optional.ofNullable(experimentName) + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ fun limit(): Optional = Optional.ofNullable(limit) + /** Filter search results to within a particular organization */ fun orgName(): Optional = Optional.ofNullable(orgName) + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** Name of the project to search for */ fun projectName(): Optional = Optional.ofNullable(projectName) + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ fun startingAfter(): Optional = Optional.ofNullable(startingAfter) - @JvmSynthetic - internal fun getQueryParams(): Map> { - val params = mutableMapOf>() - this.endingBefore?.let { params.put("ending_before", listOf(it.toString())) } - this.experimentName?.let { params.put("experiment_name", listOf(it.toString())) } - this.limit?.let { params.put("limit", listOf(it.toString())) } - this.orgName?.let { params.put("org_name", listOf(it.toString())) } - this.projectName?.let { params.put("project_name", listOf(it.toString())) } - this.startingAfter?.let { params.put("starting_after", listOf(it.toString())) } - params.putAll(additionalQueryParams) - return params.toUnmodifiable() - } - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun _additionalQueryParams(): Map> = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - fun _additionalHeaders(): Map> = additionalHeaders - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentListParams && - this.endingBefore == other.endingBefore && - this.experimentName == other.experimentName && - this.limit == other.limit && - this.orgName == other.orgName && - this.projectName == other.projectName && - this.startingAfter == other.startingAfter && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } - - override fun hashCode(): Int { - return Objects.hash( - endingBefore, - experimentName, - limit, - orgName, - projectName, - startingAfter, - additionalQueryParams, - additionalHeaders, - ) - } - - override fun toString() = - "ExperimentListParams{endingBefore=$endingBefore, experimentName=$experimentName, limit=$limit, orgName=$orgName, projectName=$projectName, startingAfter=$startingAfter, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ExperimentListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ExperimentListParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ExperimentListParams]. */ + class Builder internal constructor() { private var endingBefore: String? = null private var experimentName: String? = null + private var ids: Ids? = null private var limit: Long? = null private var orgName: String? = null + private var projectId: String? = null private var projectName: String? = null private var startingAfter: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(experimentListParams: ExperimentListParams) = apply { - this.endingBefore = experimentListParams.endingBefore - this.experimentName = experimentListParams.experimentName - this.limit = experimentListParams.limit - this.orgName = experimentListParams.orgName - this.projectName = experimentListParams.projectName - this.startingAfter = experimentListParams.startingAfter - additionalQueryParams(experimentListParams.additionalQueryParams) - additionalHeaders(experimentListParams.additionalHeaders) + endingBefore = experimentListParams.endingBefore + experimentName = experimentListParams.experimentName + ids = experimentListParams.ids + limit = experimentListParams.limit + orgName = experimentListParams.orgName + projectId = experimentListParams.projectId + projectName = experimentListParams.projectName + startingAfter = experimentListParams.startingAfter + additionalHeaders = experimentListParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentListParams.additionalQueryParams.toBuilder() } /** - * A cursor for pagination. For example, if the initial item in the last page you fetched - * had an id of `foo`, pass `ending_before=foo` to fetch the previous page. Note: you may - * only pass one of `starting_after` and `ending_before` + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` */ - fun endingBefore(endingBefore: String) = apply { this.endingBefore = endingBefore } + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) /** Name of the experiment to search for */ - fun experimentName(experimentName: String) = apply { this.experimentName = experimentName } + fun experimentName(experimentName: String?) = apply { this.experimentName = experimentName } + + /** Alias for calling [Builder.experimentName] with `experimentName.orElse(null)`. */ + fun experimentName(experimentName: Optional) = + experimentName(experimentName.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) /** Limit the number of objects to return */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(limit: Long?) = apply { this.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()) /** Filter search results to within a particular organization */ - fun orgName(orgName: String) = apply { this.orgName = orgName } + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) /** Name of the project to search for */ - fun projectName(projectName: String) = apply { this.projectName = projectName } + fun projectName(projectName: String?) = apply { this.projectName = projectName } + + /** Alias for calling [Builder.projectName] with `projectName.orElse(null)`. */ + fun projectName(projectName: Optional) = projectName(projectName.getOrNull()) /** - * A cursor for pagination. For example, if the final item in the last page you fetched had - * an id of `foo`, pass `starting_after=foo` to fetch the next page. Note: you may only pass - * one of `starting_after` and `ending_before` + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` */ - fun startingAfter(startingAfter: String) = apply { this.startingAfter = startingAfter } + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [ExperimentListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ExperimentListParams = ExperimentListParams( endingBefore, experimentName, + ids, limit, orgName, + projectId, projectName, startingAfter, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExperimentListParams && + endingBefore == other.endingBefore && + experimentName == other.experimentName && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + projectId == other.projectId && + projectName == other.projectName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + experimentName, + ids, + limit, + orgName, + projectId, + projectName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ExperimentListParams{endingBefore=$endingBefore, experimentName=$experimentName, ids=$ids, limit=$limit, orgName=$orgName, projectId=$projectId, projectName=$projectName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentReplaceParams.kt deleted file mode 100644 index 81dd8578..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentReplaceParams.kt +++ /dev/null @@ -1,724 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -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.toUnmodifiable -import com.braintrustdata.api.models.* -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.Objects -import java.util.Optional - -class ExperimentReplaceParams -constructor( - private val projectId: String, - private val baseExpId: String?, - private val datasetId: String?, - private val datasetVersion: String?, - private val description: String?, - private val metadata: Metadata?, - private val name: String?, - private val public_: Boolean?, - private val repoInfo: RepoInfo?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun projectId(): String = projectId - - fun baseExpId(): Optional = Optional.ofNullable(baseExpId) - - fun datasetId(): Optional = Optional.ofNullable(datasetId) - - fun datasetVersion(): Optional = Optional.ofNullable(datasetVersion) - - fun description(): Optional = Optional.ofNullable(description) - - fun metadata(): Optional = Optional.ofNullable(metadata) - - fun name(): Optional = Optional.ofNullable(name) - - fun public_(): Optional = Optional.ofNullable(public_) - - fun repoInfo(): Optional = Optional.ofNullable(repoInfo) - - @JvmSynthetic - internal fun getBody(): ExperimentReplaceBody { - return ExperimentReplaceBody( - projectId, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalBodyProperties, - ) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - @JsonDeserialize(builder = ExperimentReplaceBody.Builder::class) - @NoAutoDetect - class ExperimentReplaceBody - internal constructor( - private val projectId: String?, - private val baseExpId: String?, - private val datasetId: String?, - private val datasetVersion: String?, - private val description: String?, - private val metadata: Metadata?, - private val name: String?, - private val public_: Boolean?, - private val repoInfo: RepoInfo?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") fun projectId(): String? = projectId - - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") fun baseExpId(): String? = baseExpId - - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset - */ - @JsonProperty("dataset_id") fun datasetId(): String? = 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. - */ - @JsonProperty("dataset_version") fun datasetVersion(): String? = datasetVersion - - /** Textual description of the experiment */ - @JsonProperty("description") fun description(): String? = description - - /** User-controlled metadata about the experiment */ - @JsonProperty("metadata") fun metadata(): Metadata? = metadata - - /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") fun name(): String? = name - - /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - */ - @JsonProperty("public") fun public_(): Boolean? = public_ - - /** Metadata about the state of the repo when the experiment was created */ - @JsonProperty("repo_info") fun repoInfo(): RepoInfo? = repoInfo - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentReplaceBody && - this.projectId == other.projectId && - this.baseExpId == other.baseExpId && - this.datasetId == other.datasetId && - this.datasetVersion == other.datasetVersion && - this.description == other.description && - this.metadata == other.metadata && - this.name == other.name && - this.public_ == other.public_ && - this.repoInfo == other.repoInfo && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - projectId, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "ExperimentReplaceBody{projectId=$projectId, baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var projectId: String? = null - private var baseExpId: String? = null - private var datasetId: String? = null - private var datasetVersion: String? = null - private var description: String? = null - private var metadata: Metadata? = null - private var name: String? = null - private var public_: Boolean? = null - private var repoInfo: RepoInfo? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentReplaceBody: ExperimentReplaceBody) = apply { - this.projectId = experimentReplaceBody.projectId - this.baseExpId = experimentReplaceBody.baseExpId - this.datasetId = experimentReplaceBody.datasetId - this.datasetVersion = experimentReplaceBody.datasetVersion - this.description = experimentReplaceBody.description - this.metadata = experimentReplaceBody.metadata - this.name = experimentReplaceBody.name - this.public_ = experimentReplaceBody.public_ - this.repoInfo = experimentReplaceBody.repoInfo - additionalProperties(experimentReplaceBody.additionalProperties) - } - - /** Unique identifier for the project that the experiment belongs under */ - @JsonProperty("project_id") - fun projectId(projectId: String) = apply { this.projectId = projectId } - - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") - fun baseExpId(baseExpId: String) = apply { this.baseExpId = baseExpId } - - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a - * dataset - */ - @JsonProperty("dataset_id") - fun datasetId(datasetId: String) = 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. - */ - @JsonProperty("dataset_version") - fun datasetVersion(datasetVersion: String) = apply { - this.datasetVersion = datasetVersion - } - - /** Textual description of the experiment */ - @JsonProperty("description") - fun description(description: String) = apply { this.description = description } - - /** User-controlled metadata about the experiment */ - @JsonProperty("metadata") - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } - - /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } - - /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - */ - @JsonProperty("public") fun public_(public_: Boolean) = apply { this.public_ = public_ } - - /** Metadata about the state of the repo when the experiment was created */ - @JsonProperty("repo_info") - fun repoInfo(repoInfo: RepoInfo) = apply { this.repoInfo = repoInfo } - - 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(): ExperimentReplaceBody = - ExperimentReplaceBody( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalProperties.toUnmodifiable(), - ) - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ExperimentReplaceParams && - this.projectId == other.projectId && - this.baseExpId == other.baseExpId && - this.datasetId == other.datasetId && - this.datasetVersion == other.datasetVersion && - this.description == other.description && - this.metadata == other.metadata && - this.name == other.name && - this.public_ == other.public_ && - this.repoInfo == other.repoInfo && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int { - return Objects.hash( - projectId, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "ExperimentReplaceParams{projectId=$projectId, baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - @NoAutoDetect - class Builder { - - private var projectId: String? = null - private var baseExpId: String? = null - private var datasetId: String? = null - private var datasetVersion: String? = null - private var description: String? = null - private var metadata: Metadata? = null - private var name: String? = null - private var public_: Boolean? = null - private var repoInfo: RepoInfo? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(experimentReplaceParams: ExperimentReplaceParams) = apply { - this.projectId = experimentReplaceParams.projectId - this.baseExpId = experimentReplaceParams.baseExpId - this.datasetId = experimentReplaceParams.datasetId - this.datasetVersion = experimentReplaceParams.datasetVersion - this.description = experimentReplaceParams.description - this.metadata = experimentReplaceParams.metadata - this.name = experimentReplaceParams.name - this.public_ = experimentReplaceParams.public_ - this.repoInfo = experimentReplaceParams.repoInfo - additionalQueryParams(experimentReplaceParams.additionalQueryParams) - additionalHeaders(experimentReplaceParams.additionalHeaders) - additionalBodyProperties(experimentReplaceParams.additionalBodyProperties) - } - - /** Unique identifier for the project that the experiment belongs under */ - fun projectId(projectId: String) = apply { this.projectId = projectId } - - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(baseExpId: String) = apply { this.baseExpId = baseExpId } - - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset - */ - fun datasetId(datasetId: String) = 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) = apply { this.datasetVersion = datasetVersion } - - /** Textual description of the experiment */ - fun description(description: String) = apply { this.description = description } - - /** User-controlled metadata about the experiment */ - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } - - /** Name of the experiment. Within a project, experiment names are unique */ - fun name(name: String) = 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) = apply { this.public_ = public_ } - - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo) = apply { this.repoInfo = repoInfo } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } - - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } - - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } - - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } - - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } - - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } - - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } - - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } - - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun build(): ExperimentReplaceParams = - ExperimentReplaceParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } - - /** User-controlled metadata about the experiment */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** Metadata about the state of the repo when the experiment was created */ - @JsonDeserialize(builder = RepoInfo.Builder::class) - @NoAutoDetect - class RepoInfo - private constructor( - private val commit: String?, - private val branch: String?, - private val tag: String?, - private val dirty: Boolean?, - private val authorName: String?, - private val authorEmail: String?, - private val commitMessage: String?, - private val commitTime: String?, - private val gitDiff: String?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** SHA of most recent commit */ - @JsonProperty("commit") fun commit(): String? = commit - - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") fun branch(): String? = branch - - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") fun tag(): String? = tag - - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") fun dirty(): Boolean? = dirty - - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") fun authorName(): String? = authorName - - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") fun authorEmail(): String? = authorEmail - - /** Most recent commit message */ - @JsonProperty("commit_message") fun commitMessage(): String? = commitMessage - - /** Time of the most recent commit */ - @JsonProperty("commit_time") fun commitTime(): String? = commitTime - - /** - * If the repo was dirty when run, this includes the diff between the current state of the - * repo and the most recent commit. - */ - @JsonProperty("git_diff") fun gitDiff(): String? = gitDiff - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is RepoInfo && - this.commit == other.commit && - this.branch == other.branch && - this.tag == other.tag && - this.dirty == other.dirty && - this.authorName == other.authorName && - this.authorEmail == other.authorEmail && - this.commitMessage == other.commitMessage && - this.commitTime == other.commitTime && - this.gitDiff == other.gitDiff && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "RepoInfo{commit=$commit, branch=$branch, tag=$tag, dirty=$dirty, authorName=$authorName, authorEmail=$authorEmail, commitMessage=$commitMessage, commitTime=$commitTime, gitDiff=$gitDiff, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var commit: String? = null - private var branch: String? = null - private var tag: String? = null - private var dirty: Boolean? = null - private var authorName: String? = null - private var authorEmail: String? = null - private var commitMessage: String? = null - private var commitTime: String? = null - private var gitDiff: String? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(repoInfo: RepoInfo) = apply { - this.commit = repoInfo.commit - this.branch = repoInfo.branch - this.tag = repoInfo.tag - this.dirty = repoInfo.dirty - this.authorName = repoInfo.authorName - this.authorEmail = repoInfo.authorEmail - this.commitMessage = repoInfo.commitMessage - this.commitTime = repoInfo.commitTime - this.gitDiff = repoInfo.gitDiff - additionalProperties(repoInfo.additionalProperties) - } - - /** SHA of most recent commit */ - @JsonProperty("commit") fun commit(commit: String) = apply { this.commit = commit } - - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") fun branch(branch: String) = apply { this.branch = branch } - - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") fun tag(tag: String) = apply { this.tag = tag } - - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") fun dirty(dirty: Boolean) = apply { this.dirty = dirty } - - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") - fun authorName(authorName: String) = apply { this.authorName = authorName } - - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") - fun authorEmail(authorEmail: String) = apply { this.authorEmail = authorEmail } - - /** Most recent commit message */ - @JsonProperty("commit_message") - fun commitMessage(commitMessage: String) = apply { this.commitMessage = commitMessage } - - /** Time of the most recent commit */ - @JsonProperty("commit_time") - fun commitTime(commitTime: String) = apply { this.commitTime = commitTime } - - /** - * If the repo was dirty when run, this includes the diff between the current state of - * the repo and the most recent commit. - */ - @JsonProperty("git_diff") - fun gitDiff(gitDiff: String) = apply { this.gitDiff = gitDiff } - - 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(): RepoInfo = - RepoInfo( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties.toUnmodifiable(), - ) - } - } -} 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 old mode 100644 new mode 100755 index 3062382b..b12294df --- 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,126 +2,195 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Get an experiment object by its id */ class ExperimentRetrieveParams -constructor( - private val experimentId: String, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { +private constructor( + private val experimentId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { - fun experimentId(): String = experimentId + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ExperimentRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ExperimentRetrieveParams]. */ + @JvmStatic fun builder() = Builder() } - fun _additionalQueryParams(): Map> = additionalQueryParams + /** A builder for [ExperimentRetrieveParams]. */ + class Builder internal constructor() { - fun _additionalHeaders(): Map> = additionalHeaders + private var experimentId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + @JvmSynthetic + internal fun from(experimentRetrieveParams: ExperimentRetrieveParams) = apply { + experimentId = experimentRetrieveParams.experimentId + additionalHeaders = experimentRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentRetrieveParams.additionalQueryParams.toBuilder() } - return other is ExperimentRetrieveParams && - this.experimentId == other.experimentId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } + /** Experiment id */ + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } - override fun hashCode(): Int { - return Objects.hash( - experimentId, - additionalQueryParams, - additionalHeaders, - ) - } + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) - override fun toString() = - "ExperimentRetrieveParams{experimentId=$experimentId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - @JvmStatic fun builder() = Builder() - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @NoAutoDetect - class Builder { + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - private var experimentId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(experimentRetrieveParams: ExperimentRetrieveParams) = apply { - this.experimentId = experimentRetrieveParams.experimentId - additionalQueryParams(experimentRetrieveParams.additionalQueryParams) - additionalHeaders(experimentRetrieveParams.additionalHeaders) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + 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 removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [ExperimentRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ExperimentRetrieveParams = ExperimentRetrieveParams( - checkNotNull(experimentId) { "`experimentId` is required but was not set" }, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + experimentId, + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + } + + return other is ExperimentRetrieveParams && + experimentId == other.experimentId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(experimentId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ExperimentRetrieveParams{experimentId=$experimentId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 new file mode 100755 index 00000000..f944a937 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParams.kt @@ -0,0 +1,270 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Summarize experiment */ +class ExperimentSummarizeParams +private constructor( + private val experimentId: String?, + private val comparisonExperimentId: String?, + private val summarizeScores: Boolean?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) + + /** + * The experiment to compare against, if summarizing scores and metrics. If omitted, will fall + * back to the `base_exp_id` stored in the experiment metadata, and then to the most recent + * experiment run in the same project. Must pass `summarize_scores=true` for this id to be used + */ + fun comparisonExperimentId(): Optional = Optional.ofNullable(comparisonExperimentId) + + /** + * Whether to summarize the scores and metrics. If false (or omitted), only the metadata will be + * returned. + */ + fun summarizeScores(): Optional = Optional.ofNullable(summarizeScores) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ExperimentSummarizeParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of [ExperimentSummarizeParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ExperimentSummarizeParams]. */ + class Builder internal constructor() { + + private var experimentId: String? = null + private var comparisonExperimentId: String? = null + private var summarizeScores: Boolean? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(experimentSummarizeParams: ExperimentSummarizeParams) = apply { + experimentId = experimentSummarizeParams.experimentId + comparisonExperimentId = experimentSummarizeParams.comparisonExperimentId + summarizeScores = experimentSummarizeParams.summarizeScores + additionalHeaders = experimentSummarizeParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentSummarizeParams.additionalQueryParams.toBuilder() + } + + /** Experiment id */ + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } + + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) + + /** + * The experiment to compare against, if summarizing scores and metrics. If omitted, will + * fall back to the `base_exp_id` stored in the experiment metadata, and then to the most + * recent experiment run in the same project. Must pass `summarize_scores=true` for this id + * to be used + */ + fun comparisonExperimentId(comparisonExperimentId: String?) = apply { + this.comparisonExperimentId = comparisonExperimentId + } + + /** + * Alias for calling [Builder.comparisonExperimentId] with + * `comparisonExperimentId.orElse(null)`. + */ + fun comparisonExperimentId(comparisonExperimentId: Optional) = + comparisonExperimentId(comparisonExperimentId.getOrNull()) + + /** + * Whether to summarize the scores and metrics. If false (or omitted), only the metadata + * will be returned. + */ + fun summarizeScores(summarizeScores: Boolean?) = apply { + this.summarizeScores = summarizeScores + } + + /** + * Alias for [Builder.summarizeScores]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun summarizeScores(summarizeScores: Boolean) = summarizeScores(summarizeScores as Boolean?) + + /** Alias for calling [Builder.summarizeScores] with `summarizeScores.orElse(null)`. */ + fun summarizeScores(summarizeScores: Optional) = + summarizeScores(summarizeScores.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ExperimentSummarizeParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ExperimentSummarizeParams = + ExperimentSummarizeParams( + experimentId, + comparisonExperimentId, + summarizeScores, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is ExperimentSummarizeParams && + experimentId == other.experimentId && + comparisonExperimentId == other.comparisonExperimentId && + summarizeScores == other.summarizeScores && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + experimentId, + comparisonExperimentId, + summarizeScores, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ExperimentSummarizeParams{experimentId=$experimentId, comparisonExperimentId=$comparisonExperimentId, summarizeScores=$summarizeScores, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 old mode 100644 new mode 100755 index d193ff5a..647ca5ab --- 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 @@ -3,299 +3,531 @@ 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.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +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 com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Partially update an experiment object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ class ExperimentUpdateParams -constructor( - private val experimentId: String, - private val baseExpId: String?, - private val datasetId: String?, - private val datasetVersion: String?, - private val description: String?, - private val metadata: Metadata?, - private val name: String?, - private val public_: Boolean?, - private val repoInfo: RepoInfo?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { +private constructor( + private val experimentId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Experiment id */ + fun experimentId(): Optional = Optional.ofNullable(experimentId) + + /** + * 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 = body.baseExpId() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun datasetVersion(): Optional = body.datasetVersion() + + /** + * 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 = body.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 = body.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 = body.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 = body.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 = body.repoInfo() + + /** + * Returns the raw JSON value of [baseExpId]. + * + * Unlike [baseExpId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _baseExpId(): JsonField = body._baseExpId() + + /** + * Returns the raw JSON value of [datasetId]. + * + * Unlike [datasetId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _datasetId(): JsonField = body._datasetId() + + /** + * Returns the raw JSON value of [datasetVersion]. + * + * Unlike [datasetVersion], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _datasetVersion(): JsonField = body._datasetVersion() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [public_]. + * + * Unlike [public_], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _public_(): JsonField = body._public_() + + /** + * Returns the raw JSON value of [repoInfo]. + * + * Unlike [repoInfo], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _repoInfo(): JsonField = body._repoInfo() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun experimentId(): String = experimentId - - fun baseExpId(): Optional = Optional.ofNullable(baseExpId) + fun toBuilder() = Builder().from(this) - fun datasetId(): Optional = Optional.ofNullable(datasetId) + companion object { - fun datasetVersion(): Optional = Optional.ofNullable(datasetVersion) + @JvmStatic fun none(): ExperimentUpdateParams = builder().build() - fun description(): Optional = Optional.ofNullable(description) + /** Returns a mutable builder for constructing an instance of [ExperimentUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } - fun metadata(): Optional = Optional.ofNullable(metadata) + /** A builder for [ExperimentUpdateParams]. */ + class Builder internal constructor() { - fun name(): Optional = Optional.ofNullable(name) + 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 public_(): Optional = Optional.ofNullable(public_) + @JvmSynthetic + internal fun from(experimentUpdateParams: ExperimentUpdateParams) = apply { + experimentId = experimentUpdateParams.experimentId + body = experimentUpdateParams.body.toBuilder() + additionalHeaders = experimentUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = experimentUpdateParams.additionalQueryParams.toBuilder() + } - fun repoInfo(): Optional = Optional.ofNullable(repoInfo) + /** Experiment id */ + fun experimentId(experimentId: String?) = apply { this.experimentId = experimentId } - @JvmSynthetic - internal fun getBody(): ExperimentUpdateBody { - return ExperimentUpdateBody( - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalBodyProperties, - ) - } + /** Alias for calling [Builder.experimentId] with `experimentId.orElse(null)`. */ + fun experimentId(experimentId: Optional) = experimentId(experimentId.getOrNull()) - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** + * 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: + * - [baseExpId] + * - [datasetId] + * - [datasetVersion] + * - [description] + * - [metadata] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = apply { body.baseExpId(baseExpId) } - fun getPathParam(index: Int): String { - return when (index) { - 0 -> experimentId - else -> "" - } - } + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) - @JsonDeserialize(builder = ExperimentUpdateBody.Builder::class) - @NoAutoDetect - class ExperimentUpdateBody - internal constructor( - private val baseExpId: String?, - private val datasetId: String?, - private val datasetVersion: String?, - private val description: String?, - private val metadata: Metadata?, - private val name: String?, - private val public_: Boolean?, - private val repoInfo: RepoInfo?, - private val additionalProperties: Map, - ) { + /** + * 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) } - private var hashCode: Int = 0 + /** + * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + */ + fun datasetId(datasetId: String?) = apply { body.datasetId(datasetId) } - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") fun baseExpId(): String? = baseExpId + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + * 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. */ - @JsonProperty("dataset_id") fun datasetId(): String? = datasetId + 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. */ - @JsonProperty("dataset_version") fun datasetVersion(): String? = datasetVersion + 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 */ - @JsonProperty("description") fun description(): String? = description + 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 */ - @JsonProperty("metadata") fun metadata(): Metadata? = 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) } /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") fun name(): String? = name + 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 */ - @JsonProperty("public") fun public_(): Boolean? = public_ + 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 */ - @JsonProperty("repo_info") fun repoInfo(): RepoInfo? = repoInfo + fun repoInfo(repoInfo: RepoInfo?) = apply { body.repoInfo(repoInfo) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.repoInfo] with `repoInfo.orElse(null)`. */ + fun repoInfo(repoInfo: Optional) = repoInfo(repoInfo.getOrNull()) - fun toBuilder() = Builder().from(this) + /** + * 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) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - return other is ExperimentUpdateBody && - this.baseExpId == other.baseExpId && - this.datasetId == other.datasetId && - this.datasetVersion == other.datasetVersion && - this.description == other.description && - this.metadata == other.metadata && - this.name == other.name && - this.public_ == other.public_ && - this.repoInfo == other.repoInfo && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalProperties, - ) + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - return hashCode + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - override fun toString() = - "ExperimentUpdateBody{baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalProperties=$additionalProperties}" + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - class Builder { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var baseExpId: String? = null - private var datasetId: String? = null - private var datasetVersion: String? = null - private var description: String? = null - private var metadata: Metadata? = null - private var name: String? = null - private var public_: Boolean? = null - private var repoInfo: RepoInfo? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(experimentUpdateBody: ExperimentUpdateBody) = apply { - this.baseExpId = experimentUpdateBody.baseExpId - this.datasetId = experimentUpdateBody.datasetId - this.datasetVersion = experimentUpdateBody.datasetVersion - this.description = experimentUpdateBody.description - this.metadata = experimentUpdateBody.metadata - this.name = experimentUpdateBody.name - this.public_ = experimentUpdateBody.public_ - this.repoInfo = experimentUpdateBody.repoInfo - additionalProperties(experimentUpdateBody.additionalProperties) - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Id of default base experiment to compare against when viewing this experiment */ - @JsonProperty("base_exp_id") - fun baseExpId(baseExpId: String) = apply { this.baseExpId = baseExpId } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * Identifier of the linked dataset, or null if the experiment is not linked to a - * dataset - */ - @JsonProperty("dataset_id") - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - /** - * 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. - */ - @JsonProperty("dataset_version") - fun datasetVersion(datasetVersion: String) = apply { - this.datasetVersion = datasetVersion - } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** Textual description of the experiment */ - @JsonProperty("description") - fun description(description: String) = apply { this.description = description } + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - /** User-controlled metadata about the experiment */ - @JsonProperty("metadata") - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** Name of the experiment. Within a project, experiment names are unique */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - /** - * Whether or not the experiment is public. Public experiments can be viewed by anybody - * inside or outside the organization - */ - @JsonProperty("public") fun public_(public_: Boolean) = apply { this.public_ = public_ } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - /** Metadata about the state of the repo when the experiment was created */ - @JsonProperty("repo_info") - fun repoInfo(repoInfo: RepoInfo) = apply { this.repoInfo = repoInfo } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.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 putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun build(): ExperimentUpdateBody = - ExperimentUpdateBody( - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalProperties.toUnmodifiable(), - ) + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - } - fun _additionalQueryParams(): Map> = additionalQueryParams + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - fun _additionalHeaders(): Map> = additionalHeaders + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun _additionalBodyProperties(): Map = additionalBodyProperties + 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 other is ExperimentUpdateParams && - this.experimentId == other.experimentId && - this.baseExpId == other.baseExpId && - this.datasetId == other.datasetId && - this.datasetVersion == other.datasetVersion && - this.description == other.description && - this.metadata == other.metadata && - this.name == other.name && - this.public_ == other.public_ && - this.repoInfo == other.repoInfo && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties + /** + * Returns an immutable instance of [ExperimentUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ExperimentUpdateParams = + ExperimentUpdateParams( + experimentId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - override fun hashCode(): Int { - return Objects.hash( - experimentId, + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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, @@ -304,414 +536,555 @@ constructor( name, public_, repoInfo, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, + mutableMapOf(), ) - } - override fun toString() = - "ExperimentUpdateParams{experimentId=$experimentId, baseExpId=$baseExpId, datasetId=$datasetId, datasetVersion=$datasetVersion, description=$description, metadata=$metadata, name=$name, public_=$public_, repoInfo=$repoInfo, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + /** + * 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") - fun toBuilder() = Builder().from(this) + /** + * 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") - companion object { + /** + * 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") - @JvmStatic fun builder() = Builder() - } + /** + * 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") - @NoAutoDetect - class Builder { + /** + * 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") - private var experimentId: String? = null - private var baseExpId: String? = null - private var datasetId: String? = null - private var datasetVersion: String? = null - private var description: String? = null - private var metadata: Metadata? = null - private var name: String? = null - private var public_: Boolean? = null - private var repoInfo: RepoInfo? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + /** + * 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") - @JvmSynthetic - internal fun from(experimentUpdateParams: ExperimentUpdateParams) = apply { - this.experimentId = experimentUpdateParams.experimentId - this.baseExpId = experimentUpdateParams.baseExpId - this.datasetId = experimentUpdateParams.datasetId - this.datasetVersion = experimentUpdateParams.datasetVersion - this.description = experimentUpdateParams.description - this.metadata = experimentUpdateParams.metadata - this.name = experimentUpdateParams.name - this.public_ = experimentUpdateParams.public_ - this.repoInfo = experimentUpdateParams.repoInfo - additionalQueryParams(experimentUpdateParams.additionalQueryParams) - additionalHeaders(experimentUpdateParams.additionalHeaders) - additionalBodyProperties(experimentUpdateParams.additionalBodyProperties) - } + /** + * 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") - /** Experiment id */ - fun experimentId(experimentId: String) = apply { this.experimentId = experimentId } + /** + * 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") - /** Id of default base experiment to compare against when viewing this experiment */ - fun baseExpId(baseExpId: String) = apply { this.baseExpId = baseExpId } + /** + * 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 /** - * Identifier of the linked dataset, or null if the experiment is not linked to a dataset + * Returns the raw JSON value of [datasetId]. + * + * Unlike [datasetId], this method doesn't throw if the JSON field has an unexpected type. */ - fun datasetId(datasetId: String) = apply { this.datasetId = datasetId } + @JsonProperty("dataset_id") @ExcludeMissing fun _datasetId(): JsonField = 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. + * Returns the raw JSON value of [datasetVersion]. + * + * Unlike [datasetVersion], this method doesn't throw if the JSON field has an unexpected + * type. */ - fun datasetVersion(datasetVersion: String) = apply { this.datasetVersion = datasetVersion } + @JsonProperty("dataset_version") + @ExcludeMissing + fun _datasetVersion(): JsonField = datasetVersion - /** Textual description of the experiment */ - fun description(description: String) = apply { this.description = description } + /** + * 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 - /** User-controlled metadata about the experiment */ - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } + /** + * 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 - /** Name of the experiment. Within a project, experiment names are unique */ - fun name(name: String) = apply { this.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 /** - * 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 [public_]. + * + * Unlike [public_], this method doesn't throw if the JSON field has an unexpected type. */ - fun public_(public_: Boolean) = apply { this.public_ = public_ } + @JsonProperty("public") @ExcludeMissing fun _public_(): JsonField = public_ - /** Metadata about the state of the repo when the experiment was created */ - fun repoInfo(repoInfo: RepoInfo) = apply { this.repoInfo = repoInfo } + /** + * 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 - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun toBuilder() = Builder().from(this) - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + companion object { - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + /** 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() + private var additionalProperties: MutableMap = mutableMapOf() - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } + @JvmSynthetic + internal fun from(body: Body) = apply { + baseExpId = body.baseExpId + datasetId = body.datasetId + datasetVersion = body.datasetVersion + description = body.description + metadata = body.metadata + name = body.name + public_ = body.public_ + repoInfo = body.repoInfo + additionalProperties = body.additionalProperties.toMutableMap() + } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + /** Id of default base experiment to compare against when viewing this experiment */ + fun baseExpId(baseExpId: String?) = baseExpId(JsonField.ofNullable(baseExpId)) - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } + /** Alias for calling [Builder.baseExpId] with `baseExpId.orElse(null)`. */ + fun baseExpId(baseExpId: Optional) = baseExpId(baseExpId.getOrNull()) - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + /** + * 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 } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + /** + * Identifier of the linked dataset, or null if the experiment is not linked to a + * dataset + */ + fun datasetId(datasetId: String?) = datasetId(JsonField.ofNullable(datasetId)) - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) - } + /** Alias for calling [Builder.datasetId] with `datasetId.orElse(null)`. */ + fun datasetId(datasetId: Optional) = datasetId(datasetId.getOrNull()) - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + /** + * 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 } - fun build(): ExperimentUpdateParams = - ExperimentUpdateParams( - checkNotNull(experimentId) { "`experimentId` is required but was not set" }, - baseExpId, - datasetId, - datasetVersion, - description, - metadata, - name, - public_, - repoInfo, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } + /** + * 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)) - /** User-controlled metadata about the experiment */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { + /** Alias for calling [Builder.datasetVersion] with `datasetVersion.orElse(null)`. */ + fun datasetVersion(datasetVersion: Optional) = + datasetVersion(datasetVersion.getOrNull()) - private var hashCode: Int = 0 + /** + * 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 + } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Textual description of the experiment */ + fun description(description: String?) = description(JsonField.ofNullable(description)) - fun toBuilder() = Builder().from(this) + /** Alias for calling [Builder.description] with `description.orElse(null)`. */ + fun description(description: Optional) = description(description.getOrNull()) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + /** + * 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 } - return other is Metadata && this.additionalProperties == other.additionalProperties - } + /** User-controlled metadata about the experiment */ + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + /** + * 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 } - companion object { + /** Name of the experiment. Within a project, experiment names are unique */ + fun name(name: String?) = name(JsonField.ofNullable(name)) - @JvmStatic fun builder() = Builder() - } + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) - class Builder { + /** + * 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 } - private var additionalProperties: MutableMap = mutableMapOf() + /** + * 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_)) - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } + /** + * 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() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** Metadata about the state of the repo when the experiment was created */ - @JsonDeserialize(builder = RepoInfo.Builder::class) - @NoAutoDetect - class RepoInfo - private constructor( - private val commit: String?, - private val branch: String?, - private val tag: String?, - private val dirty: Boolean?, - private val authorName: String?, - private val authorEmail: String?, - private val commitMessage: String?, - private val commitTime: String?, - private val gitDiff: String?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** SHA of most recent commit */ - @JsonProperty("commit") fun commit(): String? = commit - - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") fun branch(): String? = branch + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") fun tag(): String? = tag + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") fun dirty(): Boolean? = dirty + /** + * 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(), + ) + } - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") fun authorName(): String? = authorName + private var validated: Boolean = false - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") fun authorEmail(): String? = authorEmail + fun validate(): Body = apply { + if (validated) { + return@apply + } - /** Most recent commit message */ - @JsonProperty("commit_message") fun commitMessage(): String? = commitMessage + baseExpId() + datasetId() + datasetVersion() + description() + metadata().ifPresent { it.validate() } + name() + public_() + repoInfo().ifPresent { it.validate() } + validated = true + } - /** Time of the most recent commit */ - @JsonProperty("commit_time") fun commitTime(): String? = commitTime + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } /** - * If the repo was dirty when run, this includes the diff between the current state of the - * repo and the most recent commit. + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. */ - @JsonProperty("git_diff") fun gitDiff(): String? = gitDiff - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) + @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) override fun equals(other: Any?): Boolean { if (this === other) { return true } - return other is RepoInfo && - this.commit == other.commit && - this.branch == other.branch && - this.tag == other.tag && - this.dirty == other.dirty && - this.authorName == other.authorName && - this.authorEmail == other.authorEmail && - this.commitMessage == other.commitMessage && - this.commitTime == other.commitTime && - this.gitDiff == other.gitDiff && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties, - ) - } - return hashCode + return 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 } + private val hashCode: Int by lazy { + Objects.hash( + baseExpId, + datasetId, + datasetVersion, + description, + metadata, + name, + public_, + repoInfo, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + override fun toString() = - "RepoInfo{commit=$commit, branch=$branch, tag=$tag, dirty=$dirty, authorName=$authorName, authorEmail=$authorEmail, commitMessage=$commitMessage, commitTime=$commitTime, gitDiff=$gitDiff, additionalProperties=$additionalProperties}" + "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 */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) companion object { + /** Returns a mutable builder for constructing an instance of [Metadata]. */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Metadata]. */ + class Builder internal constructor() { - private var commit: String? = null - private var branch: String? = null - private var tag: String? = null - private var dirty: Boolean? = null - private var authorName: String? = null - private var authorEmail: String? = null - private var commitMessage: String? = null - private var commitTime: String? = null - private var gitDiff: String? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(repoInfo: RepoInfo) = apply { - this.commit = repoInfo.commit - this.branch = repoInfo.branch - this.tag = repoInfo.tag - this.dirty = repoInfo.dirty - this.authorName = repoInfo.authorName - this.authorEmail = repoInfo.authorEmail - this.commitMessage = repoInfo.commitMessage - this.commitTime = repoInfo.commitTime - this.gitDiff = repoInfo.gitDiff - additionalProperties(repoInfo.additionalProperties) + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() } - /** SHA of most recent commit */ - @JsonProperty("commit") fun commit(commit: String) = apply { this.commit = commit } - - /** Name of the branch the most recent commit belongs to */ - @JsonProperty("branch") fun branch(branch: String) = apply { this.branch = branch } - - /** Name of the tag on the most recent commit */ - @JsonProperty("tag") fun tag(tag: String) = apply { this.tag = tag } - - /** Whether or not the repo had uncommitted changes when snapshotted */ - @JsonProperty("dirty") fun dirty(dirty: Boolean) = apply { this.dirty = dirty } + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } - /** Name of the author of the most recent commit */ - @JsonProperty("author_name") - fun authorName(authorName: String) = apply { this.authorName = authorName } + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } - /** Email of the author of the most recent commit */ - @JsonProperty("author_email") - fun authorEmail(authorEmail: String) = apply { this.authorEmail = authorEmail } + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } - /** Most recent commit message */ - @JsonProperty("commit_message") - fun commitMessage(commitMessage: String) = apply { this.commitMessage = commitMessage } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - /** Time of the most recent commit */ - @JsonProperty("commit_time") - fun commitTime(commitTime: String) = apply { this.commitTime = commitTime } + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } /** - * If the repo was dirty when run, this includes the diff between the current state of - * the repo and the most recent commit. + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. */ - @JsonProperty("git_diff") - fun gitDiff(gitDiff: String) = apply { this.gitDiff = gitDiff } + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) + /** + * Returns 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 } - fun build(): RepoInfo = - RepoInfo( - commit, - branch, - tag, - dirty, - authorName, - authorEmail, - commitMessage, - commitTime, - gitDiff, - additionalProperties.toUnmodifiable(), - ) + return other is Metadata && additionalProperties == other.additionalProperties } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ExperimentUpdateParams && + experimentId == other.experimentId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(experimentId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ExperimentUpdateParams{experimentId=$experimentId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 new file mode 100755 index 00000000..d4e345ad --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackDatasetItem.kt @@ -0,0 +1,591 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class FeedbackDatasetItem +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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` + * + * @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 id(): String = id.getRequired("id") + + /** + * An optional comment string to log about the dataset event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun comment(): Optional = comment.getOptional("comment") + + /** + * 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. + * + * @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") + + /** + * The source of the feedback. Must be one of "external" (default), "app", or "api" + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun source(): Optional = source.getOptional("source") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [comment]. + * + * Unlike [comment], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("comment") @ExcludeMissing fun _comment(): JsonField = comment + + /** + * 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 [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source + + /** + * Returns the raw JSON value of [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 [FeedbackDatasetItem]. + * + * The following fields are required: + * ```java + * .id() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FeedbackDatasetItem]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var comment: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(feedbackDatasetItem: FeedbackDatasetItem) = apply { + id = feedbackDatasetItem.id + comment = feedbackDatasetItem.comment + metadata = feedbackDatasetItem.metadata + source = feedbackDatasetItem.source + tags = feedbackDatasetItem.tags.map { it.toMutableList() } + additionalProperties = feedbackDatasetItem.additionalProperties.toMutableMap() + } + + /** + * The id of the dataset event to log feedback for. This is the row `id` returned by `POST + * /v1/dataset/{dataset_id}/insert` + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** An optional comment string to log about the dataset event */ + fun comment(comment: String?) = comment(JsonField.ofNullable(comment)) + + /** Alias for calling [Builder.comment] with `comment.orElse(null)`. */ + fun comment(comment: Optional) = comment(comment.getOrNull()) + + /** + * Sets [Builder.comment] to an arbitrary JSON value. + * + * You should usually call [Builder.comment] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun comment(comment: JsonField) = apply { this.comment = comment } + + /** + * 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. + */ + 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 } + + /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ + fun source(source: Source?) = source(JsonField.ofNullable(source)) + + /** Alias for calling [Builder.source] with `source.orElse(null)`. */ + fun source(source: Optional) = source(source.getOrNull()) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [Source] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FeedbackDatasetItem]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FeedbackDatasetItem = + FeedbackDatasetItem( + checkRequired("id", id), + comment, + metadata, + source, + (tags ?: JsonMissing.of()).map { it.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. + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ + class Source @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val APP = of("app") + + @JvmField val API = of("api") + + @JvmField val EXTERNAL = of("external") + + @JvmStatic fun of(value: String) = Source(JsonField.of(value)) + } + + /** An enum containing [Source]'s known values. */ + enum class Known { + APP, + API, + EXTERNAL, + } + + /** + * An enum containing [Source]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Source] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + APP, + API, + EXTERNAL, + /** An enum member indicating that [Source] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + APP -> Value.APP + API -> Value.API + EXTERNAL -> Value.EXTERNAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + APP -> Known.APP + API -> Known.API + EXTERNAL -> Known.EXTERNAL + else -> throw BraintrustInvalidDataException("Unknown Source: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Source && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FeedbackDatasetItem && + id == other.id && + comment == other.comment && + metadata == other.metadata && + source == other.source && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, comment, metadata, source, tags, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FeedbackDatasetItem{id=$id, comment=$comment, metadata=$metadata, source=$source, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..34472611 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackExperimentItem.kt @@ -0,0 +1,753 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class FeedbackExperimentItem +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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` + * + * @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 id(): String = id.getRequired("id") + + /** + * An optional comment string to log about the experiment event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun comment(): Optional = comment.getOptional("comment") + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** + * 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. + * + * @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") + + /** + * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into the + * existing scores for the experiment event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scores(): Optional = scores.getOptional("scores") + + /** + * The source of the feedback. Must be one of "external" (default), "app", or "api" + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun source(): Optional = source.getOptional("source") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [comment]. + * + * Unlike [comment], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("comment") @ExcludeMissing fun _comment(): JsonField = comment + + /** + * 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 [scores]. + * + * Unlike [scores], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("scores") @ExcludeMissing fun _scores(): JsonField = scores + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source + + /** + * Returns the raw JSON value of [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 [FeedbackExperimentItem]. + * + * The following fields are required: + * ```java + * .id() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FeedbackExperimentItem]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var comment: JsonField = JsonMissing.of() + private var expected: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var scores: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(feedbackExperimentItem: FeedbackExperimentItem) = apply { + id = feedbackExperimentItem.id + comment = feedbackExperimentItem.comment + expected = feedbackExperimentItem.expected + metadata = feedbackExperimentItem.metadata + scores = feedbackExperimentItem.scores + source = feedbackExperimentItem.source + tags = feedbackExperimentItem.tags.map { it.toMutableList() } + additionalProperties = feedbackExperimentItem.additionalProperties.toMutableMap() + } + + /** + * The id of the experiment event to log feedback for. This is the row `id` returned by + * `POST /v1/experiment/{experiment_id}/insert` + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** An optional comment string to log about the experiment event */ + fun comment(comment: String?) = comment(JsonField.ofNullable(comment)) + + /** Alias for calling [Builder.comment] with `comment.orElse(null)`. */ + fun comment(comment: Optional) = comment(comment.getOrNull()) + + /** + * Sets [Builder.comment] to an arbitrary JSON value. + * + * You should usually call [Builder.comment] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun comment(comment: JsonField) = apply { this.comment = comment } + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * 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. + */ + 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 } + + /** + * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into + * the existing scores for the experiment event + */ + fun scores(scores: Scores?) = scores(JsonField.ofNullable(scores)) + + /** Alias for calling [Builder.scores] with `scores.orElse(null)`. */ + fun scores(scores: Optional) = scores(scores.getOrNull()) + + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed [Scores] 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 } + + /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ + fun source(source: Source?) = source(JsonField.ofNullable(source)) + + /** Alias for calling [Builder.source] with `source.orElse(null)`. */ + fun source(source: Optional) = source(source.getOrNull()) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [Source] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FeedbackExperimentItem]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FeedbackExperimentItem = + FeedbackExperimentItem( + checkRequired("id", id), + comment, + expected, + metadata, + scores, + source, + (tags ?: JsonMissing.of()).map { it.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. + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + /** + * A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into the + * existing scores for the experiment event + */ + class Scores + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Scores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scores: Scores) = apply { + additionalProperties = scores.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 [Scores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Scores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Scores{additionalProperties=$additionalProperties}" + } + + /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ + class Source @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val APP = of("app") + + @JvmField val API = of("api") + + @JvmField val EXTERNAL = of("external") + + @JvmStatic fun of(value: String) = Source(JsonField.of(value)) + } + + /** An enum containing [Source]'s known values. */ + enum class Known { + APP, + API, + EXTERNAL, + } + + /** + * An enum containing [Source]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Source] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + APP, + API, + EXTERNAL, + /** An enum member indicating that [Source] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + APP -> Value.APP + API -> Value.API + EXTERNAL -> Value.EXTERNAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + APP -> Known.APP + API -> Known.API + EXTERNAL -> Known.EXTERNAL + else -> throw BraintrustInvalidDataException("Unknown Source: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Source && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FeedbackExperimentItem && + id == other.id && + comment == other.comment && + expected == other.expected && + metadata == other.metadata && + scores == other.scores && + source == other.source && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, comment, expected, metadata, scores, source, tags, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FeedbackExperimentItem{id=$id, comment=$comment, expected=$expected, metadata=$metadata, scores=$scores, source=$source, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..1858d30c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItem.kt @@ -0,0 +1,753 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class FeedbackProjectLogsItem +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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` + * + * @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 id(): String = id.getRequired("id") + + /** + * An optional comment string to log about the project logs event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun comment(): Optional = comment.getOptional("comment") + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** + * 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. + * + * @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") + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scores(): Optional = scores.getOptional("scores") + + /** + * The source of the feedback. Must be one of "external" (default), "app", or "api" + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun source(): Optional = source.getOptional("source") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [comment]. + * + * Unlike [comment], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("comment") @ExcludeMissing fun _comment(): JsonField = comment + + /** + * 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 [scores]. + * + * Unlike [scores], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("scores") @ExcludeMissing fun _scores(): JsonField = scores + + /** + * Returns the raw JSON value of [source]. + * + * Unlike [source], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("source") @ExcludeMissing fun _source(): JsonField = source + + /** + * Returns the raw JSON value of [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 [FeedbackProjectLogsItem]. + * + * The following fields are required: + * ```java + * .id() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FeedbackProjectLogsItem]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var comment: JsonField = JsonMissing.of() + private var expected: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var scores: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(feedbackProjectLogsItem: FeedbackProjectLogsItem) = apply { + id = feedbackProjectLogsItem.id + comment = feedbackProjectLogsItem.comment + expected = feedbackProjectLogsItem.expected + metadata = feedbackProjectLogsItem.metadata + scores = feedbackProjectLogsItem.scores + source = feedbackProjectLogsItem.source + tags = feedbackProjectLogsItem.tags.map { it.toMutableList() } + additionalProperties = feedbackProjectLogsItem.additionalProperties.toMutableMap() + } + + /** + * 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` + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** An optional comment string to log about the project logs event */ + fun comment(comment: String?) = comment(JsonField.ofNullable(comment)) + + /** Alias for calling [Builder.comment] with `comment.orElse(null)`. */ + fun comment(comment: Optional) = comment(comment.getOrNull()) + + /** + * Sets [Builder.comment] to an arbitrary JSON value. + * + * You should usually call [Builder.comment] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun comment(comment: JsonField) = apply { this.comment = comment } + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * 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. + */ + 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 } + + /** + * 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 + */ + fun scores(scores: Scores?) = scores(JsonField.ofNullable(scores)) + + /** Alias for calling [Builder.scores] with `scores.orElse(null)`. */ + fun scores(scores: Optional) = scores(scores.getOrNull()) + + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed [Scores] 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 } + + /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ + fun source(source: Source?) = source(JsonField.ofNullable(source)) + + /** Alias for calling [Builder.source] with `source.orElse(null)`. */ + fun source(source: Optional) = source(source.getOrNull()) + + /** + * Sets [Builder.source] to an arbitrary JSON value. + * + * You should usually call [Builder.source] with a well-typed [Source] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun source(source: JsonField) = apply { this.source = source } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FeedbackProjectLogsItem]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FeedbackProjectLogsItem = + FeedbackProjectLogsItem( + checkRequired("id", id), + comment, + expected, + metadata, + scores, + source, + (tags ?: JsonMissing.of()).map { it.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. + */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + /** + * 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 + */ + class Scores + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Scores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scores: Scores) = apply { + additionalProperties = scores.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 [Scores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Scores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Scores{additionalProperties=$additionalProperties}" + } + + /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ + class Source @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val APP = of("app") + + @JvmField val API = of("api") + + @JvmField val EXTERNAL = of("external") + + @JvmStatic fun of(value: String) = Source(JsonField.of(value)) + } + + /** An enum containing [Source]'s known values. */ + enum class Known { + APP, + API, + EXTERNAL, + } + + /** + * An enum containing [Source]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Source] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + APP, + API, + EXTERNAL, + /** An enum member indicating that [Source] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + APP -> Value.APP + API -> Value.API + EXTERNAL -> Value.EXTERNAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + APP -> Known.APP + API -> Known.API + EXTERNAL -> Known.EXTERNAL + else -> throw BraintrustInvalidDataException("Unknown Source: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Source && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FeedbackProjectLogsItem && + id == other.id && + comment == other.comment && + expected == other.expected && + metadata == other.metadata && + scores == other.scores && + source == other.source && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, comment, expected, metadata, scores, source, tags, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FeedbackProjectLogsItem{id=$id, comment=$comment, expected=$expected, metadata=$metadata, scores=$scores, source=$source, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..f5f0e6a0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FeedbackResponseSchema.kt @@ -0,0 +1,293 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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 FeedbackResponseSchema +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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). + */ + fun status(): Status = status.getRequired("status") + + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + + @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 [FeedbackResponseSchema]. + * + * The following fields are required: + * ```java + * .status() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FeedbackResponseSchema]. */ + class Builder internal constructor() { + + private var status: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(feedbackResponseSchema: FeedbackResponseSchema) = apply { + status = feedbackResponseSchema.status + additionalProperties = feedbackResponseSchema.additionalProperties.toMutableMap() + } + + fun status(status: Status) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [Status] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun status(status: JsonField) = apply { this.status = status } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FeedbackResponseSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .status() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FeedbackResponseSchema = + FeedbackResponseSchema( + checkRequired("status", status), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + /** An enum containing [Status]'s known values. */ + enum class Known { + SUCCESS + } + + /** + * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Status] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + /** An enum member indicating that [Status] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + else -> throw BraintrustInvalidDataException("Unknown Status: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Status && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FeedbackResponseSchema && + status == other.status && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(status, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FeedbackResponseSchema{status=$status, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..a8373def --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponse.kt @@ -0,0 +1,241 @@ +// 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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class FetchDatasetEventsResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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") + + /** + * Pagination cursor + * + * Pass this string directly as the `cursor` param to your next fetch request to get the next + * page of results. Not provided if the returned result set is empty. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cursor(): Optional = cursor.getOptional("cursor") + + /** + * 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 + + /** + * 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 + + @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 [FetchDatasetEventsResponse]. + * + * The following fields are required: + * ```java + * .events() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FetchDatasetEventsResponse]. */ + class Builder internal constructor() { + + private var events: JsonField>? = null + private var cursor: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fetchDatasetEventsResponse: FetchDatasetEventsResponse) = apply { + events = fetchDatasetEventsResponse.events.map { it.toMutableList() } + cursor = fetchDatasetEventsResponse.cursor + additionalProperties = fetchDatasetEventsResponse.additionalProperties.toMutableMap() + } + + /** A list of fetched events */ + 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 [DatasetEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: DatasetEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } + } + + /** + * Pagination cursor + * + * Pass this string directly as the `cursor` param to your next fetch request to get the + * next page of results. Not provided if the returned result set is empty. + */ + fun cursor(cursor: String?) = cursor(JsonField.ofNullable(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. + */ + fun cursor(cursor: JsonField) = apply { this.cursor = cursor } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FetchDatasetEventsResponse]. + * + * 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(): FetchDatasetEventsResponse = + FetchDatasetEventsResponse( + checkRequired("events", events).map { it.toImmutable() }, + cursor, + 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 + } + + return other is FetchDatasetEventsResponse && + events == other.events && + cursor == other.cursor && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(events, cursor, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FetchDatasetEventsResponse{events=$events, cursor=$cursor, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..c1c85b0c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponse.kt @@ -0,0 +1,242 @@ +// 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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class FetchExperimentEventsResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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") + + /** + * Pagination cursor + * + * Pass this string directly as the `cursor` param to your next fetch request to get the next + * page of results. Not provided if the returned result set is empty. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cursor(): Optional = cursor.getOptional("cursor") + + /** + * 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 + + /** + * 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 + + @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 + * [FetchExperimentEventsResponse]. + * + * The following fields are required: + * ```java + * .events() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FetchExperimentEventsResponse]. */ + class Builder internal constructor() { + + private var events: JsonField>? = null + private var cursor: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fetchExperimentEventsResponse: FetchExperimentEventsResponse) = apply { + events = fetchExperimentEventsResponse.events.map { it.toMutableList() } + cursor = fetchExperimentEventsResponse.cursor + additionalProperties = fetchExperimentEventsResponse.additionalProperties.toMutableMap() + } + + /** A list of fetched events */ + 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 [ExperimentEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: ExperimentEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } + } + + /** + * Pagination cursor + * + * Pass this string directly as the `cursor` param to your next fetch request to get the + * next page of results. Not provided if the returned result set is empty. + */ + fun cursor(cursor: String?) = cursor(JsonField.ofNullable(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. + */ + fun cursor(cursor: JsonField) = apply { this.cursor = cursor } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FetchExperimentEventsResponse]. + * + * 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(): FetchExperimentEventsResponse = + FetchExperimentEventsResponse( + checkRequired("events", events).map { it.toImmutable() }, + cursor, + 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 + } + + return other is FetchExperimentEventsResponse && + events == other.events && + cursor == other.cursor && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(events, cursor, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FetchExperimentEventsResponse{events=$events, cursor=$cursor, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..9b637b71 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponse.kt @@ -0,0 +1,245 @@ +// 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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class FetchProjectLogsEventsResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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") + + /** + * Pagination cursor + * + * Pass this string directly as the `cursor` param to your next fetch request to get the next + * page of results. Not provided if the returned result set is empty. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cursor(): Optional = cursor.getOptional("cursor") + + /** + * 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 + + /** + * 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 + + @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 + * [FetchProjectLogsEventsResponse]. + * + * The following fields are required: + * ```java + * .events() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FetchProjectLogsEventsResponse]. */ + class Builder internal constructor() { + + private var events: JsonField>? = null + private var cursor: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fetchProjectLogsEventsResponse: FetchProjectLogsEventsResponse) = apply { + events = fetchProjectLogsEventsResponse.events.map { it.toMutableList() } + cursor = fetchProjectLogsEventsResponse.cursor + additionalProperties = + fetchProjectLogsEventsResponse.additionalProperties.toMutableMap() + } + + /** A list of fetched events */ + 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 [ProjectLogsEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: ProjectLogsEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } + } + + /** + * Pagination cursor + * + * Pass this string directly as the `cursor` param to your next fetch request to get the + * next page of results. Not provided if the returned result set is empty. + */ + fun cursor(cursor: String?) = cursor(JsonField.ofNullable(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. + */ + fun cursor(cursor: JsonField) = apply { this.cursor = cursor } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FetchProjectLogsEventsResponse]. + * + * 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(): FetchProjectLogsEventsResponse = + FetchProjectLogsEventsResponse( + checkRequired("events", events).map { it.toImmutable() }, + cursor, + 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 + } + + return other is FetchProjectLogsEventsResponse && + events == other.events && + cursor == other.cursor && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(events, cursor, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FetchProjectLogsEventsResponse{events=$events, cursor=$cursor, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..3044df80 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Function.kt @@ -0,0 +1,4127 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.allMaxBy +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.getOrThrow +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 com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class Function +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The transaction id of an event is unique to the network operation that processed the event + * insertion. Transaction ids are monotonically increasing over time and can be used to retrieve + * a versioned snapshot of the prompt (see the `version` parameter) + * + * @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 _xactId(): String = _xactId.getRequired("_xact_id") + + /** + * @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") + + /** + * A literal 'p' which identifies the object as a project 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 logId(): LogId = logId.getRequired("log_id") + + /** + * Name of 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 name(): String = name.getRequired("name") + + /** + * Unique identifier for the organization + * + * @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 orgId(): String = orgId.getRequired("org_id") + + /** + * 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") + + /** + * 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") + + /** + * Date of prompt creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * 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") + + /** + * 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") + + /** + * User-controlled metadata about the prompt + * + * @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") + + /** + * @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") + + /** + * 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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_xactId]. + * + * Unlike [_xactId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_xact_id") @ExcludeMissing fun __xactId(): JsonField = _xactId + + /** + * Returns the raw JSON value of [functionData]. + * + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("function_data") + @ExcludeMissing + fun _functionData(): JsonField = functionData + + /** + * Returns the raw JSON value of [logId]. + * + * Unlike [logId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("log_id") @ExcludeMissing fun _logId(): JsonField = logId + + /** + * 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 [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [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 [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 [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [functionSchema]. + * + * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("function_schema") + @ExcludeMissing + fun _functionSchema(): JsonField = functionSchema + + /** + * 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 + + /** + * 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 [origin]. + * + * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("origin") @ExcludeMissing fun _origin(): JsonField = origin + + /** + * 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 [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 [Function]. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .functionData() + * .logId() + * .name() + * .orgId() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var _xactId: JsonField? = null + private var functionData: JsonField? = null + private var logId: JsonField? = null + private var name: JsonField? = null + private var orgId: JsonField? = null + private var projectId: JsonField? = null + private var slug: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var functionSchema: JsonField = JsonMissing.of() + private var functionType: JsonField = JsonMissing.of() + private var metadata: 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(function: Function) = apply { + id = function.id + _xactId = function._xactId + functionData = function.functionData + logId = function.logId + name = function.name + orgId = function.orgId + projectId = function.projectId + slug = function.slug + created = function.created + description = function.description + functionSchema = function.functionSchema + functionType = function.functionType + metadata = function.metadata + origin = function.origin + promptData = function.promptData + tags = function.tags.map { it.toMutableList() } + additionalProperties = function.additionalProperties.toMutableMap() + } + + /** Unique identifier for the prompt */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The transaction id of an event is unique to the network operation that processed the + * event insertion. Transaction ids are monotonically increasing over time and can be used + * to retrieve a versioned snapshot of the prompt (see the `version` parameter) + */ + fun _xactId(_xactId: String) = _xactId(JsonField.of(_xactId)) + + /** + * Sets [Builder._xactId] to an arbitrary JSON value. + * + * You should usually call [Builder._xactId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } + + 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)) + + /** A literal 'p' which identifies the object as a project prompt */ + fun logId(logId: LogId) = logId(JsonField.of(logId)) + + /** + * Sets [Builder.logId] to an arbitrary JSON value. + * + * You should usually call [Builder.logId] with a well-typed [LogId] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun logId(logId: JsonField) = apply { this.logId = logId } + + /** 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 organization */ + fun orgId(orgId: String) = orgId(JsonField.of(orgId)) + + /** + * 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 } + + /** 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 } + + /** Date of prompt creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** 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 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 + } + + /** User-controlled metadata about the prompt */ + 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 origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * 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 } + + /** 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 } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .functionData() + * .logId() + * .name() + * .orgId() + * .projectId() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("id", id), + checkRequired("_xactId", _xactId), + checkRequired("functionData", functionData), + checkRequired("logId", logId), + checkRequired("name", name), + checkRequired("orgId", orgId), + checkRequired("projectId", projectId), + checkRequired("slug", slug), + created, + description, + functionSchema, + functionType, + metadata, + origin, + promptData, + (tags ?: JsonMissing.of()).map { it.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 + private constructor( + private val prompt: Prompt? = null, + private val code: Code? = null, + private val global: Global? = null, + private val _json: JsonValue? = null, + ) { + + fun prompt(): Optional = Optional.ofNullable(prompt) + + fun code(): Optional = Optional.ofNullable(code) + + fun global(): Optional = Optional.ofNullable(global) + + fun isPrompt(): Boolean = prompt != null + + fun isCode(): Boolean = code != null + + fun isGlobal(): Boolean = global != null + + fun asPrompt(): Prompt = prompt.getOrThrow("prompt") + + fun asCode(): Code = code.getOrThrow("code") + + fun asGlobal(): Global = global.getOrThrow("global") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): FunctionData = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitPrompt(prompt: Prompt) { + prompt.validate() + } + + override fun visitCode(code: Code) { + code.validate() + } + + override fun visitGlobal(global: Global) { + global.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 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 + } + + return other is FunctionData && + prompt == other.prompt && + code == other.code && + global == other.global + } + + override fun hashCode(): Int = Objects.hash(prompt, code, global) + + override fun toString(): String = + when { + prompt != null -> "FunctionData{prompt=$prompt}" + code != null -> "FunctionData{code=$code}" + global != null -> "FunctionData{global=$global}" + _json != null -> "FunctionData{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FunctionData") + } + + companion object { + + @JvmStatic fun ofPrompt(prompt: Prompt) = FunctionData(prompt = prompt) + + @JvmStatic fun ofCode(code: Code) = FunctionData(code = code) + + @JvmStatic fun ofGlobal(global: Global) = FunctionData(global = global) + } + + /** + * An interface that defines how to map each variant of [FunctionData] to a value of type + * [T]. + */ + interface Visitor { + + fun visitPrompt(prompt: Prompt): T + + fun visitCode(code: Code): T + + fun visitGlobal(global: Global): T + + /** + * Maps an unknown variant of [FunctionData] to a value of type [T]. + * + * An instance of [FunctionData] 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 FunctionData: $json") + } + } + + internal class Deserializer : BaseDeserializer(FunctionData::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(FunctionData::class) { + + override fun serialize( + value: FunctionData, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.prompt != null -> generator.writeObject(value.prompt) + value.code != null -> generator.writeObject(value.code) + value.global != null -> generator.writeObject(value.global) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FunctionData") + } + } + } + + class Prompt + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Prompt]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Prompt]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(prompt: Prompt) = apply { + type = prompt.type + additionalProperties = prompt.additionalProperties.toMutableMap() + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Prompt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Prompt = + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROMPT = of("prompt") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + PROMPT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROMPT, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROMPT -> Value.PROMPT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + PROMPT -> Known.PROMPT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Prompt && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Prompt{type=$type, additionalProperties=$additionalProperties}" + } + + class Code + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @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") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Code]. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Code]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(code: Code) = apply { + data = code.data + type = code.type + additionalProperties = code.additionalProperties.toMutableMap() + } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * 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 [data] with `Data.ofBundle(bundle)`. */ + fun data(bundle: Data.Bundle) = data(Data.ofBundle(bundle)) + + /** Alias for calling [data] with `Data.ofInline(inline)`. */ + fun data(inline: Data.Inline) = data(Data.ofInline(inline)) + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Code]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Code = + Code( + checkRequired("data", data), + checkRequired("type", type), + 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 + private constructor( + private val bundle: Bundle? = null, + private val inline: Inline? = null, + private val _json: JsonValue? = null, + ) { + + fun bundle(): Optional = Optional.ofNullable(bundle) + + fun inline(): Optional = Optional.ofNullable(inline) + + fun isBundle(): Boolean = bundle != null + + fun isInline(): Boolean = inline != null + + fun asBundle(): Bundle = bundle.getOrThrow("bundle") + + fun asInline(): Inline = inline.getOrThrow("inline") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitBundle(bundle: Bundle) { + bundle.validate() + } + + override fun visitInline(inline: Inline) { + inline.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 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 + } + + return other is Data && bundle == other.bundle && inline == other.inline + } + + override fun hashCode(): Int = Objects.hash(bundle, inline) + + override fun toString(): String = + when { + bundle != null -> "Data{bundle=$bundle}" + inline != null -> "Data{inline=$inline}" + _json != null -> "Data{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Data") + } + + companion object { + + @JvmStatic fun ofBundle(bundle: Bundle) = Data(bundle = bundle) + + @JvmStatic fun ofInline(inline: Inline) = Data(inline = inline) + } + + /** + * An interface that defines how to map each variant of [Data] to a value of type + * [T]. + */ + interface Visitor { + + fun visitBundle(bundle: Bundle): T + + fun visitInline(inline: Inline): T + + /** + * Maps an unknown variant of [Data] to a value of type [T]. + * + * An instance of [Data] 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 Data: $json") + } + } + + internal class Deserializer : BaseDeserializer(Data::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Data { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Data::class) { + + override fun serialize( + value: Data, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.bundle != null -> generator.writeObject(value.bundle) + value.inline != null -> generator.writeObject(value.inline) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Data") + } + } + } + + class Bundle + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun bundleId(): String = bundleId.getRequired("bundle_id") + + /** + * @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 location(): CodeBundle.Location = location.getRequired("location") + + /** + * @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 runtimeContext(): CodeBundle.RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * A preview of the code + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun preview(): Optional = preview.getOptional("preview") + + /** + * @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") + + /** + * Returns the raw JSON value of [bundleId]. + * + * Unlike [bundleId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bundle_id") + @ExcludeMissing + fun _bundleId(): JsonField = bundleId + + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("location") + @ExcludeMissing + fun _location(): JsonField = location + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [preview]. + * + * Unlike [preview], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("preview") + @ExcludeMissing + fun _preview(): JsonField = preview + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Bundle]. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Bundle]. */ + class Builder internal constructor() { + + private var bundleId: JsonField? = null + private var location: JsonField? = null + private var runtimeContext: JsonField? = null + private var preview: JsonField = JsonMissing.of() + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(bundle: Bundle) = apply { + bundleId = bundle.bundleId + location = bundle.location + runtimeContext = bundle.runtimeContext + preview = bundle.preview + type = bundle.type + additionalProperties = bundle.additionalProperties.toMutableMap() + } + + fun bundleId(bundleId: String) = bundleId(JsonField.of(bundleId)) + + /** + * Sets [Builder.bundleId] to an arbitrary JSON value. + * + * You should usually call [Builder.bundleId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun bundleId(bundleId: JsonField) = apply { + this.bundleId = bundleId + } + + fun location(location: CodeBundle.Location) = + location(JsonField.of(location)) + + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed + * [CodeBundle.Location] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun location(location: JsonField) = apply { + this.location = location + } + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofExperiment(experiment)`. + */ + fun location(experiment: CodeBundle.Location.Experiment) = + location(CodeBundle.Location.ofExperiment(experiment)) + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofFunction(function)`. + */ + fun location(function: CodeBundle.Location.Function) = + location(CodeBundle.Location.ofFunction(function)) + + fun runtimeContext(runtimeContext: CodeBundle.RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [CodeBundle.RuntimeContext] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = + apply { + this.runtimeContext = runtimeContext + } + + /** A preview of the code */ + fun preview(preview: String?) = preview(JsonField.ofNullable(preview)) + + /** Alias for calling [Builder.preview] with `preview.orElse(null)`. */ + fun preview(preview: Optional) = preview(preview.getOrNull()) + + /** + * Sets [Builder.preview] to an arbitrary JSON value. + * + * You should usually call [Builder.preview] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun preview(preview: JsonField) = apply { this.preview = preview } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Bundle]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Bundle = + Bundle( + checkRequired("bundleId", bundleId), + checkRequired("location", location), + checkRequired("runtimeContext", runtimeContext), + preview, + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val BUNDLE = of("bundle") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + BUNDLE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + BUNDLE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + BUNDLE -> Value.BUNDLE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + BUNDLE -> Known.BUNDLE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Bundle && + bundleId == other.bundleId && + location == other.location && + runtimeContext == other.runtimeContext && + preview == other.preview && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + bundleId, + location, + runtimeContext, + preview, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" + } + + class Inline + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun code(): String = code.getRequired("code") + + /** + * @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 runtimeContext(): RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * @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") + + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Inline]. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Inline]. */ + class Builder internal constructor() { + + private var code: JsonField? = null + private var runtimeContext: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(inline: Inline) = apply { + code = inline.code + runtimeContext = inline.runtimeContext + type = inline.type + additionalProperties = inline.additionalProperties.toMutableMap() + } + + fun code(code: String) = code(JsonField.of(code)) + + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun code(code: JsonField) = apply { this.code = code } + + fun runtimeContext(runtimeContext: RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [RuntimeContext] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = apply { + this.runtimeContext = runtimeContext + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Inline]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Inline = + Inline( + checkRequired("code", code), + checkRequired("runtimeContext", runtimeContext), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun runtime(): Runtime = runtime.getRequired("runtime") + + /** + * @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 version(): String = version.getRequired("version") + + /** + * Returns the raw JSON value of [runtime]. + * + * Unlike [runtime], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime") + @ExcludeMissing + fun _runtime(): JsonField = runtime + + /** + * 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 + + @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 + * [RuntimeContext]. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuntimeContext]. */ + class Builder internal constructor() { + + private var runtime: JsonField? = null + private var version: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(runtimeContext: RuntimeContext) = apply { + runtime = runtimeContext.runtime + version = runtimeContext.version + additionalProperties = + runtimeContext.additionalProperties.toMutableMap() + } + + fun runtime(runtime: Runtime) = runtime(JsonField.of(runtime)) + + /** + * Sets [Builder.runtime] to an arbitrary JSON value. + * + * You should usually call [Builder.runtime] with a well-typed [Runtime] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun runtime(runtime: JsonField) = apply { + this.runtime = runtime + } + + fun version(version: String) = version(JsonField.of(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 { + this.version = version + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuntimeContext]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RuntimeContext = + RuntimeContext( + checkRequired("runtime", runtime), + checkRequired("version", version), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from + * data that doesn't match any known member, and you want to know that + * value. For example, if the SDK is on an older version than the API, + * then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val NODE = of("node") + + @JvmField val PYTHON = of("python") + + @JvmStatic fun of(value: String) = Runtime(JsonField.of(value)) + } + + /** An enum containing [Runtime]'s known values. */ + enum class Known { + NODE, + PYTHON, + } + + /** + * An enum containing [Runtime]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Runtime] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + NODE, + PYTHON, + /** + * An enum member indicating that [Runtime] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, + * or [Value._UNKNOWN] if the class was instantiated with an unknown + * value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + NODE -> Value.NODE + PYTHON -> Value.PYTHON + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is + * always known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value + * is a not a known member. + */ + fun known(): Known = + when (this) { + NODE -> Known.NODE + PYTHON -> Known.PYTHON + else -> + throw BraintrustInvalidDataException( + "Unknown Runtime: $value" + ) + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is + * primarily for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Runtime && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RuntimeContext && + runtime == other.runtime && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(runtime, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuntimeContext{runtime=$runtime, version=$version, additionalProperties=$additionalProperties}" + } + + class Type + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val INLINE = of("inline") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + INLINE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + INLINE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + INLINE -> Value.INLINE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + INLINE -> Known.INLINE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Inline && + code == other.code && + runtimeContext == other.runtimeContext && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(code, runtimeContext, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Inline{code=$code, runtimeContext=$runtimeContext, type=$type, additionalProperties=$additionalProperties}" + } + } + + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CODE = of("code") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + CODE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + CODE, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + CODE -> Value.CODE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + CODE -> Known.CODE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Code && + data == other.data && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(data, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" + } + + class Global + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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") + + /** + * 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 [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Global]. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Global]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(global: Global) = apply { + name = global.name + type = global.type + additionalProperties = global.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Global]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Global = + Global( + checkRequired("name", name), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GLOBAL = of("global") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + GLOBAL + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GLOBAL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GLOBAL -> Value.GLOBAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GLOBAL -> Known.GLOBAL + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Global && + name == other.name && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Global{name=$name, type=$type, additionalProperties=$additionalProperties}" + } + } + + /** A literal 'p' which identifies the object as a project prompt */ + class LogId @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val P = of("p") + + @JvmStatic fun of(value: String) = LogId(JsonField.of(value)) + } + + /** An enum containing [LogId]'s known values. */ + enum class Known { + P + } + + /** + * An enum containing [LogId]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [LogId] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + P, + /** An enum member indicating that [LogId] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + P -> Value.P + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + P -> Known.P + else -> throw BraintrustInvalidDataException("Unknown LogId: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is LogId && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** JSON schema for the function's parameters and return type */ + class FunctionSchema + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FunctionSchema]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionSchema]. */ + class Builder internal constructor() { + + private var parameters: JsonValue = JsonMissing.of() + private var returns: JsonValue = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionSchema: FunctionSchema) = apply { + parameters = functionSchema.parameters + returns = functionSchema.returns + additionalProperties = functionSchema.additionalProperties.toMutableMap() + } + + fun parameters(parameters: JsonValue) = apply { this.parameters = parameters } + + fun returns(returns: JsonValue) = apply { this.returns = returns } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionSchema = + 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 + } + + return other is FunctionSchema && + parameters == other.parameters && + returns == other.returns && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(parameters, returns, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionSchema{parameters=$parameters, returns=$returns, additionalProperties=$additionalProperties}" + } + + class FunctionType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM = of("llm") + + @JvmField val SCORER = of("scorer") + + @JvmField val TASK = of("task") + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = FunctionType(JsonField.of(value)) + } + + /** An enum containing [FunctionType]'s known values. */ + enum class Known { + LLM, + SCORER, + TASK, + TOOL, + } + + /** + * An enum containing [FunctionType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [FunctionType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM, + SCORER, + TASK, + TOOL, + /** + * An enum member indicating that [FunctionType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM -> Value.LLM + SCORER -> Value.SCORER + TASK -> Value.TASK + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LLM -> Known.LLM + SCORER -> Known.SCORER + TASK -> Known.TASK + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown FunctionType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is FunctionType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** User-controlled metadata about the prompt */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class Origin + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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") + + /** + * The function exists for internal purposes and should not be displayed in the list of + * functions. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun internal_(): Optional = internal_.getOptional("internal") + + /** + * 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 + + /** + * Returns the raw JSON value of [internal_]. + * + * Unlike [internal_], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("internal") @ExcludeMissing fun _internal_(): JsonField = internal_ + + @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 [Origin]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Origin]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var internal_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(origin: Origin) = apply { + objectId = origin.objectId + objectType = origin.objectType + internal_ = origin.internal_ + additionalProperties = origin.additionalProperties.toMutableMap() + } + + /** Id of the object the function is originating from */ + 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 + } + + /** + * The function exists for internal purposes and should not be displayed in the list of + * functions. + */ + fun internal_(internal_: Boolean?) = internal_(JsonField.ofNullable(internal_)) + + /** + * Alias for [Builder.internal_]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun internal_(internal_: Boolean) = internal_(internal_ as Boolean?) + + /** Alias for calling [Builder.internal_] with `internal_.orElse(null)`. */ + fun internal_(internal_: Optional) = internal_(internal_.getOrNull()) + + /** + * Sets [Builder.internal_] to an arbitrary JSON value. + * + * You should usually call [Builder.internal_] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun internal_(internal_: JsonField) = apply { this.internal_ = internal_ } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Origin]. + * + * 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(): Origin = + Origin( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + internal_, + 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 + } + + return other is Origin && + objectId == other.objectId && + objectType == other.objectType && + internal_ == other.internal_ && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(objectId, objectType, internal_, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Origin{objectId=$objectId, objectType=$objectType, internal_=$internal_, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + id == other.id && + _xactId == other._xactId && + functionData == other.functionData && + logId == other.logId && + name == other.name && + orgId == other.orgId && + projectId == other.projectId && + slug == other.slug && + created == other.created && + description == other.description && + functionSchema == other.functionSchema && + functionType == other.functionType && + metadata == other.metadata && + origin == other.origin && + promptData == other.promptData && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _xactId, + functionData, + logId, + name, + orgId, + projectId, + slug, + created, + description, + functionSchema, + functionType, + metadata, + origin, + promptData, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{id=$id, _xactId=$_xactId, functionData=$functionData, logId=$logId, name=$name, orgId=$orgId, projectId=$projectId, slug=$slug, created=$created, description=$description, functionSchema=$functionSchema, functionType=$functionType, metadata=$metadata, origin=$origin, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..bce0ea6e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionCreateParams.kt @@ -0,0 +1,4216 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Create a new function. If there is an existing function in the project with the same slug as the + * one specified in the request, will return the existing function unmodified + */ +class FunctionCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * @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 = body.functionData() + + /** + * Name of 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 name(): String = body.name() + + /** + * 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 = body.projectId() + + /** + * 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 = body.slug() + + /** + * 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 = body.description() + + /** + * 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 = body.functionSchema() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionType(): Optional = body.functionType() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun origin(): Optional = body.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 = body.promptData() + + /** + * 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> = body.tags() + + /** + * Returns the raw JSON value of [functionData]. + * + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionData(): JsonField = body._functionData() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [slug]. + * + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _slug(): JsonField = body._slug() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [functionSchema]. + * + * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionSchema(): JsonField = body._functionSchema() + + /** + * Returns the raw JSON value of [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionType(): JsonField = body._functionType() + + /** + * Returns the raw JSON value of [origin]. + * + * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _origin(): JsonField = body._origin() + + /** + * Returns the raw JSON value of [promptData]. + * + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _promptData(): JsonField = body._promptData() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FunctionCreateParams]. + * + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionCreateParams]. */ + 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(functionCreateParams: FunctionCreateParams) = apply { + body = functionCreateParams.body.toBuilder() + additionalHeaders = functionCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = functionCreateParams.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: + * - [functionData] + * - [name] + * - [projectId] + * - [slug] + * - [description] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun functionData(functionData: FunctionData) = apply { body.functionData(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 { + 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) } + + /** + * 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 prompt 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) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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 { + 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()) + + /** + * 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 { + 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()) + + /** + * 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 { 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()) + + /** + * 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 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 [FunctionCreateParams]. + * + * 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(): FunctionCreateParams = + FunctionCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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(), + ) + + /** + * @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 + * + * @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 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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 [functionData]. + * + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_data") + @ExcludeMissing + fun _functionData(): JsonField = functionData + + /** + * 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 [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 [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 [functionSchema]. + * + * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_schema") + @ExcludeMissing + fun _functionSchema(): JsonField = functionSchema + + /** + * 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 + + /** + * 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 + + /** + * 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 [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]. + * + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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 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 + } + + fun origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * 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 } + + /** 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 + } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + 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 a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @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 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + functionData, + name, + projectId, + slug, + description, + functionSchema, + functionType, + origin, + promptData, + tags, + additionalProperties, + ) + } + + 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) + @JsonSerialize(using = FunctionData.Serializer::class) + class FunctionData + private constructor( + private val prompt: Prompt? = null, + private val code: Code? = null, + private val global: Global? = null, + private val _json: JsonValue? = null, + ) { + + fun prompt(): Optional = Optional.ofNullable(prompt) + + fun code(): Optional = Optional.ofNullable(code) + + fun global(): Optional = Optional.ofNullable(global) + + fun isPrompt(): Boolean = prompt != null + + fun isCode(): Boolean = code != null + + fun isGlobal(): Boolean = global != null + + fun asPrompt(): Prompt = prompt.getOrThrow("prompt") + + fun asCode(): Code = code.getOrThrow("code") + + fun asGlobal(): Global = global.getOrThrow("global") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): FunctionData = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitPrompt(prompt: Prompt) { + prompt.validate() + } + + override fun visitCode(code: Code) { + code.validate() + } + + override fun visitGlobal(global: Global) { + global.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 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 + } + + return other is FunctionData && + prompt == other.prompt && + code == other.code && + global == other.global + } + + override fun hashCode(): Int = Objects.hash(prompt, code, global) + + override fun toString(): String = + when { + prompt != null -> "FunctionData{prompt=$prompt}" + code != null -> "FunctionData{code=$code}" + global != null -> "FunctionData{global=$global}" + _json != null -> "FunctionData{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FunctionData") + } + + companion object { + + @JvmStatic fun ofPrompt(prompt: Prompt) = FunctionData(prompt = prompt) + + @JvmStatic fun ofCode(code: Code) = FunctionData(code = code) + + @JvmStatic fun ofGlobal(global: Global) = FunctionData(global = global) + } + + /** + * An interface that defines how to map each variant of [FunctionData] to a value of type + * [T]. + */ + interface Visitor { + + fun visitPrompt(prompt: Prompt): T + + fun visitCode(code: Code): T + + fun visitGlobal(global: Global): T + + /** + * Maps an unknown variant of [FunctionData] to a value of type [T]. + * + * An instance of [FunctionData] 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 FunctionData: $json") + } + } + + internal class Deserializer : BaseDeserializer(FunctionData::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(FunctionData::class) { + + override fun serialize( + value: FunctionData, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.prompt != null -> generator.writeObject(value.prompt) + value.code != null -> generator.writeObject(value.code) + value.global != null -> generator.writeObject(value.global) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FunctionData") + } + } + } + + class Prompt + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Prompt]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Prompt]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(prompt: Prompt) = apply { + type = prompt.type + additionalProperties = prompt.additionalProperties.toMutableMap() + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Prompt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Prompt = + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROMPT = of("prompt") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + PROMPT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROMPT, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROMPT -> Value.PROMPT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + PROMPT -> Known.PROMPT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Prompt && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Prompt{type=$type, additionalProperties=$additionalProperties}" + } + + class Code + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @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") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Code]. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Code]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(code: Code) = apply { + data = code.data + type = code.type + additionalProperties = code.additionalProperties.toMutableMap() + } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * 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 [data] with `Data.ofBundle(bundle)`. */ + fun data(bundle: Data.Bundle) = data(Data.ofBundle(bundle)) + + /** Alias for calling [data] with `Data.ofInline(inline)`. */ + fun data(inline: Data.Inline) = data(Data.ofInline(inline)) + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Code]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Code = + Code( + checkRequired("data", data), + checkRequired("type", type), + 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 + private constructor( + private val bundle: Bundle? = null, + private val inline: Inline? = null, + private val _json: JsonValue? = null, + ) { + + fun bundle(): Optional = Optional.ofNullable(bundle) + + fun inline(): Optional = Optional.ofNullable(inline) + + fun isBundle(): Boolean = bundle != null + + fun isInline(): Boolean = inline != null + + fun asBundle(): Bundle = bundle.getOrThrow("bundle") + + fun asInline(): Inline = inline.getOrThrow("inline") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitBundle(bundle: Bundle) { + bundle.validate() + } + + override fun visitInline(inline: Inline) { + inline.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 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 + } + + return other is Data && bundle == other.bundle && inline == other.inline + } + + override fun hashCode(): Int = Objects.hash(bundle, inline) + + override fun toString(): String = + when { + bundle != null -> "Data{bundle=$bundle}" + inline != null -> "Data{inline=$inline}" + _json != null -> "Data{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Data") + } + + companion object { + + @JvmStatic fun ofBundle(bundle: Bundle) = Data(bundle = bundle) + + @JvmStatic fun ofInline(inline: Inline) = Data(inline = inline) + } + + /** + * An interface that defines how to map each variant of [Data] to a value of type + * [T]. + */ + interface Visitor { + + fun visitBundle(bundle: Bundle): T + + fun visitInline(inline: Inline): T + + /** + * Maps an unknown variant of [Data] to a value of type [T]. + * + * An instance of [Data] 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 Data: $json") + } + } + + internal class Deserializer : BaseDeserializer(Data::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Data { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Data::class) { + + override fun serialize( + value: Data, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.bundle != null -> generator.writeObject(value.bundle) + value.inline != null -> generator.writeObject(value.inline) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Data") + } + } + } + + class Bundle + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun bundleId(): String = bundleId.getRequired("bundle_id") + + /** + * @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 location(): CodeBundle.Location = location.getRequired("location") + + /** + * @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 runtimeContext(): CodeBundle.RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * A preview of the code + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun preview(): Optional = preview.getOptional("preview") + + /** + * @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") + + /** + * Returns the raw JSON value of [bundleId]. + * + * Unlike [bundleId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bundle_id") + @ExcludeMissing + fun _bundleId(): JsonField = bundleId + + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("location") + @ExcludeMissing + fun _location(): JsonField = location + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [preview]. + * + * Unlike [preview], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("preview") + @ExcludeMissing + fun _preview(): JsonField = preview + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Bundle]. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Bundle]. */ + class Builder internal constructor() { + + private var bundleId: JsonField? = null + private var location: JsonField? = null + private var runtimeContext: JsonField? = null + private var preview: JsonField = JsonMissing.of() + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(bundle: Bundle) = apply { + bundleId = bundle.bundleId + location = bundle.location + runtimeContext = bundle.runtimeContext + preview = bundle.preview + type = bundle.type + additionalProperties = bundle.additionalProperties.toMutableMap() + } + + fun bundleId(bundleId: String) = bundleId(JsonField.of(bundleId)) + + /** + * Sets [Builder.bundleId] to an arbitrary JSON value. + * + * You should usually call [Builder.bundleId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun bundleId(bundleId: JsonField) = apply { + this.bundleId = bundleId + } + + fun location(location: CodeBundle.Location) = + location(JsonField.of(location)) + + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed + * [CodeBundle.Location] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun location(location: JsonField) = apply { + this.location = location + } + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofExperiment(experiment)`. + */ + fun location(experiment: CodeBundle.Location.Experiment) = + location(CodeBundle.Location.ofExperiment(experiment)) + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofFunction(function)`. + */ + fun location(function: CodeBundle.Location.Function) = + location(CodeBundle.Location.ofFunction(function)) + + fun runtimeContext(runtimeContext: CodeBundle.RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [CodeBundle.RuntimeContext] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = + apply { + this.runtimeContext = runtimeContext + } + + /** A preview of the code */ + fun preview(preview: String?) = preview(JsonField.ofNullable(preview)) + + /** Alias for calling [Builder.preview] with `preview.orElse(null)`. */ + fun preview(preview: Optional) = preview(preview.getOrNull()) + + /** + * Sets [Builder.preview] to an arbitrary JSON value. + * + * You should usually call [Builder.preview] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun preview(preview: JsonField) = apply { this.preview = preview } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Bundle]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Bundle = + Bundle( + checkRequired("bundleId", bundleId), + checkRequired("location", location), + checkRequired("runtimeContext", runtimeContext), + preview, + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val BUNDLE = of("bundle") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + BUNDLE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + BUNDLE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + BUNDLE -> Value.BUNDLE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + BUNDLE -> Known.BUNDLE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Bundle && + bundleId == other.bundleId && + location == other.location && + runtimeContext == other.runtimeContext && + preview == other.preview && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + bundleId, + location, + runtimeContext, + preview, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" + } + + class Inline + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun code(): String = code.getRequired("code") + + /** + * @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 runtimeContext(): RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * @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") + + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Inline]. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Inline]. */ + class Builder internal constructor() { + + private var code: JsonField? = null + private var runtimeContext: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(inline: Inline) = apply { + code = inline.code + runtimeContext = inline.runtimeContext + type = inline.type + additionalProperties = inline.additionalProperties.toMutableMap() + } + + fun code(code: String) = code(JsonField.of(code)) + + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun code(code: JsonField) = apply { this.code = code } + + fun runtimeContext(runtimeContext: RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [RuntimeContext] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = apply { + this.runtimeContext = runtimeContext + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Inline]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Inline = + Inline( + checkRequired("code", code), + checkRequired("runtimeContext", runtimeContext), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun runtime(): Runtime = runtime.getRequired("runtime") + + /** + * @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 version(): String = version.getRequired("version") + + /** + * Returns the raw JSON value of [runtime]. + * + * Unlike [runtime], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime") + @ExcludeMissing + fun _runtime(): JsonField = runtime + + /** + * 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 + + @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 + * [RuntimeContext]. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuntimeContext]. */ + class Builder internal constructor() { + + private var runtime: JsonField? = null + private var version: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(runtimeContext: RuntimeContext) = apply { + runtime = runtimeContext.runtime + version = runtimeContext.version + additionalProperties = + runtimeContext.additionalProperties.toMutableMap() + } + + fun runtime(runtime: Runtime) = runtime(JsonField.of(runtime)) + + /** + * Sets [Builder.runtime] to an arbitrary JSON value. + * + * You should usually call [Builder.runtime] with a well-typed [Runtime] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun runtime(runtime: JsonField) = apply { + this.runtime = runtime + } + + fun version(version: String) = version(JsonField.of(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 { + this.version = version + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuntimeContext]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RuntimeContext = + RuntimeContext( + checkRequired("runtime", runtime), + checkRequired("version", version), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from + * data that doesn't match any known member, and you want to know that + * value. For example, if the SDK is on an older version than the API, + * then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val NODE = of("node") + + @JvmField val PYTHON = of("python") + + @JvmStatic fun of(value: String) = Runtime(JsonField.of(value)) + } + + /** An enum containing [Runtime]'s known values. */ + enum class Known { + NODE, + PYTHON, + } + + /** + * An enum containing [Runtime]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Runtime] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + NODE, + PYTHON, + /** + * An enum member indicating that [Runtime] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, + * or [Value._UNKNOWN] if the class was instantiated with an unknown + * value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + NODE -> Value.NODE + PYTHON -> Value.PYTHON + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is + * always known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value + * is a not a known member. + */ + fun known(): Known = + when (this) { + NODE -> Known.NODE + PYTHON -> Known.PYTHON + else -> + throw BraintrustInvalidDataException( + "Unknown Runtime: $value" + ) + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is + * primarily for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Runtime && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RuntimeContext && + runtime == other.runtime && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(runtime, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuntimeContext{runtime=$runtime, version=$version, additionalProperties=$additionalProperties}" + } + + class Type + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val INLINE = of("inline") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + INLINE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + INLINE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + INLINE -> Value.INLINE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + INLINE -> Known.INLINE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Inline && + code == other.code && + runtimeContext == other.runtimeContext && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(code, runtimeContext, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Inline{code=$code, runtimeContext=$runtimeContext, type=$type, additionalProperties=$additionalProperties}" + } + } + + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CODE = of("code") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + CODE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + CODE, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + CODE -> Value.CODE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + CODE -> Known.CODE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Code && + data == other.data && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(data, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" + } + + class Global + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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") + + /** + * 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 [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Global]. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Global]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(global: Global) = apply { + name = global.name + type = global.type + additionalProperties = global.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Global]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Global = + Global( + checkRequired("name", name), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GLOBAL = of("global") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + GLOBAL + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GLOBAL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GLOBAL -> Value.GLOBAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GLOBAL -> Known.GLOBAL + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Global && + name == other.name && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Global{name=$name, type=$type, additionalProperties=$additionalProperties}" + } + } + + /** JSON schema for the function's parameters and return type */ + class FunctionSchema + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FunctionSchema]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionSchema]. */ + class Builder internal constructor() { + + private var parameters: JsonValue = JsonMissing.of() + private var returns: JsonValue = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionSchema: FunctionSchema) = apply { + parameters = functionSchema.parameters + returns = functionSchema.returns + additionalProperties = functionSchema.additionalProperties.toMutableMap() + } + + fun parameters(parameters: JsonValue) = apply { this.parameters = parameters } + + fun returns(returns: JsonValue) = apply { this.returns = returns } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionSchema = + 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 + } + + return other is FunctionSchema && + parameters == other.parameters && + returns == other.returns && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(parameters, returns, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionSchema{parameters=$parameters, returns=$returns, additionalProperties=$additionalProperties}" + } + + class FunctionType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM = of("llm") + + @JvmField val SCORER = of("scorer") + + @JvmField val TASK = of("task") + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = FunctionType(JsonField.of(value)) + } + + /** An enum containing [FunctionType]'s known values. */ + enum class Known { + LLM, + SCORER, + TASK, + TOOL, + } + + /** + * An enum containing [FunctionType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [FunctionType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM, + SCORER, + TASK, + TOOL, + /** + * An enum member indicating that [FunctionType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM -> Value.LLM + SCORER -> Value.SCORER + TASK -> Value.TASK + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LLM -> Known.LLM + SCORER -> Known.SCORER + TASK -> Known.TASK + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown FunctionType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is FunctionType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Origin + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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") + + /** + * The function exists for internal purposes and should not be displayed in the list of + * functions. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun internal_(): Optional = internal_.getOptional("internal") + + /** + * 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 + + /** + * Returns the raw JSON value of [internal_]. + * + * Unlike [internal_], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("internal") @ExcludeMissing fun _internal_(): JsonField = internal_ + + @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 [Origin]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Origin]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var internal_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(origin: Origin) = apply { + objectId = origin.objectId + objectType = origin.objectType + internal_ = origin.internal_ + additionalProperties = origin.additionalProperties.toMutableMap() + } + + /** Id of the object the function is originating from */ + 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 + } + + /** + * The function exists for internal purposes and should not be displayed in the list of + * functions. + */ + fun internal_(internal_: Boolean?) = internal_(JsonField.ofNullable(internal_)) + + /** + * Alias for [Builder.internal_]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun internal_(internal_: Boolean) = internal_(internal_ as Boolean?) + + /** Alias for calling [Builder.internal_] with `internal_.orElse(null)`. */ + fun internal_(internal_: Optional) = internal_(internal_.getOrNull()) + + /** + * Sets [Builder.internal_] to an arbitrary JSON value. + * + * You should usually call [Builder.internal_] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun internal_(internal_: JsonField) = apply { this.internal_ = internal_ } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Origin]. + * + * 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(): Origin = + Origin( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + internal_, + 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 + } + + return other is Origin && + objectId == other.objectId && + objectType == other.objectType && + internal_ == other.internal_ && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(objectId, objectType, internal_, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Origin{objectId=$objectId, objectType=$objectType, internal_=$internal_, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FunctionCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..5ae4c720 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete a function object by its id */ +class FunctionDeleteParams +private constructor( + private val functionId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** Function id */ + fun functionId(): Optional = Optional.ofNullable(functionId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FunctionDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FunctionDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionDeleteParams]. */ + class Builder internal constructor() { + + private var functionId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionDeleteParams: FunctionDeleteParams) = apply { + functionId = functionDeleteParams.functionId + additionalHeaders = functionDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = functionDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = functionDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** Function id */ + fun functionId(functionId: String?) = apply { this.functionId = functionId } + + /** Alias for calling [Builder.functionId] with `functionId.orElse(null)`. */ + fun functionId(functionId: Optional) = functionId(functionId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [FunctionDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionDeleteParams = + FunctionDeleteParams( + functionId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is FunctionDeleteParams && + functionId == other.functionId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(functionId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "FunctionDeleteParams{functionId=$functionId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100644 index 00000000..5700fbb5 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeParams.kt @@ -0,0 +1,5206 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Invoke a function. */ +class FunctionInvokeParams +private constructor( + private val functionId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Function id */ + fun functionId(): Optional = Optional.ofNullable(functionId) + + /** The expected output of the function */ + fun _expected(): JsonValue = body._expected() + + /** Argument to the function, which can be any JSON serializable value */ + fun _input(): JsonValue = body._input() + + /** + * If the function is an LLM, additional messages to pass along to it + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun messages(): Optional> = body.messages() + + /** + * Any relevant metadata + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = body.metadata() + + /** + * The mode format of the returned value (defaults to 'auto') + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun mode(): Optional = body.mode() + + /** + * Options for tracing the function call + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun parent(): Optional = body.parent() + + /** + * Whether to stream the response. If true, results will be returned in the Braintrust SSE + * format. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun stream(): Optional = body.stream() + + /** + * The version of the function + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun version(): Optional = body.version() + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _messages(): JsonField> = body._messages() + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _metadata(): JsonField = body._metadata() + + /** + * Returns the raw JSON value of [mode]. + * + * Unlike [mode], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _mode(): JsonField = body._mode() + + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _parent(): JsonField = body._parent() + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _stream(): JsonField = body._stream() + + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _version(): JsonField = body._version() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FunctionInvokeParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FunctionInvokeParams]. */ + @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 } + + /** Alias for calling [Builder.functionId] with `functionId.orElse(null)`. */ + fun functionId(functionId: Optional) = functionId(functionId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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 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. + */ + fun build(): FunctionInvokeParams = + FunctionInvokeParams( + 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 */ + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + + /** Argument to the function, which can be any JSON serializable value */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonValue = input + + /** + * If the function is an LLM, additional messages to pass along to it + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun messages(): Optional> = messages.getOptional("messages") + + /** + * Any relevant metadata + * + * @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") + + /** + * The mode format of the returned value (defaults to 'auto') + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun mode(): Optional = mode.getOptional("mode") + + /** + * Options for tracing the function call + * + * @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") + + /** + * Whether to stream the response. If true, results will be returned in the Braintrust SSE + * format. + * + * @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") + + /** + * The version of the function + * + * @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") + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("messages") + @ExcludeMissing + fun _messages(): JsonField> = messages + + /** + * Returns the raw JSON value of [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 [mode]. + * + * Unlike [mode], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("mode") @ExcludeMissing fun _mode(): JsonField = mode + + /** + * Returns the raw JSON value of [parent]. + * + * Unlike [parent], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("parent") @ExcludeMissing fun _parent(): JsonField = parent + + /** + * Returns the raw JSON value of [stream]. + * + * Unlike [stream], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stream") @ExcludeMissing fun _stream(): JsonField = stream + + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("version") @ExcludeMissing fun _version(): JsonField = version + + @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 expected: JsonValue = JsonMissing.of() + private var input: JsonValue = JsonMissing.of() + private var messages: JsonField>? = null + private var metadata: JsonField = JsonMissing.of() + private var mode: JsonField = JsonMissing.of() + private var parent: JsonField = JsonMissing.of() + private var stream: JsonField = JsonMissing.of() + private var version: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + expected = body.expected + input = body.input + messages = body.messages.map { it.toMutableList() } + metadata = body.metadata + mode = body.mode + parent = body.parent + stream = body.stream + version = body.version + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** The expected output of the function */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** Argument to the function, which can be any JSON serializable value */ + fun input(input: JsonValue) = apply { this.input = input } + + /** If the function is an LLM, additional messages to pass along to it */ + fun messages(messages: List) = messages(JsonField.of(messages)) + + /** + * Sets [Builder.messages] to an arbitrary JSON value. + * + * You should usually call [Builder.messages] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun messages(messages: JsonField>) = apply { + this.messages = messages.map { it.toMutableList() } + } + + /** + * Adds a single [Message] to [messages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMessage(message: Message) = apply { + messages = + (messages ?: JsonField.of(mutableListOf())).also { + checkKnown("messages", it).add(message) + } + } + + /** Alias for calling [addMessage] with `Message.ofSystem(system)`. */ + fun addMessage(system: Message.System) = addMessage(Message.ofSystem(system)) + + /** Alias for calling [addMessage] with `Message.ofUser(user)`. */ + fun addMessage(user: Message.User) = addMessage(Message.ofUser(user)) + + /** Alias for calling [addMessage] with `Message.ofAssistant(assistant)`. */ + fun addMessage(assistant: Message.Assistant) = + addMessage(Message.ofAssistant(assistant)) + + /** Alias for calling [addMessage] with `Message.ofTool(tool)`. */ + fun addMessage(tool: Message.Tool) = addMessage(Message.ofTool(tool)) + + /** Alias for calling [addMessage] with `Message.ofFunction(function)`. */ + fun addMessage(function: Message.Function) = addMessage(Message.ofFunction(function)) + + /** Alias for calling [addMessage] with `Message.ofFallback(fallback)`. */ + fun addMessage(fallback: Message.Fallback) = addMessage(Message.ofFallback(fallback)) + + /** Any relevant metadata */ + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * 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 } + + /** The mode format of the returned value (defaults to 'auto') */ + fun mode(mode: Mode?) = mode(JsonField.ofNullable(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 { this.mode = mode } + + /** Options for tracing the function call */ + 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)) + + /** + * Whether to stream the response. If true, results will be returned in the Braintrust + * SSE format. + */ + fun stream(stream: Boolean?) = stream(JsonField.ofNullable(stream)) + + /** + * Alias for [Builder.stream]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun stream(stream: Boolean) = stream(stream as Boolean?) + + /** Alias for calling [Builder.stream] with `stream.orElse(null)`. */ + fun stream(stream: Optional) = stream(stream.getOrNull()) + + /** + * Sets [Builder.stream] to an arbitrary JSON value. + * + * You should usually call [Builder.stream] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun stream(stream: JsonField) = apply { this.stream = stream } + + /** The version of the function */ + fun version(version: String) = version(JsonField.of(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 { this.version = version } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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( + expected, + input, + (messages ?: JsonMissing.of()).map { it.toImmutable() }, + metadata, + mode, + parent, + stream, + version, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + messages().ifPresent { it.forEach { it.validate() } } + metadata().ifPresent { it.validate() } + mode().ifPresent { it.validate() } + parent().ifPresent { it.validate() } + stream() + 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 = + (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + expected, + input, + messages, + metadata, + mode, + parent, + stream, + version, + additionalProperties, + ) + } + + 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}" + } + + @JsonDeserialize(using = Message.Deserializer::class) + @JsonSerialize(using = Message.Serializer::class) + class Message + private constructor( + private val system: System? = null, + private val user: User? = null, + private val assistant: Assistant? = null, + private val tool: Tool? = null, + private val function: Function? = null, + private val fallback: Fallback? = null, + private val _json: JsonValue? = null, + ) { + + fun system(): Optional = Optional.ofNullable(system) + + fun user(): Optional = Optional.ofNullable(user) + + fun assistant(): Optional = Optional.ofNullable(assistant) + + fun tool(): Optional = Optional.ofNullable(tool) + + fun function(): Optional = Optional.ofNullable(function) + + fun fallback(): Optional = Optional.ofNullable(fallback) + + fun isSystem(): Boolean = system != null + + fun isUser(): Boolean = user != null + + fun isAssistant(): Boolean = assistant != null + + fun isTool(): Boolean = tool != null + + fun isFunction(): Boolean = function != null + + fun isFallback(): Boolean = fallback != null + + fun asSystem(): System = system.getOrThrow("system") + + fun asUser(): User = user.getOrThrow("user") + + fun asAssistant(): Assistant = assistant.getOrThrow("assistant") + + fun asTool(): Tool = tool.getOrThrow("tool") + + fun asFunction(): Function = function.getOrThrow("function") + + fun asFallback(): Fallback = fallback.getOrThrow("fallback") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + system != null -> visitor.visitSystem(system) + user != null -> visitor.visitUser(user) + assistant != null -> visitor.visitAssistant(assistant) + tool != null -> visitor.visitTool(tool) + function != null -> visitor.visitFunction(function) + fallback != null -> visitor.visitFallback(fallback) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Message = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitSystem(system: System) { + system.validate() + } + + override fun visitUser(user: User) { + user.validate() + } + + override fun visitAssistant(assistant: Assistant) { + assistant.validate() + } + + override fun visitTool(tool: Tool) { + tool.validate() + } + + override fun visitFunction(function: Function) { + function.validate() + } + + override fun visitFallback(fallback: Fallback) { + fallback.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 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 + } + + return other is Message && + system == other.system && + user == other.user && + assistant == other.assistant && + tool == other.tool && + function == other.function && + fallback == other.fallback + } + + override fun hashCode(): Int = + Objects.hash(system, user, assistant, tool, function, fallback) + + override fun toString(): String = + when { + system != null -> "Message{system=$system}" + user != null -> "Message{user=$user}" + assistant != null -> "Message{assistant=$assistant}" + tool != null -> "Message{tool=$tool}" + function != null -> "Message{function=$function}" + fallback != null -> "Message{fallback=$fallback}" + _json != null -> "Message{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Message") + } + + companion object { + + @JvmStatic fun ofSystem(system: System) = Message(system = system) + + @JvmStatic fun ofUser(user: User) = Message(user = user) + + @JvmStatic fun ofAssistant(assistant: Assistant) = Message(assistant = assistant) + + @JvmStatic fun ofTool(tool: Tool) = Message(tool = tool) + + @JvmStatic fun ofFunction(function: Function) = Message(function = function) + + @JvmStatic fun ofFallback(fallback: Fallback) = Message(fallback = fallback) + } + + /** + * An interface that defines how to map each variant of [Message] to a value of type [T]. + */ + interface Visitor { + + fun visitSystem(system: System): T + + fun visitUser(user: User): T + + fun visitAssistant(assistant: Assistant): T + + fun visitTool(tool: Tool): T + + fun visitFunction(function: Function): T + + fun visitFallback(fallback: Fallback): T + + /** + * Maps an unknown variant of [Message] to a value of type [T]. + * + * An instance of [Message] can contain an unknown variant if it was deserialized from + * data that doesn't match any known variant. For example, if the SDK is on an older + * version than the API, then the API may respond with new variants that the SDK is + * unaware of. + * + * @throws BraintrustInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw BraintrustInvalidDataException("Unknown Message: $json") + } + } + + internal class Deserializer : BaseDeserializer(Message::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Message { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Message(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() + } + } + } + + internal class Serializer : BaseSerializer(Message::class) { + + override fun serialize( + value: Message, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.system != null -> generator.writeObject(value.system) + value.user != null -> generator.writeObject(value.user) + value.assistant != null -> generator.writeObject(value.assistant) + value.tool != null -> generator.writeObject(value.tool) + value.function != null -> generator.writeObject(value.function) + value.fallback != null -> generator.writeObject(value.fallback) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Message") + } + } + } + + class System + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws 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 [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @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 [System]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [System]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(system: System) = apply { + role = system.role + content = system.content + name = system.name + additionalProperties = system.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [System]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): System = + System( + checkRequired("role", role), + content, + name, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SYSTEM = of("system") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + SYSTEM + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SYSTEM, + /** + * An enum member indicating that [Role] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SYSTEM -> Value.SYSTEM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + SYSTEM -> Known.SYSTEM + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is System && + role == other.role && + content == other.content && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "System{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" + } + + class User + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws 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 [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @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 [User]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [User]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(user: User) = apply { + role = user.role + content = user.content + name = user.name + additionalProperties = user.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofText(text)`. */ + fun content(text: String) = content(Content.ofText(text)) + + /** Alias for calling [content] with `Content.ofArray(array)`. */ + fun contentOfArray(array: List) = + content(Content.ofArray(array)) + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [User]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): User = + User( + checkRequired("role", role), + content, + name, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val USER = of("user") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + USER + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + USER, + /** + * An enum member indicating that [Role] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + USER -> Value.USER + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + USER -> Known.USER + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val text: String? = null, + private val array: List? = null, + private val _json: JsonValue? = null, + ) { + + fun text(): Optional = Optional.ofNullable(text) + + fun array(): Optional> = Optional.ofNullable(array) + + fun isText(): Boolean = text != null + + fun isArray(): Boolean = array != null + + fun asText(): String = text.getOrThrow("text") + + fun asArray(): List = array.getOrThrow("array") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitText(text: String) {} + + override fun visitArray(array: List) { + array.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 = + 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 + } + + return other is Content && text == other.text && array == other.array + } + + override fun hashCode(): Int = Objects.hash(text, array) + + override fun toString(): String = + when { + text != null -> "Content{text=$text}" + array != null -> "Content{array=$array}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofText(text: String) = Content(text = text) + + @JvmStatic + fun ofArray(array: List) = + Content(array = array.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value of type + * [T]. + */ + interface Visitor { + + fun visitText(text: String): T + + fun visitArray(array: List): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws BraintrustInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw BraintrustInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(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() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.text != null -> generator.writeObject(value.text) + value.array != null -> generator.writeObject(value.array) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + @JsonDeserialize(using = ChatCompletionContentPart.Deserializer::class) + @JsonSerialize(using = ChatCompletionContentPart.Serializer::class) + class ChatCompletionContentPart + private constructor( + private val text: ChatCompletionContentPartText? = null, + private val image: ChatCompletionContentPartImage? = null, + private val _json: JsonValue? = null, + ) { + + fun text(): Optional = Optional.ofNullable(text) + + fun image(): Optional = + Optional.ofNullable(image) + + fun isText(): Boolean = text != null + + fun isImage(): Boolean = image != null + + fun asText(): ChatCompletionContentPartText = text.getOrThrow("text") + + fun asImage(): ChatCompletionContentPartImage = image.getOrThrow("image") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + text != null -> visitor.visitText(text) + image != null -> visitor.visitImage(image) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionContentPart = apply { + if (validated) { + return@apply + } + + accept( + 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.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionContentPart && + text == other.text && + image == other.image + } + + override fun hashCode(): Int = Objects.hash(text, image) + + override fun toString(): String = + when { + text != null -> "ChatCompletionContentPart{text=$text}" + image != null -> "ChatCompletionContentPart{image=$image}" + _json != null -> "ChatCompletionContentPart{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ChatCompletionContentPart") + } + + companion object { + + @JvmStatic + fun ofText(text: ChatCompletionContentPartText) = + ChatCompletionContentPart(text = text) + + @JvmStatic + fun ofImage(image: ChatCompletionContentPartImage) = + ChatCompletionContentPart(image = image) + } + + /** + * An interface that defines how to map each variant of + * [ChatCompletionContentPart] to a value of type [T]. + */ + interface Visitor { + + fun visitText(text: ChatCompletionContentPartText): T + + fun visitImage(image: ChatCompletionContentPartImage): T + + /** + * Maps an unknown variant of [ChatCompletionContentPart] to a value of type + * [T]. + * + * An instance of [ChatCompletionContentPart] 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 ChatCompletionContentPart: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + ChatCompletionContentPart::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): ChatCompletionContentPart { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : + BaseSerializer( + ChatCompletionContentPart::class + ) { + + override fun serialize( + value: ChatCompletionContentPart, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.text != null -> generator.writeObject(value.text) + value.image != null -> generator.writeObject(value.image) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException("Invalid ChatCompletionContentPart") + } + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is User && + role == other.role && + content == other.content && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "User{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" + } + + class Assistant + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun functionCall(): Optional = functionCall.getOptional("function_call") + + /** + * @throws 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 toolCalls(): Optional> = + toolCalls.getOptional("tool_calls") + + /** + * Returns the raw JSON value of [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_call") + @ExcludeMissing + fun _functionCall(): JsonField = functionCall + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [toolCalls]. + * + * Unlike [toolCalls], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_calls") + @ExcludeMissing + fun _toolCalls(): JsonField> = toolCalls + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Assistant]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Assistant]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var functionCall: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var toolCalls: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(assistant: Assistant) = apply { + role = assistant.role + content = assistant.content + functionCall = assistant.functionCall + name = assistant.name + toolCalls = assistant.toolCalls.map { it.toMutableList() } + additionalProperties = assistant.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun functionCall(functionCall: FunctionCall?) = + functionCall(JsonField.ofNullable(functionCall)) + + /** Alias for calling [Builder.functionCall] with `functionCall.orElse(null)`. */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + this.functionCall = functionCall + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun toolCalls(toolCalls: List?) = + toolCalls(JsonField.ofNullable(toolCalls)) + + /** Alias for calling [Builder.toolCalls] with `toolCalls.orElse(null)`. */ + fun toolCalls(toolCalls: Optional>) = + toolCalls(toolCalls.getOrNull()) + + /** + * Sets [Builder.toolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCalls] with a well-typed + * `List` value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun toolCalls(toolCalls: JsonField>) = apply { + this.toolCalls = toolCalls.map { it.toMutableList() } + } + + /** + * Adds a single [ChatCompletionMessageToolCall] to [toolCalls]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addToolCall(toolCall: ChatCompletionMessageToolCall) = apply { + toolCalls = + (toolCalls ?: JsonField.of(mutableListOf())).also { + checkKnown("toolCalls", it).add(toolCall) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Assistant]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Assistant = + Assistant( + checkRequired("role", role), + content, + functionCall, + name, + (toolCalls ?: JsonMissing.of()).map { it.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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ASSISTANT = of("assistant") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + ASSISTANT + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ASSISTANT, + /** + * An enum member indicating that [Role] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ASSISTANT -> Value.ASSISTANT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + ASSISTANT -> Known.ASSISTANT + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class FunctionCall + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun arguments(): String = arguments.getRequired("arguments") + + /** + * @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") + + /** + * Returns the raw JSON value of [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("arguments") + @ExcludeMissing + fun _arguments(): JsonField = arguments + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FunctionCall]. + * + * The following fields are required: + * ```java + * .arguments() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionCall]. */ + class Builder internal constructor() { + + private var arguments: JsonField? = null + private var name: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionCall: FunctionCall) = apply { + arguments = functionCall.arguments + name = functionCall.name + additionalProperties = functionCall.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun arguments(arguments: JsonField) = apply { + this.arguments = arguments + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionCall]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .arguments() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionCall = + FunctionCall( + checkRequired("arguments", arguments), + checkRequired("name", name), + 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 + } + + return other is FunctionCall && + arguments == other.arguments && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(arguments, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionCall{arguments=$arguments, name=$name, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Assistant && + role == other.role && + content == other.content && + functionCall == other.functionCall && + name == other.name && + toolCalls == other.toolCalls && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, functionCall, name, toolCalls, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Assistant{role=$role, content=$content, functionCall=$functionCall, name=$name, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" + } + + class Tool + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun toolCallId(): Optional = toolCallId.getOptional("tool_call_id") + + /** + * Returns the raw JSON value of [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [toolCallId]. + * + * Unlike [toolCallId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_call_id") + @ExcludeMissing + fun _toolCallId(): JsonField = toolCallId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Tool]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Tool]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var toolCallId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(tool: Tool) = apply { + role = tool.role + content = tool.content + toolCallId = tool.toolCallId + additionalProperties = tool.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun toolCallId(toolCallId: String) = toolCallId(JsonField.of(toolCallId)) + + /** + * Sets [Builder.toolCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCallId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolCallId(toolCallId: JsonField) = apply { + this.toolCallId = toolCallId + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Tool]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Tool = + Tool( + checkRequired("role", role), + content, + toolCallId, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + TOOL + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TOOL, + /** + * An enum member indicating that [Role] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Tool && + role == other.role && + content == other.content && + toolCallId == other.toolCallId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, toolCallId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Tool{role=$role, content=$content, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" + } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 an unexpected + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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 role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * Returns the raw JSON value of [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 [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .name() + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + name = function.name + role = function.role + content = function.content + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("name", name), + checkRequired("role", role), + content, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FUNCTION, + /** + * An enum member indicating that [Role] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + name == other.name && + role == other.role && + content == other.content && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, role, content, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{name=$name, role=$role, content=$content, additionalProperties=$additionalProperties}" + } + + class Fallback + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 + * value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * Returns the raw JSON value of [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Fallback]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Fallback]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fallback: Fallback) = apply { + role = fallback.role + content = fallback.content + additionalProperties = fallback.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Fallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Fallback = + Fallback( + checkRequired("role", role), + content, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val MODEL = of("model") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + MODEL + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + MODEL, + /** + * An enum member indicating that [Role] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + MODEL -> Value.MODEL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + MODEL -> Known.MODEL + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Fallback && + role == other.role && + content == other.content && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(role, content, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Fallback{role=$role, content=$content, additionalProperties=$additionalProperties}" + } + } + + /** Any relevant metadata */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + /** The mode format of the returned value (defaults to 'auto') */ + class Mode @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val PARALLEL = of("parallel") + + @JvmStatic fun of(value: String) = Mode(JsonField.of(value)) + } + + /** An enum containing [Mode]'s known values. */ + enum class Known { + AUTO, + PARALLEL, + } + + /** + * An enum containing [Mode]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Mode] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + PARALLEL, + /** An enum member indicating that [Mode] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + PARALLEL -> Value.PARALLEL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + PARALLEL -> Known.PARALLEL + else -> throw BraintrustInvalidDataException("Unknown Mode: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Mode && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Options for tracing the function call */ + @JsonDeserialize(using = Parent.Deserializer::class) + @JsonSerialize(using = Parent.Serializer::class) + class Parent + private constructor( + private val spanParentStruct: SpanParentStruct? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + /** Span parent properties */ + fun spanParentStruct(): Optional = Optional.ofNullable(spanParentStruct) + + /** The parent's span identifier, created by calling `.export()` on a span */ + fun string(): Optional = Optional.ofNullable(string) + + fun isSpanParentStruct(): Boolean = spanParentStruct != null + + fun isString(): Boolean = string != null + + /** Span parent properties */ + fun asSpanParentStruct(): SpanParentStruct = spanParentStruct.getOrThrow("spanParentStruct") + + /** The parent's span identifier, created by calling `.export()` on a span */ + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Parent = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitSpanParentStruct(spanParentStruct: SpanParentStruct) { + spanParentStruct.validate() + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 + } + + return other is Parent && + spanParentStruct == other.spanParentStruct && + string == other.string + } + + override fun hashCode(): Int = Objects.hash(spanParentStruct, string) + + override fun toString(): String = + when { + spanParentStruct != null -> "Parent{spanParentStruct=$spanParentStruct}" + string != null -> "Parent{string=$string}" + _json != null -> "Parent{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Parent") + } + + companion object { + + /** Span parent properties */ + @JvmStatic + fun ofSpanParentStruct(spanParentStruct: SpanParentStruct) = + Parent(spanParentStruct = spanParentStruct) + + /** The parent's span identifier, created by calling `.export()` on a span */ + @JvmStatic fun ofString(string: String) = Parent(string = string) + } + + /** An interface that defines how to map each variant of [Parent] to a value of type [T]. */ + interface Visitor { + + /** Span parent properties */ + fun visitSpanParentStruct(spanParentStruct: SpanParentStruct): T + + /** The parent's span identifier, created by calling `.export()` on a span */ + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Parent] to a value of type [T]. + * + * An instance of [Parent] 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 Parent: $json") + } + } + + internal class Deserializer : BaseDeserializer(Parent::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Parent { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Parent::class) { + + override fun serialize( + value: Parent, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.spanParentStruct != null -> generator.writeObject(value.spanParentStruct) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Parent") + } + } + } + + /** Span parent properties */ + class SpanParentStruct + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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") + + /** + * @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 = objectType.getRequired("object_type") + + /** + * Include these properties in every span created under this parent + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun propagatedEvent(): Optional = + propagatedEvent.getOptional("propagated_event") + + /** + * Identifiers for the row to to log a subspan under + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun rowIds(): Optional = rowIds.getOptional("row_ids") + + /** + * 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 + + /** + * Returns the raw JSON value of [propagatedEvent]. + * + * Unlike [propagatedEvent], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("propagated_event") + @ExcludeMissing + fun _propagatedEvent(): JsonField = propagatedEvent + + /** + * Returns the raw JSON value of [rowIds]. + * + * Unlike [rowIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SpanParentStruct]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanParentStruct]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var propagatedEvent: JsonField = JsonMissing.of() + private var rowIds: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(spanParentStruct: SpanParentStruct) = apply { + objectId = spanParentStruct.objectId + objectType = spanParentStruct.objectType + propagatedEvent = spanParentStruct.propagatedEvent + rowIds = spanParentStruct.rowIds + additionalProperties = spanParentStruct.additionalProperties.toMutableMap() + } + + /** The id of the container object you are logging 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 } + + fun objectType(objectType: ObjectType) = objectType(JsonField.of(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 { + this.objectType = objectType + } + + /** Include these properties in every span created under this parent */ + fun propagatedEvent(propagatedEvent: PropagatedEvent?) = + propagatedEvent(JsonField.ofNullable(propagatedEvent)) + + /** + * Alias for calling [Builder.propagatedEvent] with `propagatedEvent.orElse(null)`. + */ + fun propagatedEvent(propagatedEvent: Optional) = + propagatedEvent(propagatedEvent.getOrNull()) + + /** + * Sets [Builder.propagatedEvent] to an arbitrary JSON value. + * + * You should usually call [Builder.propagatedEvent] with a well-typed + * [PropagatedEvent] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun propagatedEvent(propagatedEvent: JsonField) = apply { + this.propagatedEvent = propagatedEvent + } + + /** Identifiers for the row to to log a subspan under */ + fun rowIds(rowIds: RowIds?) = rowIds(JsonField.ofNullable(rowIds)) + + /** Alias for calling [Builder.rowIds] with `rowIds.orElse(null)`. */ + fun rowIds(rowIds: Optional) = rowIds(rowIds.getOrNull()) + + /** + * Sets [Builder.rowIds] to an arbitrary JSON value. + * + * You should usually call [Builder.rowIds] with a well-typed [RowIds] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun rowIds(rowIds: JsonField) = apply { this.rowIds = rowIds } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SpanParentStruct]. + * + * 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(): SpanParentStruct = + SpanParentStruct( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + propagatedEvent, + rowIds, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROJECT_LOGS = of("project_logs") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val PLAYGROUND_LOGS = of("playground_logs") + + @JvmStatic fun of(value: String) = ObjectType(JsonField.of(value)) + } + + /** An enum containing [ObjectType]'s known values. */ + enum class Known { + PROJECT_LOGS, + EXPERIMENT, + PLAYGROUND_LOGS, + } + + /** + * An enum containing [ObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROJECT_LOGS, + EXPERIMENT, + PLAYGROUND_LOGS, + /** + * An enum member indicating that [ObjectType] was instantiated with an unknown + * value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROJECT_LOGS -> Value.PROJECT_LOGS + EXPERIMENT -> Value.EXPERIMENT + PLAYGROUND_LOGS -> Value.PLAYGROUND_LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + PROJECT_LOGS -> Known.PROJECT_LOGS + EXPERIMENT -> Known.EXPERIMENT + PLAYGROUND_LOGS -> Known.PLAYGROUND_LOGS + else -> throw BraintrustInvalidDataException("Unknown ObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** Include these properties in every span created under this parent */ + class PropagatedEvent + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PropagatedEvent]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PropagatedEvent]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(propagatedEvent: PropagatedEvent) = apply { + additionalProperties = propagatedEvent.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 [PropagatedEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PropagatedEvent = + 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 + } + + return other is PropagatedEvent && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PropagatedEvent{additionalProperties=$additionalProperties}" + } + + /** Identifiers for the row to to log a subspan under */ + class RowIds + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The root_span_id of the row + * + * @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 rootSpanId(): String = rootSpanId.getRequired("root_span_id") + + /** + * The span_id of the row + * + * @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 spanId(): String = spanId.getRequired("span_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("root_span_id") + @ExcludeMissing + fun _rootSpanId(): JsonField = rootSpanId + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RowIds]. + * + * The following fields are required: + * ```java + * .id() + * .rootSpanId() + * .spanId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RowIds]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var rootSpanId: JsonField? = null + private var spanId: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(rowIds: RowIds) = apply { + id = rowIds.id + rootSpanId = rowIds.rootSpanId + spanId = rowIds.spanId + additionalProperties = rowIds.additionalProperties.toMutableMap() + } + + /** The id of the row */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** The root_span_id of the row */ + fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { + this.rootSpanId = rootSpanId + } + + /** The span_id of the row */ + fun spanId(spanId: String) = spanId(JsonField.of(spanId)) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or + * not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RowIds]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .rootSpanId() + * .spanId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RowIds = + RowIds( + checkRequired("id", id), + checkRequired("rootSpanId", rootSpanId), + checkRequired("spanId", spanId), + 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 + } + + return other is RowIds && + id == other.id && + rootSpanId == other.rootSpanId && + spanId == other.spanId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, rootSpanId, spanId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RowIds{id=$id, rootSpanId=$rootSpanId, spanId=$spanId, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanParentStruct && + objectId == other.objectId && + objectType == other.objectType && + propagatedEvent == other.propagatedEvent && + rowIds == other.rowIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(objectId, objectType, propagatedEvent, rowIds, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SpanParentStruct{objectId=$objectId, objectType=$objectType, propagatedEvent=$propagatedEvent, rowIds=$rowIds, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionInvokeParams && + functionId == other.functionId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(functionId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FunctionInvokeParams{functionId=$functionId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..b932f1ff --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionInvokeResponse.kt @@ -0,0 +1,114 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.ExcludeMissing +import com.braintrustdata.api.core.JsonValue +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 + +class FunctionInvokeResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor(private val additionalProperties: MutableMap) { + + @JsonCreator private constructor() : this(mutableMapOf()) + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FunctionInvokeResponse]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionInvokeResponse]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionInvokeResponse: FunctionInvokeResponse) = apply { + additionalProperties = functionInvokeResponse.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 [FunctionInvokeResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionInvokeResponse = + 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 + } + + return other is FunctionInvokeResponse && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "FunctionInvokeResponse{additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..c7b3e196 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPage.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.FunctionService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see FunctionService.list */ +class FunctionListPage +private constructor( + private val service: FunctionService, + private val params: FunctionListParams, + private val response: FunctionListPageResponse, +) : Page { + + /** + * Delegates to [FunctionListPageResponse], but gracefully handles missing data. + * + * @see FunctionListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): FunctionListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): FunctionListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): FunctionListParams = params + + /** The response that this page was parsed from. */ + fun response(): FunctionListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FunctionListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionListPage]. */ + class Builder internal constructor() { + + private var service: FunctionService? = null + private var params: FunctionListParams? = null + private var response: FunctionListPageResponse? = null + + @JvmSynthetic + internal fun from(functionListPage: FunctionListPage) = apply { + service = functionListPage.service + params = functionListPage.params + response = functionListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..5cd52e24 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageAsync.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.FunctionServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see FunctionServiceAsync.list */ +class FunctionListPageAsync +private constructor( + private val service: FunctionServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: FunctionListParams, + private val response: FunctionListPageResponse, +) : PageAsync { + + /** + * Delegates to [FunctionListPageResponse], but gracefully handles missing data. + * + * @see FunctionListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): FunctionListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): FunctionListParams = params + + /** The response that this page was parsed from. */ + fun response(): FunctionListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FunctionListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionListPageAsync]. */ + class Builder internal constructor() { + + private var service: FunctionServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: FunctionListParams? = null + private var response: FunctionListPageResponse? = null + + @JvmSynthetic + internal fun from(functionListPageAsync: FunctionListPageAsync) = apply { + service = functionListPageAsync.service + streamHandlerExecutor = functionListPageAsync.streamHandlerExecutor + params = functionListPageAsync.params + response = functionListPageAsync.response + } + + fun service(service: FunctionServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionListPageAsync = + FunctionListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "FunctionListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..423c3fba --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is FunctionListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..33d8f263 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionListParams.kt @@ -0,0 +1,475 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all functions. The functions are sorted by creation date, with the most recently-created + * functions coming first + */ +class FunctionListParams +private constructor( + private val endingBefore: String?, + private val functionName: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val projectId: String?, + private val projectName: String?, + private val slug: String?, + private val startingAfter: String?, + private val version: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** Name of the function to search for */ + fun functionName(): Optional = Optional.ofNullable(functionName) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** Name of the project to search for */ + fun projectName(): Optional = Optional.ofNullable(projectName) + + /** Retrieve prompt with a specific slug */ + fun slug(): Optional = Optional.ofNullable(slug) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** + * Retrieve prompt at a specific version. + * + * The version id can either be a transaction id (e.g. '1000192656880881099') or a version + * identifier (e.g. '81cd05ee665fdfb3'). + */ + fun version(): Optional = Optional.ofNullable(version) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FunctionListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FunctionListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var functionName: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var projectId: String? = null + private var projectName: String? = null + private var slug: String? = null + private var startingAfter: String? = null + private var version: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(functionListParams: FunctionListParams) = apply { + endingBefore = functionListParams.endingBefore + functionName = functionListParams.functionName + ids = functionListParams.ids + limit = functionListParams.limit + orgName = functionListParams.orgName + projectId = functionListParams.projectId + projectName = functionListParams.projectName + slug = functionListParams.slug + startingAfter = functionListParams.startingAfter + version = functionListParams.version + additionalHeaders = functionListParams.additionalHeaders.toBuilder() + additionalQueryParams = functionListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** Name of the function to search for */ + fun functionName(functionName: String?) = apply { this.functionName = functionName } + + /** Alias for calling [Builder.functionName] with `functionName.orElse(null)`. */ + fun functionName(functionName: Optional) = functionName(functionName.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) + + /** Name of the project to search for */ + fun projectName(projectName: String?) = apply { this.projectName = projectName } + + /** Alias for calling [Builder.projectName] with `projectName.orElse(null)`. */ + fun projectName(projectName: Optional) = projectName(projectName.getOrNull()) + + /** Retrieve prompt with a specific slug */ + fun slug(slug: String?) = apply { this.slug = slug } + + /** Alias for calling [Builder.slug] with `slug.orElse(null)`. */ + fun slug(slug: Optional) = slug(slug.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + /** + * Retrieve prompt at a specific version. + * + * The version id can either be a transaction id (e.g. '1000192656880881099') or a version + * identifier (e.g. '81cd05ee665fdfb3'). + */ + fun version(version: String?) = apply { this.version = version } + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FunctionListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionListParams = + FunctionListParams( + endingBefore, + functionName, + ids, + limit, + orgName, + projectId, + projectName, + slug, + startingAfter, + version, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionListParams && + endingBefore == other.endingBefore && + functionName == other.functionName && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + projectId == other.projectId && + projectName == other.projectName && + slug == other.slug && + startingAfter == other.startingAfter && + version == other.version && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + functionName, + ids, + limit, + orgName, + projectId, + projectName, + slug, + startingAfter, + version, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "FunctionListParams{endingBefore=$endingBefore, functionName=$functionName, ids=$ids, limit=$limit, orgName=$orgName, projectId=$projectId, projectName=$projectName, slug=$slug, startingAfter=$startingAfter, version=$version, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..995a22d6 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionReplaceParams.kt @@ -0,0 +1,4216 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Create or replace function. If there is an existing function in the project with the same slug as + * the one specified in the request, will replace the existing function with the provided fields + */ +class FunctionReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * @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 = body.functionData() + + /** + * Name of 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 name(): String = body.name() + + /** + * 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 = body.projectId() + + /** + * 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 = body.slug() + + /** + * 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 = body.description() + + /** + * 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 = body.functionSchema() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionType(): Optional = body.functionType() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun origin(): Optional = body.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 = body.promptData() + + /** + * 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> = body.tags() + + /** + * Returns the raw JSON value of [functionData]. + * + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionData(): JsonField = body._functionData() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [slug]. + * + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _slug(): JsonField = body._slug() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [functionSchema]. + * + * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionSchema(): JsonField = body._functionSchema() + + /** + * Returns the raw JSON value of [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionType(): JsonField = body._functionType() + + /** + * Returns the raw JSON value of [origin]. + * + * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _origin(): JsonField = body._origin() + + /** + * Returns the raw JSON value of [promptData]. + * + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _promptData(): JsonField = body._promptData() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [FunctionReplaceParams]. + * + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionReplaceParams]. */ + 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(functionReplaceParams: FunctionReplaceParams) = apply { + body = functionReplaceParams.body.toBuilder() + additionalHeaders = functionReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = functionReplaceParams.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: + * - [functionData] + * - [name] + * - [projectId] + * - [slug] + * - [description] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun functionData(functionData: FunctionData) = apply { body.functionData(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 { + 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) } + + /** + * 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 prompt 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) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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 { + 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()) + + /** + * 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 { + 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()) + + /** + * 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 { 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()) + + /** + * 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 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 [FunctionReplaceParams]. + * + * 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(): FunctionReplaceParams = + FunctionReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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(), + ) + + /** + * @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 + * + * @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 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * 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 [functionData]. + * + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_data") + @ExcludeMissing + fun _functionData(): JsonField = functionData + + /** + * 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 [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 [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 [functionSchema]. + * + * Unlike [functionSchema], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_schema") + @ExcludeMissing + fun _functionSchema(): JsonField = functionSchema + + /** + * 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 + + /** + * 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 + + /** + * 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 [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]. + * + * The following fields are required: + * ```java + * .functionData() + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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 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 + } + + fun origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * 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 } + + /** 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 + } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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 + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + 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 a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @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 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + functionData, + name, + projectId, + slug, + description, + functionSchema, + functionType, + origin, + promptData, + tags, + additionalProperties, + ) + } + + 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) + @JsonSerialize(using = FunctionData.Serializer::class) + class FunctionData + private constructor( + private val prompt: Prompt? = null, + private val code: Code? = null, + private val global: Global? = null, + private val _json: JsonValue? = null, + ) { + + fun prompt(): Optional = Optional.ofNullable(prompt) + + fun code(): Optional = Optional.ofNullable(code) + + fun global(): Optional = Optional.ofNullable(global) + + fun isPrompt(): Boolean = prompt != null + + fun isCode(): Boolean = code != null + + fun isGlobal(): Boolean = global != null + + fun asPrompt(): Prompt = prompt.getOrThrow("prompt") + + fun asCode(): Code = code.getOrThrow("code") + + fun asGlobal(): Global = global.getOrThrow("global") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): FunctionData = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitPrompt(prompt: Prompt) { + prompt.validate() + } + + override fun visitCode(code: Code) { + code.validate() + } + + override fun visitGlobal(global: Global) { + global.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 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 + } + + return other is FunctionData && + prompt == other.prompt && + code == other.code && + global == other.global + } + + override fun hashCode(): Int = Objects.hash(prompt, code, global) + + override fun toString(): String = + when { + prompt != null -> "FunctionData{prompt=$prompt}" + code != null -> "FunctionData{code=$code}" + global != null -> "FunctionData{global=$global}" + _json != null -> "FunctionData{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FunctionData") + } + + companion object { + + @JvmStatic fun ofPrompt(prompt: Prompt) = FunctionData(prompt = prompt) + + @JvmStatic fun ofCode(code: Code) = FunctionData(code = code) + + @JvmStatic fun ofGlobal(global: Global) = FunctionData(global = global) + } + + /** + * An interface that defines how to map each variant of [FunctionData] to a value of type + * [T]. + */ + interface Visitor { + + fun visitPrompt(prompt: Prompt): T + + fun visitCode(code: Code): T + + fun visitGlobal(global: Global): T + + /** + * Maps an unknown variant of [FunctionData] to a value of type [T]. + * + * An instance of [FunctionData] 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 FunctionData: $json") + } + } + + internal class Deserializer : BaseDeserializer(FunctionData::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(FunctionData::class) { + + override fun serialize( + value: FunctionData, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.prompt != null -> generator.writeObject(value.prompt) + value.code != null -> generator.writeObject(value.code) + value.global != null -> generator.writeObject(value.global) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FunctionData") + } + } + } + + class Prompt + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Prompt]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Prompt]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(prompt: Prompt) = apply { + type = prompt.type + additionalProperties = prompt.additionalProperties.toMutableMap() + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Prompt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Prompt = + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROMPT = of("prompt") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + PROMPT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROMPT, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROMPT -> Value.PROMPT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + PROMPT -> Known.PROMPT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Prompt && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Prompt{type=$type, additionalProperties=$additionalProperties}" + } + + class Code + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @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") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Code]. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Code]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(code: Code) = apply { + data = code.data + type = code.type + additionalProperties = code.additionalProperties.toMutableMap() + } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * 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 [data] with `Data.ofBundle(bundle)`. */ + fun data(bundle: Data.Bundle) = data(Data.ofBundle(bundle)) + + /** Alias for calling [data] with `Data.ofInline(inline)`. */ + fun data(inline: Data.Inline) = data(Data.ofInline(inline)) + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Code]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Code = + Code( + checkRequired("data", data), + checkRequired("type", type), + 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 + private constructor( + private val bundle: Bundle? = null, + private val inline: Inline? = null, + private val _json: JsonValue? = null, + ) { + + fun bundle(): Optional = Optional.ofNullable(bundle) + + fun inline(): Optional = Optional.ofNullable(inline) + + fun isBundle(): Boolean = bundle != null + + fun isInline(): Boolean = inline != null + + fun asBundle(): Bundle = bundle.getOrThrow("bundle") + + fun asInline(): Inline = inline.getOrThrow("inline") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitBundle(bundle: Bundle) { + bundle.validate() + } + + override fun visitInline(inline: Inline) { + inline.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 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 + } + + return other is Data && bundle == other.bundle && inline == other.inline + } + + override fun hashCode(): Int = Objects.hash(bundle, inline) + + override fun toString(): String = + when { + bundle != null -> "Data{bundle=$bundle}" + inline != null -> "Data{inline=$inline}" + _json != null -> "Data{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Data") + } + + companion object { + + @JvmStatic fun ofBundle(bundle: Bundle) = Data(bundle = bundle) + + @JvmStatic fun ofInline(inline: Inline) = Data(inline = inline) + } + + /** + * An interface that defines how to map each variant of [Data] to a value of type + * [T]. + */ + interface Visitor { + + fun visitBundle(bundle: Bundle): T + + fun visitInline(inline: Inline): T + + /** + * Maps an unknown variant of [Data] to a value of type [T]. + * + * An instance of [Data] 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 Data: $json") + } + } + + internal class Deserializer : BaseDeserializer(Data::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Data { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Data::class) { + + override fun serialize( + value: Data, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.bundle != null -> generator.writeObject(value.bundle) + value.inline != null -> generator.writeObject(value.inline) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Data") + } + } + } + + class Bundle + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun bundleId(): String = bundleId.getRequired("bundle_id") + + /** + * @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 location(): CodeBundle.Location = location.getRequired("location") + + /** + * @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 runtimeContext(): CodeBundle.RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * A preview of the code + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun preview(): Optional = preview.getOptional("preview") + + /** + * @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") + + /** + * Returns the raw JSON value of [bundleId]. + * + * Unlike [bundleId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bundle_id") + @ExcludeMissing + fun _bundleId(): JsonField = bundleId + + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("location") + @ExcludeMissing + fun _location(): JsonField = location + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [preview]. + * + * Unlike [preview], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("preview") + @ExcludeMissing + fun _preview(): JsonField = preview + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Bundle]. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Bundle]. */ + class Builder internal constructor() { + + private var bundleId: JsonField? = null + private var location: JsonField? = null + private var runtimeContext: JsonField? = null + private var preview: JsonField = JsonMissing.of() + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(bundle: Bundle) = apply { + bundleId = bundle.bundleId + location = bundle.location + runtimeContext = bundle.runtimeContext + preview = bundle.preview + type = bundle.type + additionalProperties = bundle.additionalProperties.toMutableMap() + } + + fun bundleId(bundleId: String) = bundleId(JsonField.of(bundleId)) + + /** + * Sets [Builder.bundleId] to an arbitrary JSON value. + * + * You should usually call [Builder.bundleId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun bundleId(bundleId: JsonField) = apply { + this.bundleId = bundleId + } + + fun location(location: CodeBundle.Location) = + location(JsonField.of(location)) + + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed + * [CodeBundle.Location] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun location(location: JsonField) = apply { + this.location = location + } + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofExperiment(experiment)`. + */ + fun location(experiment: CodeBundle.Location.Experiment) = + location(CodeBundle.Location.ofExperiment(experiment)) + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofFunction(function)`. + */ + fun location(function: CodeBundle.Location.Function) = + location(CodeBundle.Location.ofFunction(function)) + + fun runtimeContext(runtimeContext: CodeBundle.RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [CodeBundle.RuntimeContext] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = + apply { + this.runtimeContext = runtimeContext + } + + /** A preview of the code */ + fun preview(preview: String?) = preview(JsonField.ofNullable(preview)) + + /** Alias for calling [Builder.preview] with `preview.orElse(null)`. */ + fun preview(preview: Optional) = preview(preview.getOrNull()) + + /** + * Sets [Builder.preview] to an arbitrary JSON value. + * + * You should usually call [Builder.preview] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun preview(preview: JsonField) = apply { this.preview = preview } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Bundle]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Bundle = + Bundle( + checkRequired("bundleId", bundleId), + checkRequired("location", location), + checkRequired("runtimeContext", runtimeContext), + preview, + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val BUNDLE = of("bundle") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + BUNDLE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + BUNDLE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + BUNDLE -> Value.BUNDLE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + BUNDLE -> Known.BUNDLE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Bundle && + bundleId == other.bundleId && + location == other.location && + runtimeContext == other.runtimeContext && + preview == other.preview && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + bundleId, + location, + runtimeContext, + preview, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" + } + + class Inline + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun code(): String = code.getRequired("code") + + /** + * @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 runtimeContext(): RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * @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") + + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Inline]. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Inline]. */ + class Builder internal constructor() { + + private var code: JsonField? = null + private var runtimeContext: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(inline: Inline) = apply { + code = inline.code + runtimeContext = inline.runtimeContext + type = inline.type + additionalProperties = inline.additionalProperties.toMutableMap() + } + + fun code(code: String) = code(JsonField.of(code)) + + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun code(code: JsonField) = apply { this.code = code } + + fun runtimeContext(runtimeContext: RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [RuntimeContext] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = apply { + this.runtimeContext = runtimeContext + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Inline]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Inline = + Inline( + checkRequired("code", code), + checkRequired("runtimeContext", runtimeContext), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun runtime(): Runtime = runtime.getRequired("runtime") + + /** + * @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 version(): String = version.getRequired("version") + + /** + * Returns the raw JSON value of [runtime]. + * + * Unlike [runtime], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime") + @ExcludeMissing + fun _runtime(): JsonField = runtime + + /** + * 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 + + @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 + * [RuntimeContext]. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuntimeContext]. */ + class Builder internal constructor() { + + private var runtime: JsonField? = null + private var version: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(runtimeContext: RuntimeContext) = apply { + runtime = runtimeContext.runtime + version = runtimeContext.version + additionalProperties = + runtimeContext.additionalProperties.toMutableMap() + } + + fun runtime(runtime: Runtime) = runtime(JsonField.of(runtime)) + + /** + * Sets [Builder.runtime] to an arbitrary JSON value. + * + * You should usually call [Builder.runtime] with a well-typed [Runtime] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun runtime(runtime: JsonField) = apply { + this.runtime = runtime + } + + fun version(version: String) = version(JsonField.of(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 { + this.version = version + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuntimeContext]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RuntimeContext = + RuntimeContext( + checkRequired("runtime", runtime), + checkRequired("version", version), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from + * data that doesn't match any known member, and you want to know that + * value. For example, if the SDK is on an older version than the API, + * then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val NODE = of("node") + + @JvmField val PYTHON = of("python") + + @JvmStatic fun of(value: String) = Runtime(JsonField.of(value)) + } + + /** An enum containing [Runtime]'s known values. */ + enum class Known { + NODE, + PYTHON, + } + + /** + * An enum containing [Runtime]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Runtime] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + NODE, + PYTHON, + /** + * An enum member indicating that [Runtime] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, + * or [Value._UNKNOWN] if the class was instantiated with an unknown + * value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + NODE -> Value.NODE + PYTHON -> Value.PYTHON + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is + * always known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value + * is a not a known member. + */ + fun known(): Known = + when (this) { + NODE -> Known.NODE + PYTHON -> Known.PYTHON + else -> + throw BraintrustInvalidDataException( + "Unknown Runtime: $value" + ) + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is + * primarily for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Runtime && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RuntimeContext && + runtime == other.runtime && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(runtime, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuntimeContext{runtime=$runtime, version=$version, additionalProperties=$additionalProperties}" + } + + class Type + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val INLINE = of("inline") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + INLINE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + INLINE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + INLINE -> Value.INLINE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + INLINE -> Known.INLINE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Inline && + code == other.code && + runtimeContext == other.runtimeContext && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(code, runtimeContext, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Inline{code=$code, runtimeContext=$runtimeContext, type=$type, additionalProperties=$additionalProperties}" + } + } + + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CODE = of("code") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + CODE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + CODE, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + CODE -> Value.CODE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + CODE -> Known.CODE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Code && + data == other.data && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(data, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" + } + + class Global + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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") + + /** + * 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 [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Global]. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Global]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(global: Global) = apply { + name = global.name + type = global.type + additionalProperties = global.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Global]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Global = + Global( + checkRequired("name", name), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GLOBAL = of("global") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + GLOBAL + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GLOBAL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GLOBAL -> Value.GLOBAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GLOBAL -> Known.GLOBAL + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Global && + name == other.name && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Global{name=$name, type=$type, additionalProperties=$additionalProperties}" + } + } + + /** JSON schema for the function's parameters and return type */ + class FunctionSchema + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [FunctionSchema]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionSchema]. */ + class Builder internal constructor() { + + private var parameters: JsonValue = JsonMissing.of() + private var returns: JsonValue = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(functionSchema: FunctionSchema) = apply { + parameters = functionSchema.parameters + returns = functionSchema.returns + additionalProperties = functionSchema.additionalProperties.toMutableMap() + } + + fun parameters(parameters: JsonValue) = apply { this.parameters = parameters } + + fun returns(returns: JsonValue) = apply { this.returns = returns } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionSchema = + 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 + } + + return other is FunctionSchema && + parameters == other.parameters && + returns == other.returns && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(parameters, returns, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionSchema{parameters=$parameters, returns=$returns, additionalProperties=$additionalProperties}" + } + + class FunctionType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM = of("llm") + + @JvmField val SCORER = of("scorer") + + @JvmField val TASK = of("task") + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = FunctionType(JsonField.of(value)) + } + + /** An enum containing [FunctionType]'s known values. */ + enum class Known { + LLM, + SCORER, + TASK, + TOOL, + } + + /** + * An enum containing [FunctionType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [FunctionType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM, + SCORER, + TASK, + TOOL, + /** + * An enum member indicating that [FunctionType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM -> Value.LLM + SCORER -> Value.SCORER + TASK -> Value.TASK + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LLM -> Known.LLM + SCORER -> Known.SCORER + TASK -> Known.TASK + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown FunctionType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is FunctionType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Origin + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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") + + /** + * The function exists for internal purposes and should not be displayed in the list of + * functions. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun internal_(): Optional = internal_.getOptional("internal") + + /** + * 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 + + /** + * Returns the raw JSON value of [internal_]. + * + * Unlike [internal_], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("internal") @ExcludeMissing fun _internal_(): JsonField = internal_ + + @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 [Origin]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Origin]. */ + class Builder internal constructor() { + + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var internal_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(origin: Origin) = apply { + objectId = origin.objectId + objectType = origin.objectType + internal_ = origin.internal_ + additionalProperties = origin.additionalProperties.toMutableMap() + } + + /** Id of the object the function is originating from */ + 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 + } + + /** + * The function exists for internal purposes and should not be displayed in the list of + * functions. + */ + fun internal_(internal_: Boolean?) = internal_(JsonField.ofNullable(internal_)) + + /** + * Alias for [Builder.internal_]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun internal_(internal_: Boolean) = internal_(internal_ as Boolean?) + + /** Alias for calling [Builder.internal_] with `internal_.orElse(null)`. */ + fun internal_(internal_: Optional) = internal_(internal_.getOrNull()) + + /** + * Sets [Builder.internal_] to an arbitrary JSON value. + * + * You should usually call [Builder.internal_] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun internal_(internal_: JsonField) = apply { this.internal_ = internal_ } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Origin]. + * + * 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(): Origin = + Origin( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + internal_, + 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 + } + + return other is Origin && + objectId == other.objectId && + objectType == other.objectType && + internal_ == other.internal_ && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(objectId, objectType, internal_, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Origin{objectId=$objectId, objectType=$objectType, internal_=$internal_, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FunctionReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..e38243ac --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionRetrieveParams.kt @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a function object by its id */ +class FunctionRetrieveParams +private constructor( + private val functionId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Function id */ + fun functionId(): Optional = Optional.ofNullable(functionId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FunctionRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FunctionRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionRetrieveParams]. */ + class Builder internal constructor() { + + private var functionId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(functionRetrieveParams: FunctionRetrieveParams) = apply { + functionId = functionRetrieveParams.functionId + additionalHeaders = functionRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = functionRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Function id */ + fun functionId(functionId: String?) = apply { this.functionId = functionId } + + /** Alias for calling [Builder.functionId] with `functionId.orElse(null)`. */ + fun functionId(functionId: Optional) = functionId(functionId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [FunctionRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): FunctionRetrieveParams = + FunctionRetrieveParams( + functionId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is FunctionRetrieveParams && + functionId == other.functionId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(functionId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FunctionRetrieveParams{functionId=$functionId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..aec18c7b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/FunctionUpdateParams.kt @@ -0,0 +1,3317 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Partially update a function object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ +class FunctionUpdateParams +private constructor( + private val functionId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Function id */ + fun functionId(): Optional = Optional.ofNullable(functionId) + + /** + * 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 = body.description() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionData(): Optional = body.functionData() + + /** + * 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 = body.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 = body.promptData() + + /** + * 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> = body.tags() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [functionData]. + * + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionData(): JsonField = body._functionData() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [promptData]. + * + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _promptData(): JsonField = body._promptData() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): FunctionUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [FunctionUpdateParams]. */ + @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 } + + /** Alias for calling [Builder.functionId] with `functionId.orElse(null)`. */ + fun functionId(functionId: Optional) = functionId(functionId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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 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. + */ + fun build(): FunctionUpdateParams = + FunctionUpdateParams( + 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = 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 = functionData.getOptional("function_data") + + /** + * 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") + + /** + * 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 [functionData]. + * + * Unlike [functionData], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_data") + @ExcludeMissing + fun _functionData(): JsonField = functionData + + /** + * 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 [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 functionData: JsonField = JsonMissing.of() + private var name: 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 { + description = body.description + functionData = body.functionData + name = body.name + promptData = body.promptData + 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 + } + + fun functionData(functionData: FunctionData?) = + functionData(JsonField.ofNullable(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 { + 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.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. + * + * 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 + } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + description() + functionData().ifPresent { it.validate() } + name() + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + description == other.description && + functionData == other.functionData && + name == other.name && + promptData == other.promptData && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(description, functionData, name, promptData, tags, additionalProperties) + } + + 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) + @JsonSerialize(using = FunctionData.Serializer::class) + class FunctionData + private constructor( + private val prompt: Prompt? = null, + private val code: Code? = null, + private val global: Global? = null, + private val _json: JsonValue? = null, + ) { + + fun prompt(): Optional = Optional.ofNullable(prompt) + + fun code(): Optional = Optional.ofNullable(code) + + fun global(): Optional = Optional.ofNullable(global) + + fun isPrompt(): Boolean = prompt != null + + fun isCode(): Boolean = code != null + + fun isGlobal(): Boolean = global != null + + fun asPrompt(): Prompt = prompt.getOrThrow("prompt") + + fun asCode(): Code = code.getOrThrow("code") + + fun asGlobal(): Global = global.getOrThrow("global") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): FunctionData = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitPrompt(prompt: Prompt) { + prompt.validate() + } + + override fun visitCode(code: Code) { + code.validate() + } + + override fun visitGlobal(global: Global) { + global.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 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 + } + + return other is FunctionData && + prompt == other.prompt && + code == other.code && + global == other.global + } + + override fun hashCode(): Int = Objects.hash(prompt, code, global) + + override fun toString(): String = + when { + prompt != null -> "FunctionData{prompt=$prompt}" + code != null -> "FunctionData{code=$code}" + global != null -> "FunctionData{global=$global}" + _json != null -> "FunctionData{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FunctionData") + } + + companion object { + + @JvmStatic fun ofPrompt(prompt: Prompt) = FunctionData(prompt = prompt) + + @JvmStatic fun ofCode(code: Code) = FunctionData(code = code) + + @JvmStatic fun ofGlobal(global: Global) = FunctionData(global = global) + } + + /** + * An interface that defines how to map each variant of [FunctionData] to a value of type + * [T]. + */ + interface Visitor { + + fun visitPrompt(prompt: Prompt): T + + fun visitCode(code: Code): T + + fun visitGlobal(global: Global): T + + /** + * Maps an unknown variant of [FunctionData] to a value of type [T]. + * + * An instance of [FunctionData] 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 FunctionData: $json") + } + } + + internal class Deserializer : BaseDeserializer(FunctionData::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FunctionData { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(FunctionData::class) { + + override fun serialize( + value: FunctionData, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.prompt != null -> generator.writeObject(value.prompt) + value.code != null -> generator.writeObject(value.code) + value.global != null -> generator.writeObject(value.global) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FunctionData") + } + } + } + + class Prompt + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Prompt]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Prompt]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(prompt: Prompt) = apply { + type = prompt.type + additionalProperties = prompt.additionalProperties.toMutableMap() + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Prompt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Prompt = + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROMPT = of("prompt") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + PROMPT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROMPT, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROMPT -> Value.PROMPT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + PROMPT -> Known.PROMPT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Prompt && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Prompt{type=$type, additionalProperties=$additionalProperties}" + } + + class Code + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun data(): Data = data.getRequired("data") + + /** + * @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") + + /** + * Returns the raw JSON value of [data]. + * + * Unlike [data], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data") @ExcludeMissing fun _data(): JsonField = data + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Code]. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Code]. */ + class Builder internal constructor() { + + private var data: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(code: Code) = apply { + data = code.data + type = code.type + additionalProperties = code.additionalProperties.toMutableMap() + } + + fun data(data: Data) = data(JsonField.of(data)) + + /** + * 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 [data] with `Data.ofBundle(bundle)`. */ + fun data(bundle: Data.Bundle) = data(Data.ofBundle(bundle)) + + /** Alias for calling [data] with `Data.ofInline(inline)`. */ + fun data(inline: Data.Inline) = data(Data.ofInline(inline)) + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Code]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .data() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Code = + Code( + checkRequired("data", data), + checkRequired("type", type), + 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 + private constructor( + private val bundle: Bundle? = null, + private val inline: Inline? = null, + private val _json: JsonValue? = null, + ) { + + fun bundle(): Optional = Optional.ofNullable(bundle) + + fun inline(): Optional = Optional.ofNullable(inline) + + fun isBundle(): Boolean = bundle != null + + fun isInline(): Boolean = inline != null + + fun asBundle(): Bundle = bundle.getOrThrow("bundle") + + fun asInline(): Inline = inline.getOrThrow("inline") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Data = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitBundle(bundle: Bundle) { + bundle.validate() + } + + override fun visitInline(inline: Inline) { + inline.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 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 + } + + return other is Data && bundle == other.bundle && inline == other.inline + } + + override fun hashCode(): Int = Objects.hash(bundle, inline) + + override fun toString(): String = + when { + bundle != null -> "Data{bundle=$bundle}" + inline != null -> "Data{inline=$inline}" + _json != null -> "Data{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Data") + } + + companion object { + + @JvmStatic fun ofBundle(bundle: Bundle) = Data(bundle = bundle) + + @JvmStatic fun ofInline(inline: Inline) = Data(inline = inline) + } + + /** + * An interface that defines how to map each variant of [Data] to a value of type + * [T]. + */ + interface Visitor { + + fun visitBundle(bundle: Bundle): T + + fun visitInline(inline: Inline): T + + /** + * Maps an unknown variant of [Data] to a value of type [T]. + * + * An instance of [Data] 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 Data: $json") + } + } + + internal class Deserializer : BaseDeserializer(Data::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Data { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Data::class) { + + override fun serialize( + value: Data, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.bundle != null -> generator.writeObject(value.bundle) + value.inline != null -> generator.writeObject(value.inline) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Data") + } + } + } + + class Bundle + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun bundleId(): String = bundleId.getRequired("bundle_id") + + /** + * @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 location(): CodeBundle.Location = location.getRequired("location") + + /** + * @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 runtimeContext(): CodeBundle.RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * A preview of the code + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun preview(): Optional = preview.getOptional("preview") + + /** + * @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") + + /** + * Returns the raw JSON value of [bundleId]. + * + * Unlike [bundleId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("bundle_id") + @ExcludeMissing + fun _bundleId(): JsonField = bundleId + + /** + * Returns the raw JSON value of [location]. + * + * Unlike [location], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("location") + @ExcludeMissing + fun _location(): JsonField = location + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [preview]. + * + * Unlike [preview], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("preview") + @ExcludeMissing + fun _preview(): JsonField = preview + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Bundle]. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Bundle]. */ + class Builder internal constructor() { + + private var bundleId: JsonField? = null + private var location: JsonField? = null + private var runtimeContext: JsonField? = null + private var preview: JsonField = JsonMissing.of() + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(bundle: Bundle) = apply { + bundleId = bundle.bundleId + location = bundle.location + runtimeContext = bundle.runtimeContext + preview = bundle.preview + type = bundle.type + additionalProperties = bundle.additionalProperties.toMutableMap() + } + + fun bundleId(bundleId: String) = bundleId(JsonField.of(bundleId)) + + /** + * Sets [Builder.bundleId] to an arbitrary JSON value. + * + * You should usually call [Builder.bundleId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun bundleId(bundleId: JsonField) = apply { + this.bundleId = bundleId + } + + fun location(location: CodeBundle.Location) = + location(JsonField.of(location)) + + /** + * Sets [Builder.location] to an arbitrary JSON value. + * + * You should usually call [Builder.location] with a well-typed + * [CodeBundle.Location] value instead. This method is primarily for setting + * the field to an undocumented or not yet supported value. + */ + fun location(location: JsonField) = apply { + this.location = location + } + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofExperiment(experiment)`. + */ + fun location(experiment: CodeBundle.Location.Experiment) = + location(CodeBundle.Location.ofExperiment(experiment)) + + /** + * Alias for calling [location] with + * `CodeBundle.Location.ofFunction(function)`. + */ + fun location(function: CodeBundle.Location.Function) = + location(CodeBundle.Location.ofFunction(function)) + + fun runtimeContext(runtimeContext: CodeBundle.RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [CodeBundle.RuntimeContext] value instead. This method is primarily for + * setting the field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = + apply { + this.runtimeContext = runtimeContext + } + + /** A preview of the code */ + fun preview(preview: String?) = preview(JsonField.ofNullable(preview)) + + /** Alias for calling [Builder.preview] with `preview.orElse(null)`. */ + fun preview(preview: Optional) = preview(preview.getOrNull()) + + /** + * Sets [Builder.preview] to an arbitrary JSON value. + * + * You should usually call [Builder.preview] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun preview(preview: JsonField) = apply { this.preview = preview } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Bundle]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .bundleId() + * .location() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Bundle = + Bundle( + checkRequired("bundleId", bundleId), + checkRequired("location", location), + checkRequired("runtimeContext", runtimeContext), + preview, + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val BUNDLE = of("bundle") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + BUNDLE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + BUNDLE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + BUNDLE -> Value.BUNDLE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + BUNDLE -> Known.BUNDLE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Bundle && + bundleId == other.bundleId && + location == other.location && + runtimeContext == other.runtimeContext && + preview == other.preview && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + bundleId, + location, + runtimeContext, + preview, + type, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Bundle{bundleId=$bundleId, location=$location, runtimeContext=$runtimeContext, preview=$preview, type=$type, additionalProperties=$additionalProperties}" + } + + class Inline + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun code(): String = code.getRequired("code") + + /** + * @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 runtimeContext(): RuntimeContext = + runtimeContext.getRequired("runtime_context") + + /** + * @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") + + /** + * Returns the raw JSON value of [code]. + * + * Unlike [code], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("code") @ExcludeMissing fun _code(): JsonField = code + + /** + * Returns the raw JSON value of [runtimeContext]. + * + * Unlike [runtimeContext], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime_context") + @ExcludeMissing + fun _runtimeContext(): JsonField = runtimeContext + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Inline]. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Inline]. */ + class Builder internal constructor() { + + private var code: JsonField? = null + private var runtimeContext: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(inline: Inline) = apply { + code = inline.code + runtimeContext = inline.runtimeContext + type = inline.type + additionalProperties = inline.additionalProperties.toMutableMap() + } + + fun code(code: String) = code(JsonField.of(code)) + + /** + * Sets [Builder.code] to an arbitrary JSON value. + * + * You should usually call [Builder.code] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun code(code: JsonField) = apply { this.code = code } + + fun runtimeContext(runtimeContext: RuntimeContext) = + runtimeContext(JsonField.of(runtimeContext)) + + /** + * Sets [Builder.runtimeContext] to an arbitrary JSON value. + * + * You should usually call [Builder.runtimeContext] with a well-typed + * [RuntimeContext] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun runtimeContext(runtimeContext: JsonField) = apply { + this.runtimeContext = runtimeContext + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Inline]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .code() + * .runtimeContext() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Inline = + Inline( + checkRequired("code", code), + checkRequired("runtimeContext", runtimeContext), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun runtime(): Runtime = runtime.getRequired("runtime") + + /** + * @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 version(): String = version.getRequired("version") + + /** + * Returns the raw JSON value of [runtime]. + * + * Unlike [runtime], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("runtime") + @ExcludeMissing + fun _runtime(): JsonField = runtime + + /** + * 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 + + @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 + * [RuntimeContext]. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RuntimeContext]. */ + class Builder internal constructor() { + + private var runtime: JsonField? = null + private var version: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(runtimeContext: RuntimeContext) = apply { + runtime = runtimeContext.runtime + version = runtimeContext.version + additionalProperties = + runtimeContext.additionalProperties.toMutableMap() + } + + fun runtime(runtime: Runtime) = runtime(JsonField.of(runtime)) + + /** + * Sets [Builder.runtime] to an arbitrary JSON value. + * + * You should usually call [Builder.runtime] with a well-typed [Runtime] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun runtime(runtime: JsonField) = apply { + this.runtime = runtime + } + + fun version(version: String) = version(JsonField.of(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 { + this.version = version + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RuntimeContext]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .runtime() + * .version() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RuntimeContext = + RuntimeContext( + checkRequired("runtime", runtime), + checkRequired("version", version), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from + * data that doesn't match any known member, and you want to know that + * value. For example, if the SDK is on an older version than the API, + * then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val NODE = of("node") + + @JvmField val PYTHON = of("python") + + @JvmStatic fun of(value: String) = Runtime(JsonField.of(value)) + } + + /** An enum containing [Runtime]'s known values. */ + enum class Known { + NODE, + PYTHON, + } + + /** + * An enum containing [Runtime]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Runtime] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. + * For example, if the SDK is on an older version than the API, then + * the API may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + NODE, + PYTHON, + /** + * An enum member indicating that [Runtime] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, + * or [Value._UNKNOWN] if the class was instantiated with an unknown + * value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + NODE -> Value.NODE + PYTHON -> Value.PYTHON + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is + * always known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value + * is a not a known member. + */ + fun known(): Known = + when (this) { + NODE -> Known.NODE + PYTHON -> Known.PYTHON + else -> + throw BraintrustInvalidDataException( + "Unknown Runtime: $value" + ) + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is + * primarily for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Runtime && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RuntimeContext && + runtime == other.runtime && + version == other.version && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(runtime, version, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RuntimeContext{runtime=$runtime, version=$version, additionalProperties=$additionalProperties}" + } + + class Type + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val INLINE = of("inline") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + INLINE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + INLINE, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + INLINE -> Value.INLINE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + INLINE -> Known.INLINE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Inline && + code == other.code && + runtimeContext == other.runtimeContext && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(code, runtimeContext, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Inline{code=$code, runtimeContext=$runtimeContext, type=$type, additionalProperties=$additionalProperties}" + } + } + + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CODE = of("code") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + CODE + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + CODE, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + CODE -> Value.CODE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + CODE -> Known.CODE + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Code && + data == other.data && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(data, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Code{data=$data, type=$type, additionalProperties=$additionalProperties}" + } + + class Global + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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") + + /** + * 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 [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Global]. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Global]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(global: Global) = apply { + name = global.name + type = global.type + additionalProperties = global.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Global]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Global = + Global( + checkRequired("name", name), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GLOBAL = of("global") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + GLOBAL + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GLOBAL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GLOBAL -> Value.GLOBAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GLOBAL -> Known.GLOBAL + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Global && + name == other.name && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Global{name=$name, type=$type, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FunctionUpdateParams && + functionId == other.functionId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(functionId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "FunctionUpdateParams{functionId=$functionId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..8d26f5d0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Group.kt @@ -0,0 +1,568 @@ +// 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.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * A group is a collection of users which can be assigned an ACL + * + * Groups can consist of individual users, as well as a set of groups they inherit from + */ +class Group +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * 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") + + /** + * Unique id for the organization that the group belongs under + * + * It is forbidden to change the org after creating a 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 orgId(): String = orgId.getRequired("org_id") + + /** + * Date of group creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Date of group deletion, or null if the group 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") + + /** + * 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") + + /** + * Identifies the user who created the group + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [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 [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Group]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .orgId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Group]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var orgId: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var deletedAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var memberGroups: JsonField>? = null + private var memberUsers: JsonField>? = null + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(group: Group) = apply { + id = group.id + name = group.name + orgId = group.orgId + created = group.created + deletedAt = group.deletedAt + description = group.description + memberGroups = group.memberGroups.map { it.toMutableList() } + memberUsers = group.memberUsers.map { it.toMutableList() } + userId = group.userId + additionalProperties = group.additionalProperties.toMutableMap() + } + + /** Unique identifier for the group */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** 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 } + + /** + * Unique id for the organization that the group belongs under + * + * It is forbidden to change the org after creating a group + */ + fun orgId(orgId: String) = orgId(JsonField.of(orgId)) + + /** + * 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 } + + /** Date of group creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Date of group deletion, or null if the group is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } + + /** 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 of + * their inherited users + */ + fun memberGroups(memberGroups: List?) = + memberGroups(JsonField.ofNullable(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 { + this.memberGroups = memberGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [memberGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberGroup(memberGroup: String) = apply { + memberGroups = + (memberGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("memberGroups", it).add(memberGroup) + } + } + + /** Ids of users which belong to this group */ + fun memberUsers(memberUsers: List?) = memberUsers(JsonField.ofNullable(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 { + this.memberUsers = memberUsers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [memberUsers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberUser(memberUser: String) = apply { + memberUsers = + (memberUsers ?: JsonField.of(mutableListOf())).also { + checkKnown("memberUsers", it).add(memberUser) + } + } + + /** Identifies the user who created the group */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Group]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .orgId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Group = + Group( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("orgId", orgId), + created, + deletedAt, + description, + (memberGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (memberUsers ?: JsonMissing.of()).map { it.toImmutable() }, + userId, + 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 + } + + return other is Group && + id == other.id && + name == other.name && + orgId == other.orgId && + created == other.created && + deletedAt == other.deletedAt && + description == other.description && + memberGroups == other.memberGroups && + memberUsers == other.memberUsers && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + orgId, + created, + deletedAt, + description, + memberGroups, + memberUsers, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Group{id=$id, name=$name, orgId=$orgId, created=$created, deletedAt=$deletedAt, description=$description, memberGroups=$memberGroups, memberUsers=$memberUsers, userId=$userId, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..2cc4d139 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupCreateParams.kt @@ -0,0 +1,806 @@ +// 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.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.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 + +/** + * Create a new group. If there is an existing group with the same name as the one specified in the + * request, will return the existing group unmodified + */ +class GroupCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.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 = body.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> = body.memberGroups() + + /** + * 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> = body.memberUsers() + + /** + * 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 = body.orgName() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [memberGroups]. + * + * Unlike [memberGroups], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _memberGroups(): JsonField> = body._memberGroups() + + /** + * Returns the raw JSON value of [memberUsers]. + * + * Unlike [memberUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _memberUsers(): JsonField> = body._memberUsers() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [GroupCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** + * 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] + * - [description] + * - [memberGroups] + * - [memberUsers] + * - [orgName] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.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) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 + * of their inherited users + */ + fun memberGroups(memberGroups: List?) = + memberGroups(JsonField.ofNullable(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 { + this.memberGroups = memberGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [memberGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberGroup(memberGroup: String) = apply { + memberGroups = + (memberGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("memberGroups", it).add(memberGroup) + } + } + + /** Ids of users which belong to this group */ + fun memberUsers(memberUsers: List?) = + memberUsers(JsonField.ofNullable(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 { + this.memberUsers = memberUsers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [memberUsers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberUser(memberUser: String) = apply { + memberUsers = + (memberUsers ?: JsonField.of(mutableListOf())).also { + checkKnown("memberUsers", it).add(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?) = 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), + description, + (memberGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (memberUsers ?: JsonMissing.of()).map { it.toImmutable() }, + orgName, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + description() + memberGroups() + memberUsers() + 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 (description.asKnown().isPresent) 1 else 0) + + (memberGroups.asKnown().getOrNull()?.size ?: 0) + + (memberUsers.asKnown().getOrNull()?.size ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + description == other.description && + memberGroups == other.memberGroups && + memberUsers == other.memberUsers && + orgName == other.orgName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + description, + memberGroups, + memberUsers, + orgName, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, description=$description, memberGroups=$memberGroups, memberUsers=$memberUsers, orgName=$orgName, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GroupCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "GroupCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..aaf2ab81 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete a group object by its id */ +class GroupDeleteParams +private constructor( + private val groupId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** Group id */ + fun groupId(): Optional = Optional.ofNullable(groupId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): GroupDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GroupDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GroupDeleteParams]. */ + class Builder internal constructor() { + + private var groupId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(groupDeleteParams: GroupDeleteParams) = apply { + groupId = groupDeleteParams.groupId + additionalHeaders = groupDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = groupDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = groupDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** Group id */ + fun groupId(groupId: String?) = apply { this.groupId = groupId } + + /** 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) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [GroupDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): GroupDeleteParams = + GroupDeleteParams( + groupId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is GroupDeleteParams && + groupId == other.groupId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(groupId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "GroupDeleteParams{groupId=$groupId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100755 index 00000000..0e0898de --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPage.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.GroupService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see GroupService.list */ +class GroupListPage +private constructor( + private val service: GroupService, + private val params: GroupListParams, + private val response: GroupListPageResponse, +) : Page { + + /** + * Delegates to [GroupListPageResponse], but gracefully handles missing data. + * + * @see GroupListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): GroupListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): GroupListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): GroupListParams = params + + /** The response that this page was parsed from. */ + fun response(): GroupListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [GroupListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GroupListPage]. */ + class Builder internal constructor() { + + private var service: GroupService? = null + private var params: GroupListParams? = null + private var response: GroupListPageResponse? = null + + @JvmSynthetic + internal fun from(groupListPage: GroupListPage) = apply { + service = groupListPage.service + params = groupListPage.params + response = groupListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GroupListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..688fe9a2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageAsync.kt @@ -0,0 +1,138 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.GroupServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see GroupServiceAsync.list */ +class GroupListPageAsync +private constructor( + private val service: GroupServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: GroupListParams, + private val response: GroupListPageResponse, +) : PageAsync { + + /** + * Delegates to [GroupListPageResponse], but gracefully handles missing data. + * + * @see GroupListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): GroupListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): GroupListParams = params + + /** The response that this page was parsed from. */ + fun response(): GroupListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [GroupListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GroupListPageAsync]. */ + class Builder internal constructor() { + + private var service: GroupServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: GroupListParams? = null + private var response: GroupListPageResponse? = null + + @JvmSynthetic + internal fun from(groupListPageAsync: GroupListPageAsync) = apply { + service = groupListPageAsync.service + streamHandlerExecutor = groupListPageAsync.streamHandlerExecutor + params = groupListPageAsync.params + response = groupListPageAsync.response + } + + fun service(service: GroupServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): GroupListPageAsync = + GroupListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GroupListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "GroupListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..2041e2a3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListPageResponse.kt @@ -0,0 +1,193 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is GroupListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..186ac5df --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupListParams.kt @@ -0,0 +1,401 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all groups. The groups are sorted by creation date, with the most recently-created + * groups coming first + */ +class GroupListParams +private constructor( + private val endingBefore: String?, + private val groupName: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** Name of the group to search for */ + fun groupName(): Optional = Optional.ofNullable(groupName) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): GroupListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GroupListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GroupListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var groupName: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(groupListParams: GroupListParams) = apply { + endingBefore = groupListParams.endingBefore + groupName = groupListParams.groupName + ids = groupListParams.ids + limit = groupListParams.limit + orgName = groupListParams.orgName + startingAfter = groupListParams.startingAfter + additionalHeaders = groupListParams.additionalHeaders.toBuilder() + additionalQueryParams = groupListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** Name of the group to search for */ + fun groupName(groupName: String?) = apply { this.groupName = groupName } + + /** Alias for calling [Builder.groupName] with `groupName.orElse(null)`. */ + fun groupName(groupName: Optional) = groupName(groupName.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [GroupListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): GroupListParams = + GroupListParams( + endingBefore, + groupName, + ids, + limit, + orgName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GroupListParams && + endingBefore == other.endingBefore && + groupName == other.groupName && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + groupName, + ids, + limit, + orgName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "GroupListParams{endingBefore=$endingBefore, groupName=$groupName, ids=$ids, limit=$limit, orgName=$orgName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..8c31f44d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupReplaceParams.kt @@ -0,0 +1,806 @@ +// 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.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.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 + +/** + * Create or replace group. If there is an existing group with the same name as the one specified in + * the request, will replace the existing group with the provided fields + */ +class GroupReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.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 = body.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> = body.memberGroups() + + /** + * 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> = body.memberUsers() + + /** + * 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 = body.orgName() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [memberGroups]. + * + * Unlike [memberGroups], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _memberGroups(): JsonField> = body._memberGroups() + + /** + * Returns the raw JSON value of [memberUsers]. + * + * Unlike [memberUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _memberUsers(): JsonField> = body._memberUsers() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [GroupReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** + * 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] + * - [description] + * - [memberGroups] + * - [memberUsers] + * - [orgName] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.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) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 + * of their inherited users + */ + fun memberGroups(memberGroups: List?) = + memberGroups(JsonField.ofNullable(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 { + this.memberGroups = memberGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [memberGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberGroup(memberGroup: String) = apply { + memberGroups = + (memberGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("memberGroups", it).add(memberGroup) + } + } + + /** Ids of users which belong to this group */ + fun memberUsers(memberUsers: List?) = + memberUsers(JsonField.ofNullable(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 { + this.memberUsers = memberUsers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [memberUsers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberUser(memberUser: String) = apply { + memberUsers = + (memberUsers ?: JsonField.of(mutableListOf())).also { + checkKnown("memberUsers", it).add(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?) = 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), + description, + (memberGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (memberUsers ?: JsonMissing.of()).map { it.toImmutable() }, + orgName, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + description() + memberGroups() + memberUsers() + 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 (description.asKnown().isPresent) 1 else 0) + + (memberGroups.asKnown().getOrNull()?.size ?: 0) + + (memberUsers.asKnown().getOrNull()?.size ?: 0) + + (if (orgName.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + description == other.description && + memberGroups == other.memberGroups && + memberUsers == other.memberUsers && + orgName == other.orgName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + description, + memberGroups, + memberUsers, + orgName, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, description=$description, memberGroups=$memberGroups, memberUsers=$memberUsers, orgName=$orgName, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GroupReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "GroupReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..ec78ce09 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupRetrieveParams.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a group object by its id */ +class GroupRetrieveParams +private constructor( + private val groupId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Group id */ + fun groupId(): Optional = Optional.ofNullable(groupId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): GroupRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GroupRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GroupRetrieveParams]. */ + class Builder internal constructor() { + + private var groupId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(groupRetrieveParams: GroupRetrieveParams) = apply { + groupId = groupRetrieveParams.groupId + additionalHeaders = groupRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = groupRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Group id */ + fun groupId(groupId: String?) = apply { this.groupId = groupId } + + /** 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) + } + + 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 [GroupRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): GroupRetrieveParams = + GroupRetrieveParams(groupId, additionalHeaders.build(), additionalQueryParams.build()) + } + + 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 + } + + return other is GroupRetrieveParams && + groupId == other.groupId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(groupId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "GroupRetrieveParams{groupId=$groupId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..3ea798f9 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/GroupUpdateParams.kt @@ -0,0 +1,948 @@ +// 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.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.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 + +/** + * Partially update a group object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ +class GroupUpdateParams +private constructor( + private val groupId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Group id */ + fun groupId(): Optional = Optional.ofNullable(groupId) + + /** + * 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> = body.addMemberGroups() + + /** + * 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> = body.addMemberUsers() + + /** + * 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 = body.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 = body.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> = body.removeMemberGroups() + + /** + * 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> = body.removeMemberUsers() + + /** + * Returns the raw JSON value of [addMemberGroups]. + * + * Unlike [addMemberGroups], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _addMemberGroups(): JsonField> = body._addMemberGroups() + + /** + * Returns the raw JSON value of [addMemberUsers]. + * + * Unlike [addMemberUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _addMemberUsers(): JsonField> = body._addMemberUsers() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [removeMemberGroups]. + * + * Unlike [removeMemberGroups], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _removeMemberGroups(): JsonField> = body._removeMemberGroups() + + /** + * Returns the raw JSON value of [removeMemberUsers]. + * + * Unlike [removeMemberUsers], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _removeMemberUsers(): JsonField> = body._removeMemberUsers() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): GroupUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [GroupUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** Group id */ + fun groupId(groupId: String?) = apply { this.groupId = groupId } + + /** Alias for calling [Builder.groupId] with `groupId.orElse(null)`. */ + fun groupId(groupId: Optional) = groupId(groupId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [addMemberGroups] + * - [addMemberUsers] + * - [description] + * - [name] + * - [removeMemberGroups] + * - etc. + */ + 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()) + + /** + * 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) } + + 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. + */ + fun build(): GroupUpdateParams = + GroupUpdateParams( + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 + internal fun from(body: Body) = apply { + addMemberGroups = body.addMemberGroups.map { it.toMutableList() } + addMemberUsers = body.addMemberUsers.map { it.toMutableList() } + description = body.description + name = body.name + removeMemberGroups = body.removeMemberGroups.map { it.toMutableList() } + removeMemberUsers = body.removeMemberUsers.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of group IDs to add to the group's inheriting-from set */ + fun addMemberGroups(addMemberGroups: List?) = + addMemberGroups(JsonField.ofNullable(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 { + this.addMemberGroups = addMemberGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [addMemberGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAddMemberGroup(addMemberGroup: String) = apply { + addMemberGroups = + (addMemberGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("addMemberGroups", it).add(addMemberGroup) + } + } + + /** A list of user IDs to add to the group */ + fun addMemberUsers(addMemberUsers: List?) = + addMemberUsers(JsonField.ofNullable(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 { + this.addMemberUsers = addMemberUsers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [addMemberUsers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAddMemberUser(addMemberUser: String) = apply { + addMemberUsers = + (addMemberUsers ?: JsonField.of(mutableListOf())).also { + checkKnown("addMemberUsers", it).add(addMemberUser) + } + } + + /** 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 + } + + /** Name of the group */ + 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 } + + /** A list of group IDs to remove from the group's inheriting-from set */ + fun removeMemberGroups(removeMemberGroups: List?) = + removeMemberGroups(JsonField.ofNullable(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 { + this.removeMemberGroups = removeMemberGroups.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [removeMemberGroups]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRemoveMemberGroup(removeMemberGroup: String) = apply { + removeMemberGroups = + (removeMemberGroups ?: JsonField.of(mutableListOf())).also { + checkKnown("removeMemberGroups", it).add(removeMemberGroup) + } + } + + /** A list of user IDs to remove from the group */ + fun removeMemberUsers(removeMemberUsers: List?) = + removeMemberUsers(JsonField.ofNullable(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 { + this.removeMemberUsers = removeMemberUsers.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [removeMemberUsers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRemoveMemberUser(removeMemberUser: String) = apply { + removeMemberUsers = + (removeMemberUsers ?: JsonField.of(mutableListOf())).also { + checkKnown("removeMemberUsers", it).add(removeMemberUser) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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( + (addMemberGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (addMemberUsers ?: JsonMissing.of()).map { it.toImmutable() }, + description, + name, + (removeMemberGroups ?: JsonMissing.of()).map { it.toImmutable() }, + (removeMemberUsers ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + addMemberGroups() + addMemberUsers() + description() + name() + removeMemberGroups() + removeMemberUsers() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + 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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + addMemberGroups == other.addMemberGroups && + addMemberUsers == other.addMemberUsers && + description == other.description && + name == other.name && + removeMemberGroups == other.removeMemberGroups && + removeMemberUsers == other.removeMemberUsers && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + addMemberGroups, + addMemberUsers, + description, + name, + removeMemberGroups, + removeMemberUsers, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{addMemberGroups=$addMemberGroups, addMemberUsers=$addMemberUsers, description=$description, name=$name, removeMemberGroups=$removeMemberGroups, removeMemberUsers=$removeMemberUsers, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GroupUpdateParams && + groupId == other.groupId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(groupId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "GroupUpdateParams{groupId=$groupId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..aa7784d0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertDatasetEvent.kt @@ -0,0 +1,1059 @@ +// 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.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 + +/** A dataset event */ +class InsertDatasetEvent +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * The `_is_merge` field controls how the row is merged with any existing row with the same id + * in the DB. By default (or when set to `false`), the existing row is completely replaced by + * the new row. When set to `true`, the new row is deep-merged into the existing row, if one is + * found. If no existing row is found, the new row is inserted as is. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, "b": + * 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": 11, "c": + * 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": 20}}`. If we + * replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be + * `{"id": "foo", "input": {"b": 11, "c": 20}}` + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _isMerge(): Optional = _isMerge.getOptional("_is_merge") + + /** + * The `_merge_paths` field allows controlling the depth of the merge, when `_is_merge=true`. + * `_merge_paths` is a list of paths, where each path is a list of field names. The deep merge + * will not descend below any of the specified merge paths. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": {"b": 10}, + * "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as `{"_is_merge": true, + * "_merge_paths": [["input", "a"], ["output"]], "input": {"a": {"q": 30}, "c": {"e": 30}, + * "bar": "baz"}, "output": {"d": 40}}`, the new row will be `{"id": "foo": "input": {"a": {"q": + * 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, "output": {"d": 40}}`. In this case, due to the + * merge paths, we have replaced `input.a` and `output`, but have still deep-merged `input` and + * `input.c`. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _mergePaths(): Optional>> = _mergePaths.getOptional("_merge_paths") + + /** + * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will not show up + * in subsequent fetches for this dataset + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _objectDelete(): Optional = _objectDelete.getOptional("_object_delete") + + /** + * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for + * `_parent_id` will be dropped in a future version of Braintrust. Log `span_id`, + * `root_span_id`, and `span_parents` explicitly instead. + * + * Use the `_parent_id` field to create this row as a subspan of an existing row. Tracking + * hierarchical relationships are important for tracing (see the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details). + * + * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", + * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the parent + * row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": "What comes after + * foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root span row + * `"abc"` will show up in the summary view. You can view the full trace hierarchy (in this + * case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _parentId(): Optional = _parentId.getOptional("_parent_id") + + /** + * The timestamp the dataset event was created + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * The output of your application, including post-processing (an arbitrary, JSON serializable + * object) + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** The argument that uniquely define an input case (an arbitrary, JSON serializable object) */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonValue = input + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + * + * @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") + + /** + * Indicates the event was copied from another object. + * + * @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") + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun rootSpanId(): Optional = rootSpanId.getOptional("root_span_id") + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanId(): Optional = spanId.getOptional("span_id") + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanParents(): Optional> = spanParents.getOptional("span_parents") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_isMerge]. + * + * Unlike [_isMerge], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge(): JsonField = _isMerge + + /** + * Returns the raw JSON value of [_mergePaths]. + * + * Unlike [_mergePaths], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_merge_paths") + @ExcludeMissing + fun __mergePaths(): JsonField>> = _mergePaths + + /** + * Returns the raw JSON value of [_objectDelete]. + * + * Unlike [_objectDelete], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_object_delete") + @ExcludeMissing + fun __objectDelete(): JsonField = _objectDelete + + /** + * Returns the raw JSON value of [_parentId]. + * + * Unlike [_parentId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_parent_id") @ExcludeMissing fun __parentId(): JsonField = _parentId + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [origin]. + * + * Unlike [origin], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("origin") @ExcludeMissing fun _origin(): JsonField = origin + + /** + * Returns the raw JSON value of [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId(): JsonField = rootSpanId + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + + /** + * Returns the raw JSON value of [spanParents]. + * + * Unlike [spanParents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_parents") + @ExcludeMissing + fun _spanParents(): JsonField> = spanParents + + /** + * 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 [InsertDatasetEvent]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsertDatasetEvent]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var _isMerge: JsonField = JsonMissing.of() + private var _mergePaths: JsonField>>? = null + private var _objectDelete: JsonField = JsonMissing.of() + private var _parentId: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var expected: JsonValue = JsonMissing.of() + private var input: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var rootSpanId: JsonField = JsonMissing.of() + private var spanId: JsonField = JsonMissing.of() + private var spanParents: JsonField>? = null + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(insertDatasetEvent: InsertDatasetEvent) = apply { + id = insertDatasetEvent.id + _isMerge = insertDatasetEvent._isMerge + _mergePaths = insertDatasetEvent._mergePaths.map { it.toMutableList() } + _objectDelete = insertDatasetEvent._objectDelete + _parentId = insertDatasetEvent._parentId + created = insertDatasetEvent.created + expected = insertDatasetEvent.expected + input = insertDatasetEvent.input + metadata = insertDatasetEvent.metadata + origin = insertDatasetEvent.origin + rootSpanId = insertDatasetEvent.rootSpanId + spanId = insertDatasetEvent.spanId + spanParents = insertDatasetEvent.spanParents.map { it.toMutableList() } + tags = insertDatasetEvent.tags.map { it.toMutableList() } + additionalProperties = insertDatasetEvent.additionalProperties.toMutableMap() + } + + /** + * A unique identifier for the dataset event. If you don't provide one, BrainTrust will + * generate one for you + */ + fun id(id: String?) = id(JsonField.ofNullable(id)) + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The `_is_merge` field controls how the row is merged with any existing row with the same + * id in the DB. By default (or when set to `false`), the existing row is completely + * replaced by the new row. When set to `true`, the new row is deep-merged into the existing + * row, if one is found. If no existing row is found, the new row is inserted as is. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, "b": + * 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": 11, "c": + * 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": 20}}`. If we + * replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be + * `{"id": "foo", "input": {"b": 11, "c": 20}}` + */ + fun _isMerge(_isMerge: Boolean?) = _isMerge(JsonField.ofNullable(_isMerge)) + + /** + * Alias for [Builder._isMerge]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun _isMerge(_isMerge: Boolean) = _isMerge(_isMerge as Boolean?) + + /** Alias for calling [Builder._isMerge] with `_isMerge.orElse(null)`. */ + fun _isMerge(_isMerge: Optional) = _isMerge(_isMerge.getOrNull()) + + /** + * Sets [Builder._isMerge] to an arbitrary JSON value. + * + * You should usually call [Builder._isMerge] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } + + /** + * The `_merge_paths` field allows controlling the depth of the merge, when + * `_is_merge=true`. `_merge_paths` is a list of paths, where each path is a list of field + * names. The deep merge will not descend below any of the specified merge paths. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": {"b": + * 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as `{"_is_merge": + * true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": {"q": 30}, "c": {"e": + * 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be `{"id": "foo": "input": + * {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, "output": {"d": 40}}`. In this + * case, due to the merge paths, we have replaced `input.a` and `output`, but have still + * deep-merged `input` and `input.c`. + */ + fun _mergePaths(_mergePaths: List>?) = + _mergePaths(JsonField.ofNullable(_mergePaths)) + + /** Alias for calling [Builder._mergePaths] with `_mergePaths.orElse(null)`. */ + fun _mergePaths(_mergePaths: Optional>>) = + _mergePaths(_mergePaths.getOrNull()) + + /** + * Sets [Builder._mergePaths] to an arbitrary JSON value. + * + * You should usually call [Builder._mergePaths] with a well-typed `List>` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun _mergePaths(_mergePaths: JsonField>>) = apply { + this._mergePaths = _mergePaths.map { it.toMutableList() } + } + + /** + * Adds a single [List] to [_mergePaths]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMergePath(mergePath: List) = apply { + _mergePaths = + (_mergePaths ?: JsonField.of(mutableListOf())).also { + checkKnown("_mergePaths", it).add(mergePath) + } + } + + /** + * Pass `_object_delete=true` to mark the dataset event deleted. Deleted events will not + * show up in subsequent fetches for this dataset + */ + fun _objectDelete(_objectDelete: Boolean?) = + _objectDelete(JsonField.ofNullable(_objectDelete)) + + /** + * Alias for [Builder._objectDelete]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun _objectDelete(_objectDelete: Boolean) = _objectDelete(_objectDelete as Boolean?) + + /** Alias for calling [Builder._objectDelete] with `_objectDelete.orElse(null)`. */ + fun _objectDelete(_objectDelete: Optional) = + _objectDelete(_objectDelete.getOrNull()) + + /** + * Sets [Builder._objectDelete] to an arbitrary JSON value. + * + * You should usually call [Builder._objectDelete] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun _objectDelete(_objectDelete: JsonField) = apply { + this._objectDelete = _objectDelete + } + + /** + * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for + * `_parent_id` will be dropped in a future version of Braintrust. Log `span_id`, + * `root_span_id`, and `span_parents` explicitly instead. + * + * Use the `_parent_id` field to create this row as a subspan of an existing row. Tracking + * hierarchical relationships are important for tracing (see the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details). + * + * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", + * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the + * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the + * root span row `"abc"` will show up in the summary view. You can view the full trace + * hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun _parentId(_parentId: String?) = _parentId(JsonField.ofNullable(_parentId)) + + /** Alias for calling [Builder._parentId] with `_parentId.orElse(null)`. */ + fun _parentId(_parentId: Optional) = _parentId(_parentId.getOrNull()) + + /** + * Sets [Builder._parentId] to an arbitrary JSON value. + * + * You should usually call [Builder._parentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun _parentId(_parentId: JsonField) = apply { this._parentId = _parentId } + + /** The timestamp the dataset event was created */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** + * The output of your application, including post-processing (an arbitrary, JSON + * serializable object) + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * The argument that uniquely define an input case (an arbitrary, JSON serializable object) + */ + fun input(input: JsonValue) = apply { this.input = input } + + /** + * 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 example, you could log the `prompt`, example's `id`, or anything else that would be + * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, + * but its keys must be strings + */ + 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 } + + /** Indicates the event was copied from another object. */ + fun origin(origin: ObjectReference?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [ObjectReference] 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 } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun rootSpanId(rootSpanId: String?) = rootSpanId(JsonField.ofNullable(rootSpanId)) + + /** Alias for calling [Builder.rootSpanId] with `rootSpanId.orElse(null)`. */ + fun rootSpanId(rootSpanId: Optional) = rootSpanId(rootSpanId.getOrNull()) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun spanId(spanId: String?) = spanId(JsonField.ofNullable(spanId)) + + /** Alias for calling [Builder.spanId] with `spanId.orElse(null)`. */ + fun spanId(spanId: Optional) = spanId(spanId.getOrNull()) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun spanParents(spanParents: List?) = spanParents(JsonField.ofNullable(spanParents)) + + /** Alias for calling [Builder.spanParents] with `spanParents.orElse(null)`. */ + fun spanParents(spanParents: Optional>) = spanParents(spanParents.getOrNull()) + + /** + * Sets [Builder.spanParents] to an arbitrary JSON value. + * + * You should usually call [Builder.spanParents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanParents(spanParents: JsonField>) = apply { + this.spanParents = spanParents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [spanParents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSpanParent(spanParent: String) = apply { + spanParents = + (spanParents ?: JsonField.of(mutableListOf())).also { + checkKnown("spanParents", it).add(spanParent) + } + } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InsertDatasetEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InsertDatasetEvent = + InsertDatasetEvent( + id, + _isMerge, + (_mergePaths ?: JsonMissing.of()).map { it.toImmutable() }, + _objectDelete, + _parentId, + created, + expected, + input, + metadata, + origin, + rootSpanId, + spanId, + (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, + (tags ?: JsonMissing.of()).map { it.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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + */ + class Metadata + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = model.getOptional("model") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + @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 [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var model: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + model = metadata.model + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + /** The model used for this example */ + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(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 + } + + return other is Metadata && + model == other.model && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(model, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{model=$model, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsertDatasetEvent && + id == other.id && + _isMerge == other._isMerge && + _mergePaths == other._mergePaths && + _objectDelete == other._objectDelete && + _parentId == other._parentId && + created == other.created && + expected == other.expected && + input == other.input && + metadata == other.metadata && + origin == other.origin && + rootSpanId == other.rootSpanId && + spanId == other.spanId && + spanParents == other.spanParents && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _isMerge, + _mergePaths, + _objectDelete, + _parentId, + created, + expected, + input, + metadata, + origin, + rootSpanId, + spanId, + spanParents, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InsertDatasetEvent{id=$id, _isMerge=$_isMerge, _mergePaths=$_mergePaths, _objectDelete=$_objectDelete, _parentId=$_parentId, created=$created, expected=$expected, input=$input, metadata=$metadata, origin=$origin, rootSpanId=$rootSpanId, spanId=$spanId, spanParents=$spanParents, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..4d343317 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertEventsResponse.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 InsertEventsResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 rowIds(): List = rowIds.getRequired("row_ids") + + /** + * Returns the raw JSON value of [rowIds]. + * + * Unlike [rowIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InsertEventsResponse]. + * + * The following fields are required: + * ```java + * .rowIds() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsertEventsResponse]. */ + class Builder internal constructor() { + + private var rowIds: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(insertEventsResponse: InsertEventsResponse) = apply { + rowIds = insertEventsResponse.rowIds.map { it.toMutableList() } + additionalProperties = insertEventsResponse.additionalProperties.toMutableMap() + } + + /** + * The ids of all rows that were inserted, aligning one-to-one with the rows provided as + * input + */ + fun rowIds(rowIds: List) = rowIds(JsonField.of(rowIds)) + + /** + * Sets [Builder.rowIds] to an arbitrary JSON value. + * + * You should usually call [Builder.rowIds] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rowIds(rowIds: JsonField>) = apply { + this.rowIds = rowIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [rowIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addRowId(rowId: String) = apply { + rowIds = + (rowIds ?: JsonField.of(mutableListOf())).also { + checkKnown("rowIds", it).add(rowId) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InsertEventsResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .rowIds() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InsertEventsResponse = + InsertEventsResponse( + checkRequired("rowIds", rowIds).map { it.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 + } + + return other is InsertEventsResponse && + rowIds == other.rowIds && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(rowIds, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InsertEventsResponse{rowIds=$rowIds, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..a2d9a918 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertExperimentEvent.kt @@ -0,0 +1,2132 @@ +// 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.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 + +/** An experiment event */ +class InsertExperimentEvent +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * The `_is_merge` field controls how the row is merged with any existing row with the same id + * in the DB. By default (or when set to `false`), the existing row is completely replaced by + * the new row. When set to `true`, the new row is deep-merged into the existing row, if one is + * found. If no existing row is found, the new row is inserted as is. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, "b": + * 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": 11, "c": + * 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": 20}}`. If we + * replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be + * `{"id": "foo", "input": {"b": 11, "c": 20}}` + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _isMerge(): Optional = _isMerge.getOptional("_is_merge") + + /** + * The `_merge_paths` field allows controlling the depth of the merge, when `_is_merge=true`. + * `_merge_paths` is a list of paths, where each path is a list of field names. The deep merge + * will not descend below any of the specified merge paths. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": {"b": 10}, + * "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as `{"_is_merge": true, + * "_merge_paths": [["input", "a"], ["output"]], "input": {"a": {"q": 30}, "c": {"e": 30}, + * "bar": "baz"}, "output": {"d": 40}}`, the new row will be `{"id": "foo": "input": {"a": {"q": + * 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, "output": {"d": 40}}`. In this case, due to the + * merge paths, we have replaced `input.a` and `output`, but have still deep-merged `input` and + * `input.c`. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _mergePaths(): Optional>> = _mergePaths.getOptional("_merge_paths") + + /** + * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events will not show + * up in subsequent fetches for this experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _objectDelete(): Optional = _objectDelete.getOptional("_object_delete") + + /** + * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for + * `_parent_id` will be dropped in a future version of Braintrust. Log `span_id`, + * `root_span_id`, and `span_parents` explicitly instead. + * + * Use the `_parent_id` field to create this row as a subspan of an existing row. Tracking + * hierarchical relationships are important for tracing (see the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details). + * + * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", + * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the parent + * row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": "What comes after + * foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root span row + * `"abc"` will show up in the summary view. You can view the full trace hierarchy (in this + * case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _parentId(): Optional = _parentId.getOptional("_parent_id") + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun context(): Optional = context.getOptional("context") + + /** + * The timestamp 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 created(): Optional = created.getOptional("created") + + /** The error that occurred, if any. */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does not + * compare `output` to `expected` for you, since there are so many different ways to do that + * correctly. Instead, these values are just used to help you navigate your experiments while + * digging into analyses. However, we may later use these values to re-score outputs or + * fine-tune your models + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** + * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). + * Later on, Braintrust will use the `input` to know whether two test cases are the same between + * experiments, so they should not contain experiment-specific state. A simple rule of thumb is + * that if you run the same experiment twice, the `input` should be identical + */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonValue = input + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + * + * @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") + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * experiment event. Use "start" and "end" to track the time span over which the experiment + * event was produced + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metrics(): Optional = metrics.getOptional("metrics") + + /** + * Indicates the event was copied from another object. + * + * @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 output of your application, including post-processing (an arbitrary, JSON serializable + * object), that allows you to determine whether the result is correct or not. For example, in + * an app that generates SQL queries, the `output` should be the _result_ of the SQL query + * generated by the model, not the query itself, because there may be multiple valid queries + * that answer a single question + */ + @JsonProperty("output") @ExcludeMissing fun _output(): JsonValue = output + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare experiments + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scores(): Optional = scores.getOptional("scores") + + /** + * Human-identifying attributes of the span, such as name, type, etc. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanAttributes(): Optional = spanAttributes.getOptional("span_attributes") + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanId(): Optional = spanId.getOptional("span_id") + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanParents(): Optional> = spanParents.getOptional("span_parents") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_isMerge]. + * + * Unlike [_isMerge], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge(): JsonField = _isMerge + + /** + * Returns the raw JSON value of [_mergePaths]. + * + * Unlike [_mergePaths], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_merge_paths") + @ExcludeMissing + fun __mergePaths(): JsonField>> = _mergePaths + + /** + * Returns the raw JSON value of [_objectDelete]. + * + * Unlike [_objectDelete], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_object_delete") + @ExcludeMissing + fun __objectDelete(): JsonField = _objectDelete + + /** + * Returns the raw JSON value of [_parentId]. + * + * Unlike [_parentId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_parent_id") @ExcludeMissing fun __parentId(): JsonField = _parentId + + /** + * Returns the raw JSON value of [context]. + * + * Unlike [context], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("context") @ExcludeMissing fun _context(): JsonField = context + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [metrics]. + * + * Unlike [metrics], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metrics") @ExcludeMissing fun _metrics(): JsonField = metrics + + /** + * 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 + + /** + * Returns the raw JSON value of [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId(): JsonField = rootSpanId + + /** + * 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 + + /** + * Returns the raw JSON value of [spanAttributes]. + * + * Unlike [spanAttributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_attributes") + @ExcludeMissing + fun _spanAttributes(): JsonField = spanAttributes + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + + /** + * Returns the raw JSON value of [spanParents]. + * + * Unlike [spanParents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_parents") + @ExcludeMissing + fun _spanParents(): JsonField> = spanParents + + /** + * 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 [InsertExperimentEvent]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsertExperimentEvent]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var _isMerge: JsonField = JsonMissing.of() + private var _mergePaths: JsonField>>? = null + private var _objectDelete: JsonField = JsonMissing.of() + private var _parentId: JsonField = JsonMissing.of() + private var context: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var error: JsonValue = JsonMissing.of() + private var expected: JsonValue = JsonMissing.of() + private var input: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var metrics: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var output: JsonValue = JsonMissing.of() + private var rootSpanId: JsonField = JsonMissing.of() + private var scores: JsonField = JsonMissing.of() + private var spanAttributes: JsonField = JsonMissing.of() + private var spanId: JsonField = JsonMissing.of() + private var spanParents: JsonField>? = null + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(insertExperimentEvent: InsertExperimentEvent) = apply { + id = insertExperimentEvent.id + _isMerge = insertExperimentEvent._isMerge + _mergePaths = insertExperimentEvent._mergePaths.map { it.toMutableList() } + _objectDelete = insertExperimentEvent._objectDelete + _parentId = insertExperimentEvent._parentId + context = insertExperimentEvent.context + created = insertExperimentEvent.created + error = insertExperimentEvent.error + expected = insertExperimentEvent.expected + input = insertExperimentEvent.input + metadata = insertExperimentEvent.metadata + metrics = insertExperimentEvent.metrics + origin = insertExperimentEvent.origin + output = insertExperimentEvent.output + rootSpanId = insertExperimentEvent.rootSpanId + scores = insertExperimentEvent.scores + spanAttributes = insertExperimentEvent.spanAttributes + spanId = insertExperimentEvent.spanId + spanParents = insertExperimentEvent.spanParents.map { it.toMutableList() } + tags = insertExperimentEvent.tags.map { it.toMutableList() } + additionalProperties = insertExperimentEvent.additionalProperties.toMutableMap() + } + + /** + * A unique identifier for the experiment event. If you don't provide one, BrainTrust will + * generate one for you + */ + fun id(id: String?) = id(JsonField.ofNullable(id)) + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The `_is_merge` field controls how the row is merged with any existing row with the same + * id in the DB. By default (or when set to `false`), the existing row is completely + * replaced by the new row. When set to `true`, the new row is deep-merged into the existing + * row, if one is found. If no existing row is found, the new row is inserted as is. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, "b": + * 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": 11, "c": + * 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": 20}}`. If we + * replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be + * `{"id": "foo", "input": {"b": 11, "c": 20}}` + */ + fun _isMerge(_isMerge: Boolean?) = _isMerge(JsonField.ofNullable(_isMerge)) + + /** + * Alias for [Builder._isMerge]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun _isMerge(_isMerge: Boolean) = _isMerge(_isMerge as Boolean?) + + /** Alias for calling [Builder._isMerge] with `_isMerge.orElse(null)`. */ + fun _isMerge(_isMerge: Optional) = _isMerge(_isMerge.getOrNull()) + + /** + * Sets [Builder._isMerge] to an arbitrary JSON value. + * + * You should usually call [Builder._isMerge] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } + + /** + * The `_merge_paths` field allows controlling the depth of the merge, when + * `_is_merge=true`. `_merge_paths` is a list of paths, where each path is a list of field + * names. The deep merge will not descend below any of the specified merge paths. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": {"b": + * 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as `{"_is_merge": + * true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": {"q": 30}, "c": {"e": + * 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be `{"id": "foo": "input": + * {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, "output": {"d": 40}}`. In this + * case, due to the merge paths, we have replaced `input.a` and `output`, but have still + * deep-merged `input` and `input.c`. + */ + fun _mergePaths(_mergePaths: List>?) = + _mergePaths(JsonField.ofNullable(_mergePaths)) + + /** Alias for calling [Builder._mergePaths] with `_mergePaths.orElse(null)`. */ + fun _mergePaths(_mergePaths: Optional>>) = + _mergePaths(_mergePaths.getOrNull()) + + /** + * Sets [Builder._mergePaths] to an arbitrary JSON value. + * + * You should usually call [Builder._mergePaths] with a well-typed `List>` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun _mergePaths(_mergePaths: JsonField>>) = apply { + this._mergePaths = _mergePaths.map { it.toMutableList() } + } + + /** + * Adds a single [List] to [_mergePaths]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMergePath(mergePath: List) = apply { + _mergePaths = + (_mergePaths ?: JsonField.of(mutableListOf())).also { + checkKnown("_mergePaths", it).add(mergePath) + } + } + + /** + * Pass `_object_delete=true` to mark the experiment event deleted. Deleted events will not + * show up in subsequent fetches for this experiment + */ + fun _objectDelete(_objectDelete: Boolean?) = + _objectDelete(JsonField.ofNullable(_objectDelete)) + + /** + * Alias for [Builder._objectDelete]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun _objectDelete(_objectDelete: Boolean) = _objectDelete(_objectDelete as Boolean?) + + /** Alias for calling [Builder._objectDelete] with `_objectDelete.orElse(null)`. */ + fun _objectDelete(_objectDelete: Optional) = + _objectDelete(_objectDelete.getOrNull()) + + /** + * Sets [Builder._objectDelete] to an arbitrary JSON value. + * + * You should usually call [Builder._objectDelete] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun _objectDelete(_objectDelete: JsonField) = apply { + this._objectDelete = _objectDelete + } + + /** + * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for + * `_parent_id` will be dropped in a future version of Braintrust. Log `span_id`, + * `root_span_id`, and `span_parents` explicitly instead. + * + * Use the `_parent_id` field to create this row as a subspan of an existing row. Tracking + * hierarchical relationships are important for tracing (see the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details). + * + * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", + * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the + * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the + * root span row `"abc"` will show up in the summary view. You can view the full trace + * hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun _parentId(_parentId: String?) = _parentId(JsonField.ofNullable(_parentId)) + + /** Alias for calling [Builder._parentId] with `_parentId.orElse(null)`. */ + fun _parentId(_parentId: Optional) = _parentId(_parentId.getOrNull()) + + /** + * Sets [Builder._parentId] to an arbitrary JSON value. + * + * You should usually call [Builder._parentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun _parentId(_parentId: JsonField) = apply { this._parentId = _parentId } + + /** + * 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 + */ + fun context(context: Context?) = context(JsonField.ofNullable(context)) + + /** Alias for calling [Builder.context] with `context.orElse(null)`. */ + fun context(context: Optional) = context(context.getOrNull()) + + /** + * Sets [Builder.context] to an arbitrary JSON value. + * + * You should usually call [Builder.context] with a well-typed [Context] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun context(context: JsonField) = apply { this.context = context } + + /** The timestamp the experiment event was created */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** The error that occurred, if any. */ + fun error(error: JsonValue) = apply { this.error = error } + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does + * not compare `output` to `expected` for you, since there are so many different ways to do + * that correctly. Instead, these values are just used to help you navigate your experiments + * while digging into analyses. However, we may later use these values to re-score outputs + * or fine-tune your models + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * The arguments that uniquely define a test case (an arbitrary, JSON serializable object). + * Later on, Braintrust will use the `input` to know whether two test cases are the same + * between experiments, so they should not contain experiment-specific state. A simple rule + * of thumb is that if you run the same experiment twice, the `input` should be identical + */ + fun input(input: JsonValue) = apply { this.input = input } + + /** + * 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 example, you could log the `prompt`, example's `id`, or anything else that would be + * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, + * but its keys must be strings + */ + 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 } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * experiment event. Use "start" and "end" to track the time span over which the experiment + * event was produced + */ + fun metrics(metrics: Metrics?) = metrics(JsonField.ofNullable(metrics)) + + /** Alias for calling [Builder.metrics] with `metrics.orElse(null)`. */ + fun metrics(metrics: Optional) = metrics(metrics.getOrNull()) + + /** + * Sets [Builder.metrics] to an arbitrary JSON value. + * + * You should usually call [Builder.metrics] with a well-typed [Metrics] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun metrics(metrics: JsonField) = apply { this.metrics = metrics } + + /** Indicates the event was copied from another object. */ + fun origin(origin: ObjectReference?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [ObjectReference] 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 } + + /** + * The output of your application, including post-processing (an arbitrary, JSON + * serializable object), that allows you to determine whether the result is correct or not. + * For example, in an app that generates SQL queries, the `output` should be the _result_ of + * the SQL query generated by the model, not the query itself, because there may be multiple + * valid queries that answer a single question + */ + fun output(output: JsonValue) = apply { this.output = output } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun rootSpanId(rootSpanId: String?) = rootSpanId(JsonField.ofNullable(rootSpanId)) + + /** Alias for calling [Builder.rootSpanId] with `rootSpanId.orElse(null)`. */ + fun rootSpanId(rootSpanId: Optional) = rootSpanId(rootSpanId.getOrNull()) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a + * variety of signals that help you determine how accurate the outputs are compared to what + * you expect and diagnose failures. For example, a summarization app might have one score + * that tells you how accurate the summary is, and another that measures the word similarity + * between the generated and grouth truth summary. The word similarity score could help you + * determine whether the summarization was covering similar concepts or not. You can use + * these scores to help you sort, filter, and compare experiments + */ + fun scores(scores: Scores?) = scores(JsonField.ofNullable(scores)) + + /** Alias for calling [Builder.scores] with `scores.orElse(null)`. */ + fun scores(scores: Optional) = scores(scores.getOrNull()) + + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed [Scores] 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 } + + /** Human-identifying attributes of the span, such as name, type, etc. */ + fun spanAttributes(spanAttributes: SpanAttributes?) = + spanAttributes(JsonField.ofNullable(spanAttributes)) + + /** Alias for calling [Builder.spanAttributes] with `spanAttributes.orElse(null)`. */ + fun spanAttributes(spanAttributes: Optional) = + spanAttributes(spanAttributes.getOrNull()) + + /** + * Sets [Builder.spanAttributes] to an arbitrary JSON value. + * + * You should usually call [Builder.spanAttributes] with a well-typed [SpanAttributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanAttributes(spanAttributes: JsonField) = apply { + this.spanAttributes = spanAttributes + } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun spanId(spanId: String?) = spanId(JsonField.ofNullable(spanId)) + + /** Alias for calling [Builder.spanId] with `spanId.orElse(null)`. */ + fun spanId(spanId: Optional) = spanId(spanId.getOrNull()) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun spanParents(spanParents: List?) = spanParents(JsonField.ofNullable(spanParents)) + + /** Alias for calling [Builder.spanParents] with `spanParents.orElse(null)`. */ + fun spanParents(spanParents: Optional>) = spanParents(spanParents.getOrNull()) + + /** + * Sets [Builder.spanParents] to an arbitrary JSON value. + * + * You should usually call [Builder.spanParents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanParents(spanParents: JsonField>) = apply { + this.spanParents = spanParents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [spanParents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSpanParent(spanParent: String) = apply { + spanParents = + (spanParents ?: JsonField.of(mutableListOf())).also { + checkKnown("spanParents", it).add(spanParent) + } + } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InsertExperimentEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InsertExperimentEvent = + InsertExperimentEvent( + id, + _isMerge, + (_mergePaths ?: JsonMissing.of()).map { it.toImmutable() }, + _objectDelete, + _parentId, + context, + created, + error, + expected, + input, + metadata, + metrics, + origin, + output, + rootSpanId, + scores, + spanAttributes, + spanId, + (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, + (tags ?: JsonMissing.of()).map { it.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 + */ + class Context + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = callerFilename.getOptional("caller_filename") + + /** + * The function in code which created the experiment event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun callerFunctionname(): Optional = + callerFunctionname.getOptional("caller_functionname") + + /** + * Line of 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 callerLineno(): Optional = callerLineno.getOptional("caller_lineno") + + /** + * Returns the raw JSON value of [callerFilename]. + * + * Unlike [callerFilename], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_filename") + @ExcludeMissing + fun _callerFilename(): JsonField = callerFilename + + /** + * Returns the raw JSON value of [callerFunctionname]. + * + * Unlike [callerFunctionname], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonField = callerFunctionname + + /** + * Returns the raw JSON value of [callerLineno]. + * + * Unlike [callerLineno], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_lineno") + @ExcludeMissing + fun _callerLineno(): JsonField = callerLineno + + @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 [Context]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Context]. */ + class Builder internal constructor() { + + private var callerFilename: JsonField = JsonMissing.of() + private var callerFunctionname: JsonField = JsonMissing.of() + private var callerLineno: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(context: Context) = apply { + callerFilename = context.callerFilename + callerFunctionname = context.callerFunctionname + callerLineno = context.callerLineno + additionalProperties = context.additionalProperties.toMutableMap() + } + + /** Name of the file in code where the experiment event was created */ + fun callerFilename(callerFilename: String?) = + callerFilename(JsonField.ofNullable(callerFilename)) + + /** Alias for calling [Builder.callerFilename] with `callerFilename.orElse(null)`. */ + fun callerFilename(callerFilename: Optional) = + callerFilename(callerFilename.getOrNull()) + + /** + * Sets [Builder.callerFilename] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFilename] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFilename(callerFilename: JsonField) = apply { + this.callerFilename = callerFilename + } + + /** The function in code which created the experiment event */ + fun callerFunctionname(callerFunctionname: String?) = + callerFunctionname(JsonField.ofNullable(callerFunctionname)) + + /** + * Alias for calling [Builder.callerFunctionname] with + * `callerFunctionname.orElse(null)`. + */ + fun callerFunctionname(callerFunctionname: Optional) = + callerFunctionname(callerFunctionname.getOrNull()) + + /** + * Sets [Builder.callerFunctionname] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFunctionname] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFunctionname(callerFunctionname: JsonField) = apply { + this.callerFunctionname = callerFunctionname + } + + /** Line of code where the experiment event was created */ + fun callerLineno(callerLineno: Long?) = callerLineno(JsonField.ofNullable(callerLineno)) + + /** + * Alias for [Builder.callerLineno]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun callerLineno(callerLineno: Long) = callerLineno(callerLineno as Long?) + + /** Alias for calling [Builder.callerLineno] with `callerLineno.orElse(null)`. */ + fun callerLineno(callerLineno: Optional) = callerLineno(callerLineno.getOrNull()) + + /** + * Sets [Builder.callerLineno] to an arbitrary JSON value. + * + * You should usually call [Builder.callerLineno] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerLineno(callerLineno: JsonField) = apply { + this.callerLineno = callerLineno + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Context]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Context = + Context( + callerFilename, + callerFunctionname, + callerLineno, + 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 + } + + return other is Context && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(callerFilename, callerFunctionname, callerLineno, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Context{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" + } + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + */ + class Metadata + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = model.getOptional("model") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + @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 [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var model: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + model = metadata.model + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + /** The model used for this example */ + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(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 + } + + return other is Metadata && + model == other.model && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(model, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{model=$model, additionalProperties=$additionalProperties}" + } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * experiment event. Use "start" and "end" to track the time span over which the experiment + * event was produced + */ + class Metrics + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + fun _callerFilename(): JsonValue = callerFilename + + /** This metric is deprecated */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonValue = callerFunctionname + + /** This metric is deprecated */ + @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno(): JsonValue = callerLineno + + /** + * The number of tokens in the completion generated by the model (only set if this is an LLM + * span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun completionTokens(): Optional = completionTokens.getOptional("completion_tokens") + + /** + * A unix timestamp recording when the section of code which produced the experiment event + * finished + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun end(): Optional = end.getOptional("end") + + /** + * The number of tokens in the prompt used to generate the experiment event (only set if + * this is an LLM span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptTokens(): Optional = promptTokens.getOptional("prompt_tokens") + + /** + * A unix timestamp recording when the section of code which produced the experiment event + * started + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun start(): Optional = start.getOptional("start") + + /** + * The total number of tokens in the input and output of the experiment event. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tokens(): Optional = tokens.getOptional("tokens") + + /** + * Returns the raw JSON value of [completionTokens]. + * + * Unlike [completionTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("completion_tokens") + @ExcludeMissing + fun _completionTokens(): JsonField = completionTokens + + /** + * Returns the raw JSON value of [end]. + * + * Unlike [end], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end + + /** + * Returns the raw JSON value of [promptTokens]. + * + * Unlike [promptTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("prompt_tokens") + @ExcludeMissing + fun _promptTokens(): JsonField = promptTokens + + /** + * Returns the raw JSON value of [start]. + * + * Unlike [start], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start + + /** + * Returns the raw JSON value of [tokens]. + * + * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metrics]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metrics]. */ + class Builder internal constructor() { + + private var callerFilename: JsonValue = JsonMissing.of() + private var callerFunctionname: JsonValue = JsonMissing.of() + private var callerLineno: JsonValue = JsonMissing.of() + private var completionTokens: JsonField = JsonMissing.of() + private var end: JsonField = JsonMissing.of() + private var promptTokens: JsonField = JsonMissing.of() + private var start: JsonField = JsonMissing.of() + private var tokens: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metrics: Metrics) = apply { + callerFilename = metrics.callerFilename + callerFunctionname = metrics.callerFunctionname + callerLineno = metrics.callerLineno + completionTokens = metrics.completionTokens + end = metrics.end + promptTokens = metrics.promptTokens + start = metrics.start + tokens = metrics.tokens + additionalProperties = metrics.additionalProperties.toMutableMap() + } + + /** This metric is deprecated */ + fun callerFilename(callerFilename: JsonValue) = apply { + this.callerFilename = callerFilename + } + + /** This metric is deprecated */ + fun callerFunctionname(callerFunctionname: JsonValue) = apply { + this.callerFunctionname = callerFunctionname + } + + /** This metric is deprecated */ + fun callerLineno(callerLineno: JsonValue) = apply { this.callerLineno = callerLineno } + + /** + * The number of tokens in the completion generated by the model (only set if this is an + * LLM span) + */ + fun completionTokens(completionTokens: Long?) = + completionTokens(JsonField.ofNullable(completionTokens)) + + /** + * Alias for [Builder.completionTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun completionTokens(completionTokens: Long) = + completionTokens(completionTokens as Long?) + + /** + * Alias for calling [Builder.completionTokens] with `completionTokens.orElse(null)`. + */ + fun completionTokens(completionTokens: Optional) = + completionTokens(completionTokens.getOrNull()) + + /** + * Sets [Builder.completionTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.completionTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun completionTokens(completionTokens: JsonField) = apply { + this.completionTokens = completionTokens + } + + /** + * A unix timestamp recording when the section of code which produced the experiment + * event finished + */ + fun end(end: Double?) = end(JsonField.ofNullable(end)) + + /** + * Alias for [Builder.end]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun end(end: Double) = end(end as Double?) + + /** Alias for calling [Builder.end] with `end.orElse(null)`. */ + fun end(end: Optional) = end(end.getOrNull()) + + /** + * Sets [Builder.end] to an arbitrary JSON value. + * + * You should usually call [Builder.end] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun end(end: JsonField) = apply { this.end = end } + + /** + * The number of tokens in the prompt used to generate the experiment event (only set if + * this is an LLM span) + */ + fun promptTokens(promptTokens: Long?) = promptTokens(JsonField.ofNullable(promptTokens)) + + /** + * Alias for [Builder.promptTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun promptTokens(promptTokens: Long) = promptTokens(promptTokens as Long?) + + /** Alias for calling [Builder.promptTokens] with `promptTokens.orElse(null)`. */ + fun promptTokens(promptTokens: Optional) = promptTokens(promptTokens.getOrNull()) + + /** + * Sets [Builder.promptTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.promptTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptTokens(promptTokens: JsonField) = apply { + this.promptTokens = promptTokens + } + + /** + * A unix timestamp recording when the section of code which produced the experiment + * event started + */ + fun start(start: Double?) = start(JsonField.ofNullable(start)) + + /** + * Alias for [Builder.start]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun start(start: Double) = start(start as Double?) + + /** Alias for calling [Builder.start] with `start.orElse(null)`. */ + fun start(start: Optional) = start(start.getOrNull()) + + /** + * Sets [Builder.start] to an arbitrary JSON value. + * + * You should usually call [Builder.start] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun start(start: JsonField) = apply { this.start = start } + + /** The total number of tokens in the input and output of the experiment event. */ + fun tokens(tokens: Long?) = tokens(JsonField.ofNullable(tokens)) + + /** + * Alias for [Builder.tokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun tokens(tokens: Long) = tokens(tokens as Long?) + + /** Alias for calling [Builder.tokens] with `tokens.orElse(null)`. */ + fun tokens(tokens: Optional) = tokens(tokens.getOrNull()) + + /** + * Sets [Builder.tokens] to an arbitrary JSON value. + * + * You should usually call [Builder.tokens] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tokens(tokens: JsonField) = apply { this.tokens = tokens } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metrics]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metrics = + Metrics( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + 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 + } + + return other is Metrics && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + completionTokens == other.completionTokens && + end == other.end && + promptTokens == other.promptTokens && + start == other.start && + tokens == other.tokens && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metrics{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, completionTokens=$completionTokens, end=$end, promptTokens=$promptTokens, start=$start, tokens=$tokens, additionalProperties=$additionalProperties}" + } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare experiments + */ + class Scores + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Scores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scores: Scores) = apply { + additionalProperties = scores.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 [Scores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Scores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Scores{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsertExperimentEvent && + id == other.id && + _isMerge == other._isMerge && + _mergePaths == other._mergePaths && + _objectDelete == other._objectDelete && + _parentId == other._parentId && + context == other.context && + created == other.created && + error == other.error && + expected == other.expected && + input == other.input && + metadata == other.metadata && + metrics == other.metrics && + origin == other.origin && + output == other.output && + rootSpanId == other.rootSpanId && + scores == other.scores && + spanAttributes == other.spanAttributes && + spanId == other.spanId && + spanParents == other.spanParents && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _isMerge, + _mergePaths, + _objectDelete, + _parentId, + context, + created, + error, + expected, + input, + metadata, + metrics, + origin, + output, + rootSpanId, + scores, + spanAttributes, + spanId, + spanParents, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InsertExperimentEvent{id=$id, _isMerge=$_isMerge, _mergePaths=$_mergePaths, _objectDelete=$_objectDelete, _parentId=$_parentId, context=$context, created=$created, error=$error, expected=$expected, input=$input, metadata=$metadata, metrics=$metrics, origin=$origin, output=$output, rootSpanId=$rootSpanId, scores=$scores, spanAttributes=$spanAttributes, spanId=$spanId, spanParents=$spanParents, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..15a2d806 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/InsertProjectLogsEvent.kt @@ -0,0 +1,2124 @@ +// 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.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 + +/** A project logs event */ +class InsertProjectLogsEvent +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun id(): Optional = id.getOptional("id") + + /** + * The `_is_merge` field controls how the row is merged with any existing row with the same id + * in the DB. By default (or when set to `false`), the existing row is completely replaced by + * the new row. When set to `true`, the new row is deep-merged into the existing row, if one is + * found. If no existing row is found, the new row is inserted as is. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, "b": + * 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": 11, "c": + * 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": 20}}`. If we + * replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be + * `{"id": "foo", "input": {"b": 11, "c": 20}}` + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _isMerge(): Optional = _isMerge.getOptional("_is_merge") + + /** + * The `_merge_paths` field allows controlling the depth of the merge, when `_is_merge=true`. + * `_merge_paths` is a list of paths, where each path is a list of field names. The deep merge + * will not descend below any of the specified merge paths. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": {"b": 10}, + * "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as `{"_is_merge": true, + * "_merge_paths": [["input", "a"], ["output"]], "input": {"a": {"q": 30}, "c": {"e": 30}, + * "bar": "baz"}, "output": {"d": 40}}`, the new row will be `{"id": "foo": "input": {"a": {"q": + * 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, "output": {"d": 40}}`. In this case, due to the + * merge paths, we have replaced `input.a` and `output`, but have still deep-merged `input` and + * `input.c`. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _mergePaths(): Optional>> = _mergePaths.getOptional("_merge_paths") + + /** + * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events will not + * show up in subsequent fetches for this project logs + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _objectDelete(): Optional = _objectDelete.getOptional("_object_delete") + + /** + * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for + * `_parent_id` will be dropped in a future version of Braintrust. Log `span_id`, + * `root_span_id`, and `span_parents` explicitly instead. + * + * Use the `_parent_id` field to create this row as a subspan of an existing row. Tracking + * hierarchical relationships are important for tracing (see the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details). + * + * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", + * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the parent + * row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": "What comes after + * foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root span row + * `"abc"` will show up in the summary view. You can view the full trace hierarchy (in this + * case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun _parentId(): Optional = _parentId.getOptional("_parent_id") + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun context(): Optional = context.getOptional("context") + + /** + * The timestamp 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 created(): Optional = created.getOptional("created") + + /** The error that occurred, if any. */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does not + * compare `output` to `expected` for you, since there are so many different ways to do that + * correctly. Instead, these values are just used to help you navigate while digging into + * analyses. However, we may later use these values to re-score outputs or fine-tune your + * models. + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** The arguments that uniquely define a user input (an arbitrary, JSON serializable object). */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonValue = input + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + * + * @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") + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * project logs event. Use "start" and "end" to track the time span over which the project logs + * event was produced + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metrics(): Optional = metrics.getOptional("metrics") + + /** + * Indicates the event was copied from another object. + * + * @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 output of your application, including post-processing (an arbitrary, JSON serializable + * object), that allows you to determine whether the result is correct or not. For example, in + * an app that generates SQL queries, the `output` should be the _result_ of the SQL query + * generated by the model, not the query itself, because there may be multiple valid queries + * that answer a single question. + */ + @JsonProperty("output") @ExcludeMissing fun _output(): JsonValue = output + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare logs. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scores(): Optional = scores.getOptional("scores") + + /** + * Human-identifying attributes of the span, such as name, type, etc. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanAttributes(): Optional = spanAttributes.getOptional("span_attributes") + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanId(): Optional = spanId.getOptional("span_id") + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, and + * the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": + * 0.33}}`. We can create a sub-span of the parent row by logging `{"id": "llm_call", "span_id": + * "span1", "root_span_id": "root_span0", "span_parents": ["span0"], "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root + * span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in + * this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanParents(): Optional> = spanParents.getOptional("span_parents") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_isMerge]. + * + * Unlike [_isMerge], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge(): JsonField = _isMerge + + /** + * Returns the raw JSON value of [_mergePaths]. + * + * Unlike [_mergePaths], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_merge_paths") + @ExcludeMissing + fun __mergePaths(): JsonField>> = _mergePaths + + /** + * Returns the raw JSON value of [_objectDelete]. + * + * Unlike [_objectDelete], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_object_delete") + @ExcludeMissing + fun __objectDelete(): JsonField = _objectDelete + + /** + * Returns the raw JSON value of [_parentId]. + * + * Unlike [_parentId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_parent_id") @ExcludeMissing fun __parentId(): JsonField = _parentId + + /** + * Returns the raw JSON value of [context]. + * + * Unlike [context], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("context") @ExcludeMissing fun _context(): JsonField = context + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [metrics]. + * + * Unlike [metrics], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metrics") @ExcludeMissing fun _metrics(): JsonField = metrics + + /** + * 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 + + /** + * Returns the raw JSON value of [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId(): JsonField = rootSpanId + + /** + * 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 + + /** + * Returns the raw JSON value of [spanAttributes]. + * + * Unlike [spanAttributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_attributes") + @ExcludeMissing + fun _spanAttributes(): JsonField = spanAttributes + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + + /** + * Returns the raw JSON value of [spanParents]. + * + * Unlike [spanParents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_parents") + @ExcludeMissing + fun _spanParents(): JsonField> = spanParents + + /** + * 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 [InsertProjectLogsEvent]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsertProjectLogsEvent]. */ + class Builder internal constructor() { + + private var id: JsonField = JsonMissing.of() + private var _isMerge: JsonField = JsonMissing.of() + private var _mergePaths: JsonField>>? = null + private var _objectDelete: JsonField = JsonMissing.of() + private var _parentId: JsonField = JsonMissing.of() + private var context: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var error: JsonValue = JsonMissing.of() + private var expected: JsonValue = JsonMissing.of() + private var input: JsonValue = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var metrics: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var output: JsonValue = JsonMissing.of() + private var rootSpanId: JsonField = JsonMissing.of() + private var scores: JsonField = JsonMissing.of() + private var spanAttributes: JsonField = JsonMissing.of() + private var spanId: JsonField = JsonMissing.of() + private var spanParents: JsonField>? = null + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(insertProjectLogsEvent: InsertProjectLogsEvent) = apply { + id = insertProjectLogsEvent.id + _isMerge = insertProjectLogsEvent._isMerge + _mergePaths = insertProjectLogsEvent._mergePaths.map { it.toMutableList() } + _objectDelete = insertProjectLogsEvent._objectDelete + _parentId = insertProjectLogsEvent._parentId + context = insertProjectLogsEvent.context + created = insertProjectLogsEvent.created + error = insertProjectLogsEvent.error + expected = insertProjectLogsEvent.expected + input = insertProjectLogsEvent.input + metadata = insertProjectLogsEvent.metadata + metrics = insertProjectLogsEvent.metrics + origin = insertProjectLogsEvent.origin + output = insertProjectLogsEvent.output + rootSpanId = insertProjectLogsEvent.rootSpanId + scores = insertProjectLogsEvent.scores + spanAttributes = insertProjectLogsEvent.spanAttributes + spanId = insertProjectLogsEvent.spanId + spanParents = insertProjectLogsEvent.spanParents.map { it.toMutableList() } + tags = insertProjectLogsEvent.tags.map { it.toMutableList() } + additionalProperties = insertProjectLogsEvent.additionalProperties.toMutableMap() + } + + /** + * A unique identifier for the project logs event. If you don't provide one, BrainTrust will + * generate one for you + */ + fun id(id: String?) = id(JsonField.ofNullable(id)) + + /** Alias for calling [Builder.id] with `id.orElse(null)`. */ + fun id(id: Optional) = id(id.getOrNull()) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The `_is_merge` field controls how the row is merged with any existing row with the same + * id in the DB. By default (or when set to `false`), the existing row is completely + * replaced by the new row. When set to `true`, the new row is deep-merged into the existing + * row, if one is found. If no existing row is found, the new row is inserted as is. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, "b": + * 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": 11, "c": + * 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": 20}}`. If we + * replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be + * `{"id": "foo", "input": {"b": 11, "c": 20}}` + */ + fun _isMerge(_isMerge: Boolean?) = _isMerge(JsonField.ofNullable(_isMerge)) + + /** + * Alias for [Builder._isMerge]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun _isMerge(_isMerge: Boolean) = _isMerge(_isMerge as Boolean?) + + /** Alias for calling [Builder._isMerge] with `_isMerge.orElse(null)`. */ + fun _isMerge(_isMerge: Optional) = _isMerge(_isMerge.getOrNull()) + + /** + * Sets [Builder._isMerge] to an arbitrary JSON value. + * + * You should usually call [Builder._isMerge] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } + + /** + * The `_merge_paths` field allows controlling the depth of the merge, when + * `_is_merge=true`. `_merge_paths` is a list of paths, where each path is a list of field + * names. The deep merge will not descend below any of the specified merge paths. + * + * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": {"b": + * 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as `{"_is_merge": + * true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": {"q": 30}, "c": {"e": + * 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be `{"id": "foo": "input": + * {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, "output": {"d": 40}}`. In this + * case, due to the merge paths, we have replaced `input.a` and `output`, but have still + * deep-merged `input` and `input.c`. + */ + fun _mergePaths(_mergePaths: List>?) = + _mergePaths(JsonField.ofNullable(_mergePaths)) + + /** Alias for calling [Builder._mergePaths] with `_mergePaths.orElse(null)`. */ + fun _mergePaths(_mergePaths: Optional>>) = + _mergePaths(_mergePaths.getOrNull()) + + /** + * Sets [Builder._mergePaths] to an arbitrary JSON value. + * + * You should usually call [Builder._mergePaths] with a well-typed `List>` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun _mergePaths(_mergePaths: JsonField>>) = apply { + this._mergePaths = _mergePaths.map { it.toMutableList() } + } + + /** + * Adds a single [List] to [_mergePaths]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMergePath(mergePath: List) = apply { + _mergePaths = + (_mergePaths ?: JsonField.of(mutableListOf())).also { + checkKnown("_mergePaths", it).add(mergePath) + } + } + + /** + * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events will + * not show up in subsequent fetches for this project logs + */ + fun _objectDelete(_objectDelete: Boolean?) = + _objectDelete(JsonField.ofNullable(_objectDelete)) + + /** + * Alias for [Builder._objectDelete]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun _objectDelete(_objectDelete: Boolean) = _objectDelete(_objectDelete as Boolean?) + + /** Alias for calling [Builder._objectDelete] with `_objectDelete.orElse(null)`. */ + fun _objectDelete(_objectDelete: Optional) = + _objectDelete(_objectDelete.getOrNull()) + + /** + * Sets [Builder._objectDelete] to an arbitrary JSON value. + * + * You should usually call [Builder._objectDelete] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun _objectDelete(_objectDelete: JsonField) = apply { + this._objectDelete = _objectDelete + } + + /** + * DEPRECATED: The `_parent_id` field is deprecated and should not be used. Support for + * `_parent_id` will be dropped in a future version of Braintrust. Log `span_id`, + * `root_span_id`, and `span_parents` explicitly instead. + * + * Use the `_parent_id` field to create this row as a subspan of an existing row. Tracking + * hierarchical relationships are important for tracing (see the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details). + * + * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", + * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the + * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": "What + * comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the + * root span row `"abc"` will show up in the summary view. You can view the full trace + * hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun _parentId(_parentId: String?) = _parentId(JsonField.ofNullable(_parentId)) + + /** Alias for calling [Builder._parentId] with `_parentId.orElse(null)`. */ + fun _parentId(_parentId: Optional) = _parentId(_parentId.getOrNull()) + + /** + * Sets [Builder._parentId] to an arbitrary JSON value. + * + * You should usually call [Builder._parentId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun _parentId(_parentId: JsonField) = apply { this._parentId = _parentId } + + /** + * 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 + */ + fun context(context: Context?) = context(JsonField.ofNullable(context)) + + /** Alias for calling [Builder.context] with `context.orElse(null)`. */ + fun context(context: Optional) = context(context.getOrNull()) + + /** + * Sets [Builder.context] to an arbitrary JSON value. + * + * You should usually call [Builder.context] with a well-typed [Context] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun context(context: JsonField) = apply { this.context = context } + + /** The timestamp the project logs event was created */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** The error that occurred, if any. */ + fun error(error: JsonValue) = apply { this.error = error } + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does + * not compare `output` to `expected` for you, since there are so many different ways to do + * that correctly. Instead, these values are just used to help you navigate while digging + * into analyses. However, we may later use these values to re-score outputs or fine-tune + * your models. + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * The arguments that uniquely define a user input (an arbitrary, JSON serializable object). + */ + fun input(input: JsonValue) = apply { this.input = input } + + /** + * 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 example, you could log the `prompt`, example's `id`, or anything else that would be + * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, + * but its keys must be strings + */ + 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 } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * project logs event. Use "start" and "end" to track the time span over which the project + * logs event was produced + */ + fun metrics(metrics: Metrics?) = metrics(JsonField.ofNullable(metrics)) + + /** Alias for calling [Builder.metrics] with `metrics.orElse(null)`. */ + fun metrics(metrics: Optional) = metrics(metrics.getOrNull()) + + /** + * Sets [Builder.metrics] to an arbitrary JSON value. + * + * You should usually call [Builder.metrics] with a well-typed [Metrics] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun metrics(metrics: JsonField) = apply { this.metrics = metrics } + + /** Indicates the event was copied from another object. */ + fun origin(origin: ObjectReference?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [ObjectReference] 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 } + + /** + * The output of your application, including post-processing (an arbitrary, JSON + * serializable object), that allows you to determine whether the result is correct or not. + * For example, in an app that generates SQL queries, the `output` should be the _result_ of + * the SQL query generated by the model, not the query itself, because there may be multiple + * valid queries that answer a single question. + */ + fun output(output: JsonValue) = apply { this.output = output } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun rootSpanId(rootSpanId: String?) = rootSpanId(JsonField.ofNullable(rootSpanId)) + + /** Alias for calling [Builder.rootSpanId] with `rootSpanId.orElse(null)`. */ + fun rootSpanId(rootSpanId: Optional) = rootSpanId(rootSpanId.getOrNull()) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a + * variety of signals that help you determine how accurate the outputs are compared to what + * you expect and diagnose failures. For example, a summarization app might have one score + * that tells you how accurate the summary is, and another that measures the word similarity + * between the generated and grouth truth summary. The word similarity score could help you + * determine whether the summarization was covering similar concepts or not. You can use + * these scores to help you sort, filter, and compare logs. + */ + fun scores(scores: Scores?) = scores(JsonField.ofNullable(scores)) + + /** Alias for calling [Builder.scores] with `scores.orElse(null)`. */ + fun scores(scores: Optional) = scores(scores.getOrNull()) + + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed [Scores] 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 } + + /** Human-identifying attributes of the span, such as name, type, etc. */ + fun spanAttributes(spanAttributes: SpanAttributes?) = + spanAttributes(JsonField.ofNullable(spanAttributes)) + + /** Alias for calling [Builder.spanAttributes] with `spanAttributes.orElse(null)`. */ + fun spanAttributes(spanAttributes: Optional) = + spanAttributes(spanAttributes.getOrNull()) + + /** + * Sets [Builder.spanAttributes] to an arbitrary JSON value. + * + * You should usually call [Builder.spanAttributes] with a well-typed [SpanAttributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanAttributes(spanAttributes: JsonField) = apply { + this.spanAttributes = spanAttributes + } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun spanId(spanId: String?) = spanId(JsonField.ofNullable(spanId)) + + /** Alias for calling [Builder.spanId] with `spanId.orElse(null)`. */ + fun spanId(spanId: Optional) = spanId(spanId.getOrNull()) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + /** + * Use `span_id`, `root_span_id`, and `span_parents` instead of `_parent_id`, which is now + * deprecated. The span_id is a unique identifier describing the row's place in the a trace, + * and the root_span_id is a unique identifier for the whole trace. See the + * [guide](https://www.braintrust.dev/docs/guides/tracing) for full details. + * + * For example, say we have logged a row `{"id": "abc", "span_id": "span0", "root_span_id": + * "root_span0", "input": "foo", "output": "bar", "expected": "boo", "scores": + * {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"id": + * "llm_call", "span_id": "span1", "root_span_id": "root_span0", "span_parents": ["span0"], + * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": + * 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You + * can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the + * "abc" row. + * + * If the row is being merged into an existing row, this field will be ignored. + */ + fun spanParents(spanParents: List?) = spanParents(JsonField.ofNullable(spanParents)) + + /** Alias for calling [Builder.spanParents] with `spanParents.orElse(null)`. */ + fun spanParents(spanParents: Optional>) = spanParents(spanParents.getOrNull()) + + /** + * Sets [Builder.spanParents] to an arbitrary JSON value. + * + * You should usually call [Builder.spanParents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanParents(spanParents: JsonField>) = apply { + this.spanParents = spanParents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [spanParents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSpanParent(spanParent: String) = apply { + spanParents = + (spanParents ?: JsonField.of(mutableListOf())).also { + checkKnown("spanParents", it).add(spanParent) + } + } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InsertProjectLogsEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InsertProjectLogsEvent = + InsertProjectLogsEvent( + id, + _isMerge, + (_mergePaths ?: JsonMissing.of()).map { it.toImmutable() }, + _objectDelete, + _parentId, + context, + created, + error, + expected, + input, + metadata, + metrics, + origin, + output, + rootSpanId, + scores, + spanAttributes, + spanId, + (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, + (tags ?: JsonMissing.of()).map { it.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 + */ + class Context + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = callerFilename.getOptional("caller_filename") + + /** + * The function in code which created the project logs event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun callerFunctionname(): Optional = + callerFunctionname.getOptional("caller_functionname") + + /** + * Line of 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 callerLineno(): Optional = callerLineno.getOptional("caller_lineno") + + /** + * Returns the raw JSON value of [callerFilename]. + * + * Unlike [callerFilename], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_filename") + @ExcludeMissing + fun _callerFilename(): JsonField = callerFilename + + /** + * Returns the raw JSON value of [callerFunctionname]. + * + * Unlike [callerFunctionname], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonField = callerFunctionname + + /** + * Returns the raw JSON value of [callerLineno]. + * + * Unlike [callerLineno], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_lineno") + @ExcludeMissing + fun _callerLineno(): JsonField = callerLineno + + @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 [Context]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Context]. */ + class Builder internal constructor() { + + private var callerFilename: JsonField = JsonMissing.of() + private var callerFunctionname: JsonField = JsonMissing.of() + private var callerLineno: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(context: Context) = apply { + callerFilename = context.callerFilename + callerFunctionname = context.callerFunctionname + callerLineno = context.callerLineno + additionalProperties = context.additionalProperties.toMutableMap() + } + + /** Name of the file in code where the project logs event was created */ + fun callerFilename(callerFilename: String?) = + callerFilename(JsonField.ofNullable(callerFilename)) + + /** Alias for calling [Builder.callerFilename] with `callerFilename.orElse(null)`. */ + fun callerFilename(callerFilename: Optional) = + callerFilename(callerFilename.getOrNull()) + + /** + * Sets [Builder.callerFilename] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFilename] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFilename(callerFilename: JsonField) = apply { + this.callerFilename = callerFilename + } + + /** The function in code which created the project logs event */ + fun callerFunctionname(callerFunctionname: String?) = + callerFunctionname(JsonField.ofNullable(callerFunctionname)) + + /** + * Alias for calling [Builder.callerFunctionname] with + * `callerFunctionname.orElse(null)`. + */ + fun callerFunctionname(callerFunctionname: Optional) = + callerFunctionname(callerFunctionname.getOrNull()) + + /** + * Sets [Builder.callerFunctionname] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFunctionname] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFunctionname(callerFunctionname: JsonField) = apply { + this.callerFunctionname = callerFunctionname + } + + /** Line of code where the project logs event was created */ + fun callerLineno(callerLineno: Long?) = callerLineno(JsonField.ofNullable(callerLineno)) + + /** + * Alias for [Builder.callerLineno]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun callerLineno(callerLineno: Long) = callerLineno(callerLineno as Long?) + + /** Alias for calling [Builder.callerLineno] with `callerLineno.orElse(null)`. */ + fun callerLineno(callerLineno: Optional) = callerLineno(callerLineno.getOrNull()) + + /** + * Sets [Builder.callerLineno] to an arbitrary JSON value. + * + * You should usually call [Builder.callerLineno] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerLineno(callerLineno: JsonField) = apply { + this.callerLineno = callerLineno + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Context]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Context = + Context( + callerFilename, + callerFunctionname, + callerLineno, + 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 + } + + return other is Context && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(callerFilename, callerFunctionname, callerLineno, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Context{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" + } + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + */ + class Metadata + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = model.getOptional("model") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + @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 [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var model: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + model = metadata.model + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + /** The model used for this example */ + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(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 + } + + return other is Metadata && + model == other.model && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(model, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{model=$model, additionalProperties=$additionalProperties}" + } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * project logs event. Use "start" and "end" to track the time span over which the project logs + * event was produced + */ + class Metrics + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + fun _callerFilename(): JsonValue = callerFilename + + /** This metric is deprecated */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonValue = callerFunctionname + + /** This metric is deprecated */ + @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno(): JsonValue = callerLineno + + /** + * The number of tokens in the completion generated by the model (only set if this is an LLM + * span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun completionTokens(): Optional = completionTokens.getOptional("completion_tokens") + + /** + * A unix timestamp recording when the section of code which produced the project logs event + * finished + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun end(): Optional = end.getOptional("end") + + /** + * The number of tokens in the prompt used to generate the project logs event (only set if + * this is an LLM span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptTokens(): Optional = promptTokens.getOptional("prompt_tokens") + + /** + * A unix timestamp recording when the section of code which produced the project logs event + * started + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun start(): Optional = start.getOptional("start") + + /** + * The total number of tokens in the input and output of the project logs event. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tokens(): Optional = tokens.getOptional("tokens") + + /** + * Returns the raw JSON value of [completionTokens]. + * + * Unlike [completionTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("completion_tokens") + @ExcludeMissing + fun _completionTokens(): JsonField = completionTokens + + /** + * Returns the raw JSON value of [end]. + * + * Unlike [end], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end + + /** + * Returns the raw JSON value of [promptTokens]. + * + * Unlike [promptTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("prompt_tokens") + @ExcludeMissing + fun _promptTokens(): JsonField = promptTokens + + /** + * Returns the raw JSON value of [start]. + * + * Unlike [start], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start + + /** + * Returns the raw JSON value of [tokens]. + * + * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metrics]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metrics]. */ + class Builder internal constructor() { + + private var callerFilename: JsonValue = JsonMissing.of() + private var callerFunctionname: JsonValue = JsonMissing.of() + private var callerLineno: JsonValue = JsonMissing.of() + private var completionTokens: JsonField = JsonMissing.of() + private var end: JsonField = JsonMissing.of() + private var promptTokens: JsonField = JsonMissing.of() + private var start: JsonField = JsonMissing.of() + private var tokens: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metrics: Metrics) = apply { + callerFilename = metrics.callerFilename + callerFunctionname = metrics.callerFunctionname + callerLineno = metrics.callerLineno + completionTokens = metrics.completionTokens + end = metrics.end + promptTokens = metrics.promptTokens + start = metrics.start + tokens = metrics.tokens + additionalProperties = metrics.additionalProperties.toMutableMap() + } + + /** This metric is deprecated */ + fun callerFilename(callerFilename: JsonValue) = apply { + this.callerFilename = callerFilename + } + + /** This metric is deprecated */ + fun callerFunctionname(callerFunctionname: JsonValue) = apply { + this.callerFunctionname = callerFunctionname + } + + /** This metric is deprecated */ + fun callerLineno(callerLineno: JsonValue) = apply { this.callerLineno = callerLineno } + + /** + * The number of tokens in the completion generated by the model (only set if this is an + * LLM span) + */ + fun completionTokens(completionTokens: Long?) = + completionTokens(JsonField.ofNullable(completionTokens)) + + /** + * Alias for [Builder.completionTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun completionTokens(completionTokens: Long) = + completionTokens(completionTokens as Long?) + + /** + * Alias for calling [Builder.completionTokens] with `completionTokens.orElse(null)`. + */ + fun completionTokens(completionTokens: Optional) = + completionTokens(completionTokens.getOrNull()) + + /** + * Sets [Builder.completionTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.completionTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun completionTokens(completionTokens: JsonField) = apply { + this.completionTokens = completionTokens + } + + /** + * A unix timestamp recording when the section of code which produced the project logs + * event finished + */ + fun end(end: Double?) = end(JsonField.ofNullable(end)) + + /** + * Alias for [Builder.end]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun end(end: Double) = end(end as Double?) + + /** Alias for calling [Builder.end] with `end.orElse(null)`. */ + fun end(end: Optional) = end(end.getOrNull()) + + /** + * Sets [Builder.end] to an arbitrary JSON value. + * + * You should usually call [Builder.end] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun end(end: JsonField) = apply { this.end = end } + + /** + * The number of tokens in the prompt used to generate the project logs event (only set + * if this is an LLM span) + */ + fun promptTokens(promptTokens: Long?) = promptTokens(JsonField.ofNullable(promptTokens)) + + /** + * Alias for [Builder.promptTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun promptTokens(promptTokens: Long) = promptTokens(promptTokens as Long?) + + /** Alias for calling [Builder.promptTokens] with `promptTokens.orElse(null)`. */ + fun promptTokens(promptTokens: Optional) = promptTokens(promptTokens.getOrNull()) + + /** + * Sets [Builder.promptTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.promptTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptTokens(promptTokens: JsonField) = apply { + this.promptTokens = promptTokens + } + + /** + * A unix timestamp recording when the section of code which produced the project logs + * event started + */ + fun start(start: Double?) = start(JsonField.ofNullable(start)) + + /** + * Alias for [Builder.start]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun start(start: Double) = start(start as Double?) + + /** Alias for calling [Builder.start] with `start.orElse(null)`. */ + fun start(start: Optional) = start(start.getOrNull()) + + /** + * Sets [Builder.start] to an arbitrary JSON value. + * + * You should usually call [Builder.start] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun start(start: JsonField) = apply { this.start = start } + + /** The total number of tokens in the input and output of the project logs event. */ + fun tokens(tokens: Long?) = tokens(JsonField.ofNullable(tokens)) + + /** + * Alias for [Builder.tokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun tokens(tokens: Long) = tokens(tokens as Long?) + + /** Alias for calling [Builder.tokens] with `tokens.orElse(null)`. */ + fun tokens(tokens: Optional) = tokens(tokens.getOrNull()) + + /** + * Sets [Builder.tokens] to an arbitrary JSON value. + * + * You should usually call [Builder.tokens] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tokens(tokens: JsonField) = apply { this.tokens = tokens } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metrics]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metrics = + Metrics( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + 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 + } + + return other is Metrics && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + completionTokens == other.completionTokens && + end == other.end && + promptTokens == other.promptTokens && + start == other.start && + tokens == other.tokens && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metrics{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, completionTokens=$completionTokens, end=$end, promptTokens=$promptTokens, start=$start, tokens=$tokens, additionalProperties=$additionalProperties}" + } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare logs. + */ + class Scores + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Scores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scores: Scores) = apply { + additionalProperties = scores.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 [Scores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Scores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Scores{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsertProjectLogsEvent && + id == other.id && + _isMerge == other._isMerge && + _mergePaths == other._mergePaths && + _objectDelete == other._objectDelete && + _parentId == other._parentId && + context == other.context && + created == other.created && + error == other.error && + expected == other.expected && + input == other.input && + metadata == other.metadata && + metrics == other.metrics && + origin == other.origin && + output == other.output && + rootSpanId == other.rootSpanId && + scores == other.scores && + spanAttributes == other.spanAttributes && + spanId == other.spanId && + spanParents == other.spanParents && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _isMerge, + _mergePaths, + _objectDelete, + _parentId, + context, + created, + error, + expected, + input, + metadata, + metrics, + origin, + output, + rootSpanId, + scores, + spanAttributes, + spanId, + spanParents, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InsertProjectLogsEvent{id=$id, _isMerge=$_isMerge, _mergePaths=$_mergePaths, _objectDelete=$_objectDelete, _parentId=$_parentId, context=$context, created=$created, error=$error, expected=$expected, input=$input, metadata=$metadata, metrics=$metrics, origin=$origin, output=$output, rootSpanId=$rootSpanId, scores=$scores, spanAttributes=$spanAttributes, spanId=$spanId, spanParents=$spanParents, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..c4631b77 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/MetricSummary.kt @@ -0,0 +1,365 @@ +// 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.checkRequired +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 */ +class MetricSummary +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 improvements(): Long = improvements.getRequired("improvements") + + /** + * Average metric across all examples + * + * @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 metric(): Double = metric.getRequired("metric") + + /** + * Name of the metric + * + * @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") + + /** + * Number of regressions in the metric + * + * @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 regressions(): Long = regressions.getRequired("regressions") + + /** + * Unit label for the metric + * + * @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 unit(): String = unit.getRequired("unit") + + /** + * Difference in metric between the current and comparison experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun diff(): Optional = diff.getOptional("diff") + + /** + * Returns the raw JSON value of [improvements]. + * + * Unlike [improvements], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("improvements") + @ExcludeMissing + fun _improvements(): JsonField = improvements + + /** + * Returns the raw JSON value of [metric]. + * + * Unlike [metric], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metric") @ExcludeMissing fun _metric(): JsonField = metric + + /** + * 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 [regressions]. + * + * Unlike [regressions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("regressions") @ExcludeMissing fun _regressions(): JsonField = regressions + + /** + * Returns the raw JSON value of [unit]. + * + * Unlike [unit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("unit") @ExcludeMissing fun _unit(): JsonField = unit + + /** + * Returns the raw JSON value of [diff]. + * + * Unlike [diff], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("diff") @ExcludeMissing fun _diff(): JsonField = diff + + @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 [MetricSummary]. + * + * The following fields are required: + * ```java + * .improvements() + * .metric() + * .name() + * .regressions() + * .unit() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [MetricSummary]. */ + class Builder internal constructor() { + + private var improvements: JsonField? = null + private var metric: JsonField? = null + private var name: JsonField? = null + private var regressions: JsonField? = null + private var unit: JsonField? = null + private var diff: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metricSummary: MetricSummary) = apply { + improvements = metricSummary.improvements + metric = metricSummary.metric + name = metricSummary.name + regressions = metricSummary.regressions + unit = metricSummary.unit + diff = metricSummary.diff + additionalProperties = metricSummary.additionalProperties.toMutableMap() + } + + /** Number of improvements in the metric */ + fun improvements(improvements: Long) = improvements(JsonField.of(improvements)) + + /** + * Sets [Builder.improvements] to an arbitrary JSON value. + * + * You should usually call [Builder.improvements] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun improvements(improvements: JsonField) = apply { this.improvements = improvements } + + /** Average metric across all examples */ + fun metric(metric: Double) = metric(JsonField.of(metric)) + + /** + * Sets [Builder.metric] to an arbitrary JSON value. + * + * You should usually call [Builder.metric] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun metric(metric: JsonField) = apply { this.metric = metric } + + /** Name of the metric */ + 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 } + + /** Number of regressions in the metric */ + fun regressions(regressions: Long) = regressions(JsonField.of(regressions)) + + /** + * Sets [Builder.regressions] to an arbitrary JSON value. + * + * You should usually call [Builder.regressions] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun regressions(regressions: JsonField) = apply { this.regressions = regressions } + + /** Unit label for the metric */ + fun unit(unit: String) = unit(JsonField.of(unit)) + + /** + * Sets [Builder.unit] to an arbitrary JSON value. + * + * You should usually call [Builder.unit] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun unit(unit: JsonField) = apply { this.unit = unit } + + /** Difference in metric between the current and comparison experiment */ + fun diff(diff: Double) = diff(JsonField.of(diff)) + + /** + * Sets [Builder.diff] to an arbitrary JSON value. + * + * You should usually call [Builder.diff] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun diff(diff: JsonField) = apply { this.diff = diff } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [MetricSummary]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .improvements() + * .metric() + * .name() + * .regressions() + * .unit() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MetricSummary = + MetricSummary( + checkRequired("improvements", improvements), + checkRequired("metric", metric), + checkRequired("name", name), + checkRequired("regressions", regressions), + checkRequired("unit", unit), + diff, + 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 + } + + return other is MetricSummary && + improvements == other.improvements && + metric == other.metric && + name == other.name && + regressions == other.regressions && + unit == other.unit && + diff == other.diff && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(improvements, metric, name, regressions, unit, diff, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MetricSummary{improvements=$improvements, metric=$metric, name=$name, regressions=$regressions, unit=$unit, diff=$diff, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..dc51c408 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ObjectReference.kt @@ -0,0 +1,485 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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. */ +class ObjectReference +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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. + * + * @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 id(): String = id.getRequired("id") + + /** + * Transaction ID of the original event. + * + * @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 _xactId(): String = _xactId.getRequired("_xact_id") + + /** + * ID of the object the event is originating from. + * + * @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") + + /** + * Type of the object the event is originating from. + * + * @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 = objectType.getRequired("object_type") + + /** + * Created timestamp of the original event. Used to help sort in the UI + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_xactId]. + * + * Unlike [_xactId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_xact_id") @ExcludeMissing fun __xactId(): JsonField = _xactId + + /** + * 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 + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + @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 [ObjectReference]. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ObjectReference]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var _xactId: JsonField? = null + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(objectReference: ObjectReference) = apply { + id = objectReference.id + _xactId = objectReference._xactId + objectId = objectReference.objectId + objectType = objectReference.objectType + created = objectReference.created + additionalProperties = objectReference.additionalProperties.toMutableMap() + } + + /** ID of the original event. */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Transaction ID of the original event. */ + fun _xactId(_xactId: String) = _xactId(JsonField.of(_xactId)) + + /** + * Sets [Builder._xactId] to an arbitrary JSON value. + * + * You should usually call [Builder._xactId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } + + /** ID of the object the event is originating from. */ + 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 } + + /** Type of the object the event is originating from. */ + fun objectType(objectType: ObjectType) = objectType(JsonField.of(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 { this.objectType = objectType } + + /** Created timestamp of the original event. Used to help sort in the UI */ + fun created(created: String?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ObjectReference]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .objectId() + * .objectType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ObjectReference = + ObjectReference( + checkRequired("id", id), + checkRequired("_xactId", _xactId), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + created, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val DATASET = of("dataset") + + @JvmField val PROMPT = of("prompt") + + @JvmField val FUNCTION = of("function") + + @JvmField val PROMPT_SESSION = of("prompt_session") + + @JvmField val PROJECT_LOGS = of("project_logs") + + @JvmStatic fun of(value: String) = ObjectType(JsonField.of(value)) + } + + /** An enum containing [ObjectType]'s known values. */ + enum class Known { + EXPERIMENT, + DATASET, + PROMPT, + FUNCTION, + PROMPT_SESSION, + PROJECT_LOGS, + } + + /** + * An enum containing [ObjectType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ObjectType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + EXPERIMENT, + DATASET, + PROMPT, + FUNCTION, + PROMPT_SESSION, + PROJECT_LOGS, + /** + * An enum member indicating that [ObjectType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + EXPERIMENT -> Value.EXPERIMENT + DATASET -> Value.DATASET + PROMPT -> Value.PROMPT + FUNCTION -> Value.FUNCTION + PROMPT_SESSION -> Value.PROMPT_SESSION + PROJECT_LOGS -> Value.PROJECT_LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + EXPERIMENT -> Known.EXPERIMENT + DATASET -> Known.DATASET + PROMPT -> Known.PROMPT + FUNCTION -> Known.FUNCTION + PROMPT_SESSION -> Known.PROMPT_SESSION + PROJECT_LOGS -> Known.PROJECT_LOGS + else -> throw BraintrustInvalidDataException("Unknown ObjectType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ObjectType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ObjectReference && + id == other.id && + _xactId == other._xactId && + objectId == other.objectId && + objectType == other.objectType && + created == other.created && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, _xactId, objectId, objectType, created, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ObjectReference{id=$id, _xactId=$_xactId, objectId=$objectId, objectType=$objectType, created=$created, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..3e1905bb --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OnlineScoreConfig.kt @@ -0,0 +1,1185 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.allMaxBy +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.getOrThrow +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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class OnlineScoreConfig +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 samplingRate(): Double = samplingRate.getRequired("sampling_rate") + + /** + * The list of scorers to use for online scoring + * + * @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 scorers(): List = scorers.getRequired("scorers") + + /** + * Whether to trigger online scoring on the root span of each trace + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun applyToRootSpan(): Optional = applyToRootSpan.getOptional("apply_to_root_span") + + /** + * Trigger online scoring on any spans with a name in this list + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun applyToSpanNames(): Optional> = + applyToSpanNames.getOptional("apply_to_span_names") + + /** + * Returns the raw JSON value of [samplingRate]. + * + * Unlike [samplingRate], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("sampling_rate") + @ExcludeMissing + fun _samplingRate(): JsonField = samplingRate + + /** + * Returns the raw JSON value of [scorers]. + * + * Unlike [scorers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("scorers") @ExcludeMissing fun _scorers(): JsonField> = scorers + + /** + * Returns the raw JSON value of [applyToRootSpan]. + * + * Unlike [applyToRootSpan], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("apply_to_root_span") + @ExcludeMissing + fun _applyToRootSpan(): JsonField = applyToRootSpan + + /** + * Returns the raw JSON value of [applyToSpanNames]. + * + * Unlike [applyToSpanNames], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("apply_to_span_names") + @ExcludeMissing + fun _applyToSpanNames(): JsonField> = applyToSpanNames + + @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 [OnlineScoreConfig]. + * + * The following fields are required: + * ```java + * .samplingRate() + * .scorers() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OnlineScoreConfig]. */ + class Builder internal constructor() { + + private var samplingRate: JsonField? = null + private var scorers: JsonField>? = null + private var applyToRootSpan: JsonField = JsonMissing.of() + private var applyToSpanNames: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(onlineScoreConfig: OnlineScoreConfig) = apply { + samplingRate = onlineScoreConfig.samplingRate + scorers = onlineScoreConfig.scorers.map { it.toMutableList() } + applyToRootSpan = onlineScoreConfig.applyToRootSpan + applyToSpanNames = onlineScoreConfig.applyToSpanNames.map { it.toMutableList() } + additionalProperties = onlineScoreConfig.additionalProperties.toMutableMap() + } + + /** The sampling rate for online scoring */ + fun samplingRate(samplingRate: Double) = samplingRate(JsonField.of(samplingRate)) + + /** + * Sets [Builder.samplingRate] to an arbitrary JSON value. + * + * You should usually call [Builder.samplingRate] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun samplingRate(samplingRate: JsonField) = apply { + this.samplingRate = samplingRate + } + + /** The list of scorers to use for online scoring */ + fun scorers(scorers: List) = scorers(JsonField.of(scorers)) + + /** + * Sets [Builder.scorers] to an arbitrary JSON value. + * + * You should usually call [Builder.scorers] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun scorers(scorers: JsonField>) = apply { + this.scorers = scorers.map { it.toMutableList() } + } + + /** + * Adds a single [Scorer] to [scorers]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addScorer(scorer: Scorer) = apply { + scorers = + (scorers ?: JsonField.of(mutableListOf())).also { + checkKnown("scorers", it).add(scorer) + } + } + + /** Alias for calling [addScorer] with `Scorer.ofFunction(function)`. */ + fun addScorer(function: Scorer.Function) = addScorer(Scorer.ofFunction(function)) + + /** Alias for calling [addScorer] with `Scorer.ofGlobal(global)`. */ + fun addScorer(global: Scorer.Global) = addScorer(Scorer.ofGlobal(global)) + + /** Whether to trigger online scoring on the root span of each trace */ + fun applyToRootSpan(applyToRootSpan: Boolean?) = + applyToRootSpan(JsonField.ofNullable(applyToRootSpan)) + + /** + * Alias for [Builder.applyToRootSpan]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun applyToRootSpan(applyToRootSpan: Boolean) = applyToRootSpan(applyToRootSpan as Boolean?) + + /** Alias for calling [Builder.applyToRootSpan] with `applyToRootSpan.orElse(null)`. */ + fun applyToRootSpan(applyToRootSpan: Optional) = + applyToRootSpan(applyToRootSpan.getOrNull()) + + /** + * Sets [Builder.applyToRootSpan] to an arbitrary JSON value. + * + * You should usually call [Builder.applyToRootSpan] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun applyToRootSpan(applyToRootSpan: JsonField) = apply { + this.applyToRootSpan = applyToRootSpan + } + + /** Trigger online scoring on any spans with a name in this list */ + fun applyToSpanNames(applyToSpanNames: List?) = + applyToSpanNames(JsonField.ofNullable(applyToSpanNames)) + + /** Alias for calling [Builder.applyToSpanNames] with `applyToSpanNames.orElse(null)`. */ + fun applyToSpanNames(applyToSpanNames: Optional>) = + applyToSpanNames(applyToSpanNames.getOrNull()) + + /** + * Sets [Builder.applyToSpanNames] to an arbitrary JSON value. + * + * You should usually call [Builder.applyToSpanNames] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun applyToSpanNames(applyToSpanNames: JsonField>) = apply { + this.applyToSpanNames = applyToSpanNames.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [applyToSpanNames]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addApplyToSpanName(applyToSpanName: String) = apply { + applyToSpanNames = + (applyToSpanNames ?: JsonField.of(mutableListOf())).also { + checkKnown("applyToSpanNames", it).add(applyToSpanName) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [OnlineScoreConfig]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .samplingRate() + * .scorers() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): OnlineScoreConfig = + OnlineScoreConfig( + checkRequired("samplingRate", samplingRate), + checkRequired("scorers", scorers).map { it.toImmutable() }, + applyToRootSpan, + (applyToSpanNames ?: JsonMissing.of()).map { it.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 + private constructor( + private val function: Function? = null, + private val global: Global? = null, + private val _json: JsonValue? = null, + ) { + + fun function(): Optional = Optional.ofNullable(function) + + fun global(): Optional = Optional.ofNullable(global) + + fun isFunction(): Boolean = function != null + + fun isGlobal(): Boolean = global != null + + fun asFunction(): Function = function.getOrThrow("function") + + fun asGlobal(): Global = global.getOrThrow("global") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Scorer = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitFunction(function: Function) { + function.validate() + } + + override fun visitGlobal(global: Global) { + global.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 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 + } + + return other is Scorer && function == other.function && global == other.global + } + + override fun hashCode(): Int = Objects.hash(function, global) + + override fun toString(): String = + when { + function != null -> "Scorer{function=$function}" + global != null -> "Scorer{global=$global}" + _json != null -> "Scorer{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Scorer") + } + + companion object { + + @JvmStatic fun ofFunction(function: Function) = Scorer(function = function) + + @JvmStatic fun ofGlobal(global: Global) = Scorer(global = global) + } + + /** An interface that defines how to map each variant of [Scorer] to a value of type [T]. */ + interface Visitor { + + fun visitFunction(function: Function): T + + fun visitGlobal(global: Global): T + + /** + * Maps an unknown variant of [Scorer] to a value of type [T]. + * + * An instance of [Scorer] 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 Scorer: $json") + } + } + + internal class Deserializer : BaseDeserializer(Scorer::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Scorer { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Scorer::class) { + + override fun serialize( + value: Scorer, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.function != null -> generator.writeObject(value.function) + value.global != null -> generator.writeObject(value.global) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Scorer") + } + } + } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun id(): String = id.getRequired("id") + + /** + * @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") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + id = function.id + type = function.type + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("id", id), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FUNCTION, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + id == other.id && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{id=$id, type=$type, additionalProperties=$additionalProperties}" + } + + class Global + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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") + + /** + * 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 [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Global]. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Global]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(global: Global) = apply { + name = global.name + type = global.type + additionalProperties = global.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Global]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Global = + Global( + checkRequired("name", name), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GLOBAL = of("global") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + GLOBAL + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GLOBAL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GLOBAL -> Value.GLOBAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GLOBAL -> Known.GLOBAL + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Global && + name == other.name && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Global{name=$name, type=$type, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OnlineScoreConfig && + samplingRate == other.samplingRate && + scorers == other.scorers && + applyToRootSpan == other.applyToRootSpan && + applyToSpanNames == other.applyToSpanNames && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(samplingRate, scorers, applyToRootSpan, applyToSpanNames, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "OnlineScoreConfig{samplingRate=$samplingRate, scorers=$scorers, applyToRootSpan=$applyToRootSpan, applyToSpanNames=$applyToSpanNames, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..86b44aed --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Organization.kt @@ -0,0 +1,422 @@ +// 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.checkRequired +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 + +class Organization +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * Name of the organization + * + * @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") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiUrl(): Optional = apiUrl.getOptional("api_url") + + /** + * Date of organization creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 = 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 = 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 = realtimeUrl.getOptional("realtime_url") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [apiUrl]. + * + * Unlike [apiUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_url") @ExcludeMissing fun _apiUrl(): JsonField = apiUrl + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [isUniversalApi]. + * + * Unlike [isUniversalApi], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("is_universal_api") + @ExcludeMissing + fun _isUniversalApi(): JsonField = isUniversalApi + + /** + * 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 + + /** + * Returns the raw JSON value of [realtimeUrl]. + * + * Unlike [realtimeUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("realtime_url") + @ExcludeMissing + fun _realtimeUrl(): JsonField = realtimeUrl + + @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 [Organization]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Organization]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var apiUrl: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var isUniversalApi: JsonField = JsonMissing.of() + private var proxyUrl: JsonField = JsonMissing.of() + private var realtimeUrl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(organization: Organization) = apply { + id = organization.id + name = organization.name + apiUrl = organization.apiUrl + created = organization.created + isUniversalApi = organization.isUniversalApi + proxyUrl = organization.proxyUrl + realtimeUrl = organization.realtimeUrl + additionalProperties = organization.additionalProperties.toMutableMap() + } + + /** Unique identifier for the organization */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the organization */ + 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 apiUrl(apiUrl: String?) = apiUrl(JsonField.ofNullable(apiUrl)) + + /** Alias for calling [Builder.apiUrl] with `apiUrl.orElse(null)`. */ + fun apiUrl(apiUrl: Optional) = apiUrl(apiUrl.getOrNull()) + + /** + * 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 } + + /** Date of organization creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + fun isUniversalApi(isUniversalApi: Boolean?) = + isUniversalApi(JsonField.ofNullable(isUniversalApi)) + + /** + * Alias for [Builder.isUniversalApi]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isUniversalApi(isUniversalApi: Boolean) = isUniversalApi(isUniversalApi as Boolean?) + + /** Alias for calling [Builder.isUniversalApi] with `isUniversalApi.orElse(null)`. */ + fun isUniversalApi(isUniversalApi: Optional) = + isUniversalApi(isUniversalApi.getOrNull()) + + /** + * 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 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 removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Organization]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Organization = + Organization( + checkRequired("id", id), + checkRequired("name", name), + apiUrl, + created, + isUniversalApi, + proxyUrl, + realtimeUrl, + 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 + } + + return other is Organization && + id == other.id && + name == other.name && + apiUrl == other.apiUrl && + created == other.created && + isUniversalApi == other.isUniversalApi && + proxyUrl == other.proxyUrl && + realtimeUrl == other.realtimeUrl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + apiUrl, + created, + isUniversalApi, + proxyUrl, + realtimeUrl, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Organization{id=$id, name=$name, apiUrl=$apiUrl, created=$created, isUniversalApi=$isUniversalApi, proxyUrl=$proxyUrl, realtimeUrl=$realtimeUrl, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..cc9d76b9 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationDeleteParams.kt @@ -0,0 +1,238 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete an organization object by its id */ +class OrganizationDeleteParams +private constructor( + private val organizationId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** Organization id */ + fun organizationId(): Optional = Optional.ofNullable(organizationId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OrganizationDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [OrganizationDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationDeleteParams]. */ + class Builder internal constructor() { + + private var organizationId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(organizationDeleteParams: OrganizationDeleteParams) = apply { + organizationId = organizationDeleteParams.organizationId + additionalHeaders = organizationDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = organizationDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + organizationDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** Organization id */ + fun organizationId(organizationId: String?) = apply { this.organizationId = organizationId } + + /** Alias for calling [Builder.organizationId] with `organizationId.orElse(null)`. */ + fun organizationId(organizationId: Optional) = + organizationId(organizationId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [OrganizationDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OrganizationDeleteParams = + OrganizationDeleteParams( + organizationId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is OrganizationDeleteParams && + organizationId == other.organizationId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash( + organizationId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) + + override fun toString() = + "OrganizationDeleteParams{organizationId=$organizationId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100755 index 00000000..6d51bbe6 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPage.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.OrganizationService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see OrganizationService.list */ +class OrganizationListPage +private constructor( + private val service: OrganizationService, + private val params: OrganizationListParams, + private val response: OrganizationListPageResponse, +) : Page { + + /** + * Delegates to [OrganizationListPageResponse], but gracefully handles missing data. + * + * @see OrganizationListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): OrganizationListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): OrganizationListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): OrganizationListParams = params + + /** The response that this page was parsed from. */ + fun response(): OrganizationListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [OrganizationListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationListPage]. */ + class Builder internal constructor() { + + private var service: OrganizationService? = null + private var params: OrganizationListParams? = null + private var response: OrganizationListPageResponse? = null + + @JvmSynthetic + internal fun from(organizationListPage: OrganizationListPage) = apply { + service = organizationListPage.service + params = organizationListPage.params + response = organizationListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OrganizationListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..0509c367 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageAsync.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.OrganizationServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see OrganizationServiceAsync.list */ +class OrganizationListPageAsync +private constructor( + private val service: OrganizationServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: OrganizationListParams, + private val response: OrganizationListPageResponse, +) : PageAsync { + + /** + * Delegates to [OrganizationListPageResponse], but gracefully handles missing data. + * + * @see OrganizationListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): OrganizationListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): OrganizationListParams = params + + /** The response that this page was parsed from. */ + fun response(): OrganizationListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [OrganizationListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationListPageAsync]. */ + class Builder internal constructor() { + + private var service: OrganizationServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: OrganizationListParams? = null + private var response: OrganizationListPageResponse? = null + + @JvmSynthetic + internal fun from(organizationListPageAsync: OrganizationListPageAsync) = apply { + service = organizationListPageAsync.service + streamHandlerExecutor = organizationListPageAsync.streamHandlerExecutor + params = organizationListPageAsync.params + response = organizationListPageAsync.response + } + + fun service(service: OrganizationServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): OrganizationListPageAsync = + OrganizationListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OrganizationListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "OrganizationListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..b68414d7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is OrganizationListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..bdb9a6d1 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationListParams.kt @@ -0,0 +1,385 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all organizations. The organizations are sorted by creation date, with the most + * recently-created organizations coming first + */ +class OrganizationListParams +private constructor( + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OrganizationListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [OrganizationListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(organizationListParams: OrganizationListParams) = apply { + endingBefore = organizationListParams.endingBefore + ids = organizationListParams.ids + limit = organizationListParams.limit + orgName = organizationListParams.orgName + startingAfter = organizationListParams.startingAfter + additionalHeaders = organizationListParams.additionalHeaders.toBuilder() + additionalQueryParams = organizationListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [OrganizationListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OrganizationListParams = + OrganizationListParams( + endingBefore, + ids, + limit, + orgName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OrganizationListParams && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + ids, + limit, + orgName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "OrganizationListParams{endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..589862c0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParams.kt @@ -0,0 +1,1353 @@ +// 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.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.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 + +/** Modify organization membership */ +class OrganizationMemberUpdateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun orgId(): Optional = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun orgName(): Optional = body.orgName() + + /** + * Users to remove from the organization + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun removeUsers(): Optional = body.removeUsers() + + /** + * Returns the raw JSON value of [inviteUsers]. + * + * Unlike [inviteUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _inviteUsers(): JsonField = body._inviteUsers() + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgId(): JsonField = body._orgId() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + /** + * Returns the raw JSON value of [removeUsers]. + * + * Unlike [removeUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _removeUsers(): JsonField = body._removeUsers() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = inviteUsers.getOptional("invite_users") + + /** + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun orgId(): Optional = orgId.getOptional("org_id") + + /** + * 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. + * + * @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") + + /** + * Users to remove from the organization + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun removeUsers(): Optional = removeUsers.getOptional("remove_users") + + /** + * Returns the raw JSON value of [inviteUsers]. + * + * Unlike [inviteUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("invite_users") + @ExcludeMissing + fun _inviteUsers(): JsonField = inviteUsers + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_name") @ExcludeMissing fun _orgName(): JsonField = orgName + + /** + * Returns the raw JSON value of [removeUsers]. + * + * Unlike [removeUsers], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("remove_users") + @ExcludeMissing + fun _removeUsers(): JsonField = removeUsers + + @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 inviteUsers: JsonField = JsonMissing.of() + private var orgId: JsonField = JsonMissing.of() + private var orgName: JsonField = JsonMissing.of() + private var removeUsers: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + inviteUsers = body.inviteUsers + orgId = body.orgId + orgName = body.orgName + removeUsers = body.removeUsers + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Users to invite to the organization */ + fun inviteUsers(inviteUsers: InviteUsers?) = + inviteUsers(JsonField.ofNullable(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 { + this.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?) = 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.toMutableMap()) + } + + 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 isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + inviteUsers == other.inviteUsers && + orgId == other.orgId && + orgName == other.orgName && + removeUsers == other.removeUsers && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(inviteUsers, orgId, orgName, removeUsers, additionalProperties) + } + + 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 */ + class InviteUsers + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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> = emails.getOptional("emails") + + /** + * Singular form of group_ids + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun groupId(): Optional = groupId.getOptional("group_id") + + /** + * Optional list of group ids to add newly-invited users to. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun groupIds(): Optional> = groupIds.getOptional("group_ids") + + /** + * Singular form of group_names + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun groupName(): Optional = groupName.getOptional("group_name") + + /** + * Optional list of group names to add newly-invited users to. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun groupNames(): Optional> = groupNames.getOptional("group_names") + + /** + * Ids of existing users to invite + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun ids(): Optional> = ids.getOptional("ids") + + /** + * If true, send invite emails to the users who wore actually added + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun sendInviteEmails(): Optional = + sendInviteEmails.getOptional("send_invite_emails") + + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField> = emails + + /** + * 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 + + /** + * Returns the raw JSON value of [groupIds]. + * + * Unlike [groupIds], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("group_ids") + @ExcludeMissing + fun _groupIds(): JsonField> = groupIds + + /** + * Returns the raw JSON value of [groupName]. + * + * Unlike [groupName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("group_name") @ExcludeMissing fun _groupName(): JsonField = groupName + + /** + * Returns the raw JSON value of [groupNames]. + * + * Unlike [groupNames], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("group_names") + @ExcludeMissing + fun _groupNames(): JsonField> = groupNames + + /** + * Returns the raw JSON value of [ids]. + * + * Unlike [ids], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("ids") @ExcludeMissing fun _ids(): JsonField> = ids + + /** + * Returns the raw JSON value of [sendInviteEmails]. + * + * Unlike [sendInviteEmails], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("send_invite_emails") + @ExcludeMissing + fun _sendInviteEmails(): JsonField = sendInviteEmails + + @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 [InviteUsers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InviteUsers]. */ + class Builder internal constructor() { + + private var emails: JsonField>? = null + private var groupId: JsonField = JsonMissing.of() + private var groupIds: JsonField>? = null + private var groupName: JsonField = JsonMissing.of() + private var groupNames: JsonField>? = null + private var ids: JsonField>? = null + private var sendInviteEmails: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(inviteUsers: InviteUsers) = apply { + emails = inviteUsers.emails.map { it.toMutableList() } + groupId = inviteUsers.groupId + groupIds = inviteUsers.groupIds.map { it.toMutableList() } + groupName = inviteUsers.groupName + groupNames = inviteUsers.groupNames.map { it.toMutableList() } + ids = inviteUsers.ids.map { it.toMutableList() } + sendInviteEmails = inviteUsers.sendInviteEmails + additionalProperties = inviteUsers.additionalProperties.toMutableMap() + } + + /** Emails of users to invite */ + fun emails(emails: List?) = emails(JsonField.ofNullable(emails)) + + /** Alias for calling [Builder.emails] with `emails.orElse(null)`. */ + fun emails(emails: Optional>) = emails(emails.getOrNull()) + + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun emails(emails: JsonField>) = apply { + this.emails = emails.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [emails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEmail(email: String) = apply { + emails = + (emails ?: JsonField.of(mutableListOf())).also { + checkKnown("emails", it).add(email) + } + } + + /** Singular form of group_ids */ + 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 } + + /** Optional list of group ids to add newly-invited users to. */ + fun groupIds(groupIds: List?) = groupIds(JsonField.ofNullable(groupIds)) + + /** Alias for calling [Builder.groupIds] with `groupIds.orElse(null)`. */ + fun groupIds(groupIds: Optional>) = groupIds(groupIds.getOrNull()) + + /** + * Sets [Builder.groupIds] to an arbitrary JSON value. + * + * You should usually call [Builder.groupIds] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun groupIds(groupIds: JsonField>) = apply { + this.groupIds = groupIds.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [groupIds]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addGroupId(groupId: String) = apply { + groupIds = + (groupIds ?: JsonField.of(mutableListOf())).also { + checkKnown("groupIds", it).add(groupId) + } + } + + /** Singular form of group_names */ + fun groupName(groupName: String?) = groupName(JsonField.ofNullable(groupName)) + + /** Alias for calling [Builder.groupName] with `groupName.orElse(null)`. */ + fun groupName(groupName: Optional) = groupName(groupName.getOrNull()) + + /** + * Sets [Builder.groupName] to an arbitrary JSON value. + * + * You should usually call [Builder.groupName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun groupName(groupName: JsonField) = apply { this.groupName = groupName } + + /** Optional list of group names to add newly-invited users to. */ + fun groupNames(groupNames: List?) = groupNames(JsonField.ofNullable(groupNames)) + + /** Alias for calling [Builder.groupNames] with `groupNames.orElse(null)`. */ + fun groupNames(groupNames: Optional>) = groupNames(groupNames.getOrNull()) + + /** + * Sets [Builder.groupNames] to an arbitrary JSON value. + * + * You should usually call [Builder.groupNames] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun groupNames(groupNames: JsonField>) = apply { + this.groupNames = groupNames.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [groupNames]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addGroupName(groupName: String) = apply { + groupNames = + (groupNames ?: JsonField.of(mutableListOf())).also { + checkKnown("groupNames", it).add(groupName) + } + } + + /** Ids of existing users to invite */ + fun ids(ids: List?) = ids(JsonField.ofNullable(ids)) + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional>) = ids(ids.getOrNull()) + + /** + * Sets [Builder.ids] to an arbitrary JSON value. + * + * You should usually call [Builder.ids] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun ids(ids: JsonField>) = apply { + this.ids = ids.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [ids]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addId(id: String) = apply { + ids = (ids ?: JsonField.of(mutableListOf())).also { checkKnown("ids", it).add(id) } + } + + /** If true, send invite emails to the users who wore actually added */ + fun sendInviteEmails(sendInviteEmails: Boolean?) = + sendInviteEmails(JsonField.ofNullable(sendInviteEmails)) + + /** + * Alias for [Builder.sendInviteEmails]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun sendInviteEmails(sendInviteEmails: Boolean) = + sendInviteEmails(sendInviteEmails as Boolean?) + + /** + * Alias for calling [Builder.sendInviteEmails] with `sendInviteEmails.orElse(null)`. + */ + fun sendInviteEmails(sendInviteEmails: Optional) = + sendInviteEmails(sendInviteEmails.getOrNull()) + + /** + * Sets [Builder.sendInviteEmails] to an arbitrary JSON value. + * + * You should usually call [Builder.sendInviteEmails] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sendInviteEmails(sendInviteEmails: JsonField) = apply { + this.sendInviteEmails = sendInviteEmails + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InviteUsers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InviteUsers = + InviteUsers( + (emails ?: JsonMissing.of()).map { it.toImmutable() }, + groupId, + (groupIds ?: JsonMissing.of()).map { it.toImmutable() }, + groupName, + (groupNames ?: JsonMissing.of()).map { it.toImmutable() }, + (ids ?: JsonMissing.of()).map { it.toImmutable() }, + sendInviteEmails, + 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 + } + + return other is InviteUsers && + emails == other.emails && + groupId == other.groupId && + groupIds == other.groupIds && + groupName == other.groupName && + groupNames == other.groupNames && + ids == other.ids && + sendInviteEmails == other.sendInviteEmails && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + emails, + groupId, + groupIds, + groupName, + groupNames, + ids, + sendInviteEmails, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InviteUsers{emails=$emails, groupId=$groupId, groupIds=$groupIds, groupName=$groupName, groupNames=$groupNames, ids=$ids, sendInviteEmails=$sendInviteEmails, additionalProperties=$additionalProperties}" + } + + /** Users to remove from the organization */ + class RemoveUsers + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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> = emails.getOptional("emails") + + /** + * Ids 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 ids(): Optional> = ids.getOptional("ids") + + /** + * Returns the raw JSON value of [emails]. + * + * Unlike [emails], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("emails") @ExcludeMissing fun _emails(): JsonField> = emails + + /** + * Returns the raw JSON value of [ids]. + * + * Unlike [ids], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("ids") @ExcludeMissing fun _ids(): JsonField> = ids + + @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 [RemoveUsers]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RemoveUsers]. */ + class Builder internal constructor() { + + private var emails: JsonField>? = null + private var ids: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(removeUsers: RemoveUsers) = apply { + emails = removeUsers.emails.map { it.toMutableList() } + ids = removeUsers.ids.map { it.toMutableList() } + additionalProperties = removeUsers.additionalProperties.toMutableMap() + } + + /** Emails of users to remove */ + fun emails(emails: List?) = emails(JsonField.ofNullable(emails)) + + /** Alias for calling [Builder.emails] with `emails.orElse(null)`. */ + fun emails(emails: Optional>) = emails(emails.getOrNull()) + + /** + * Sets [Builder.emails] to an arbitrary JSON value. + * + * You should usually call [Builder.emails] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun emails(emails: JsonField>) = apply { + this.emails = emails.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [emails]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEmail(email: String) = apply { + emails = + (emails ?: JsonField.of(mutableListOf())).also { + checkKnown("emails", it).add(email) + } + } + + /** Ids of users to remove */ + fun ids(ids: List?) = ids(JsonField.ofNullable(ids)) + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional>) = ids(ids.getOrNull()) + + /** + * Sets [Builder.ids] to an arbitrary JSON value. + * + * You should usually call [Builder.ids] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun ids(ids: JsonField>) = apply { + this.ids = ids.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [ids]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addId(id: String) = apply { + ids = (ids ?: JsonField.of(mutableListOf())).also { checkKnown("ids", it).add(id) } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RemoveUsers]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RemoveUsers = + RemoveUsers( + (emails ?: JsonMissing.of()).map { it.toImmutable() }, + (ids ?: JsonMissing.of()).map { it.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 + } + + return other is RemoveUsers && + emails == other.emails && + ids == other.ids && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(emails, ids, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RemoveUsers{emails=$emails, ids=$ids, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OrganizationMemberUpdateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "OrganizationMemberUpdateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..c3edc93e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParams.kt @@ -0,0 +1,199 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get an organization object by its id */ +class OrganizationRetrieveParams +private constructor( + private val organizationId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Organization id */ + fun organizationId(): Optional = Optional.ofNullable(organizationId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OrganizationRetrieveParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of [OrganizationRetrieveParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationRetrieveParams]. */ + class Builder internal constructor() { + + private var organizationId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(organizationRetrieveParams: OrganizationRetrieveParams) = apply { + organizationId = organizationRetrieveParams.organizationId + additionalHeaders = organizationRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = organizationRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Organization id */ + fun organizationId(organizationId: String?) = apply { this.organizationId = organizationId } + + /** Alias for calling [Builder.organizationId] with `organizationId.orElse(null)`. */ + fun organizationId(organizationId: Optional) = + organizationId(organizationId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [OrganizationRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OrganizationRetrieveParams = + OrganizationRetrieveParams( + organizationId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is OrganizationRetrieveParams && + organizationId == other.organizationId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(organizationId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "OrganizationRetrieveParams{organizationId=$organizationId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..9061f6f3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/OrganizationUpdateParams.kt @@ -0,0 +1,714 @@ +// 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.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +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 + +/** + * Partially update an organization object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ +class OrganizationUpdateParams +private constructor( + private val organizationId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Organization id */ + fun organizationId(): Optional = Optional.ofNullable(organizationId) + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun apiUrl(): Optional = body.apiUrl() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isUniversalApi(): Optional = body.isUniversalApi() + + /** + * Name of the organization + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = body.name() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun proxyUrl(): Optional = body.proxyUrl() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun realtimeUrl(): Optional = body.realtimeUrl() + + /** + * Returns the raw JSON value of [apiUrl]. + * + * Unlike [apiUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _apiUrl(): JsonField = body._apiUrl() + + /** + * Returns the raw JSON value of [isUniversalApi]. + * + * Unlike [isUniversalApi], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _isUniversalApi(): JsonField = body._isUniversalApi() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [proxyUrl]. + * + * Unlike [proxyUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _proxyUrl(): JsonField = body._proxyUrl() + + /** + * Returns the raw JSON value of [realtimeUrl]. + * + * Unlike [realtimeUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _realtimeUrl(): JsonField = body._realtimeUrl() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): OrganizationUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [OrganizationUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OrganizationUpdateParams]. */ + 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() + + @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 } + + /** Alias for calling [Builder.organizationId] with `organizationId.orElse(null)`. */ + fun organizationId(organizationId: Optional) = + organizationId(organizationId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [apiUrl] + * - [isUniversalApi] + * - [name] + * - [proxyUrl] + * - [realtimeUrl] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + fun apiUrl(apiUrl: String?) = apply { body.apiUrl(apiUrl) } + + /** Alias for calling [Builder.apiUrl] with `apiUrl.orElse(null)`. */ + fun apiUrl(apiUrl: Optional) = apiUrl(apiUrl.getOrNull()) + + /** + * 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 { body.apiUrl(apiUrl) } + + fun isUniversalApi(isUniversalApi: Boolean?) = apply { body.isUniversalApi(isUniversalApi) } + + /** + * Alias for [Builder.isUniversalApi]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isUniversalApi(isUniversalApi: Boolean) = isUniversalApi(isUniversalApi as Boolean?) + + /** Alias for calling [Builder.isUniversalApi] with `isUniversalApi.orElse(null)`. */ + fun isUniversalApi(isUniversalApi: Optional) = + isUniversalApi(isUniversalApi.getOrNull()) + + /** + * 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 { + 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()) + + /** + * 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) } + + fun proxyUrl(proxyUrl: String?) = apply { body.proxyUrl(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 { 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()) + + /** + * 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 { body.realtimeUrl(realtimeUrl) } + + 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 [OrganizationUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OrganizationUpdateParams = + OrganizationUpdateParams( + organizationId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> organizationId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun apiUrl(): Optional = apiUrl.getOptional("api_url") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun isUniversalApi(): Optional = isUniversalApi.getOptional("is_universal_api") + + /** + * Name of the organization + * + * @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 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 = realtimeUrl.getOptional("realtime_url") + + /** + * Returns the raw JSON value of [apiUrl]. + * + * Unlike [apiUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("api_url") @ExcludeMissing fun _apiUrl(): JsonField = apiUrl + + /** + * Returns the raw JSON value of [isUniversalApi]. + * + * Unlike [isUniversalApi], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("is_universal_api") + @ExcludeMissing + fun _isUniversalApi(): JsonField = isUniversalApi + + /** + * 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 [proxyUrl]. + * + * Unlike [proxyUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("proxy_url") @ExcludeMissing fun _proxyUrl(): JsonField = proxyUrl + + /** + * Returns the raw JSON value of [realtimeUrl]. + * + * Unlike [realtimeUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("realtime_url") + @ExcludeMissing + fun _realtimeUrl(): JsonField = realtimeUrl + + @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 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() + + @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 apiUrl(apiUrl: String?) = apiUrl(JsonField.ofNullable(apiUrl)) + + /** Alias for calling [Builder.apiUrl] with `apiUrl.orElse(null)`. */ + fun apiUrl(apiUrl: Optional) = apiUrl(apiUrl.getOrNull()) + + /** + * 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 isUniversalApi(isUniversalApi: Boolean?) = + isUniversalApi(JsonField.ofNullable(isUniversalApi)) + + /** + * Alias for [Builder.isUniversalApi]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isUniversalApi(isUniversalApi: Boolean) = isUniversalApi(isUniversalApi as Boolean?) + + /** Alias for calling [Builder.isUniversalApi] with `isUniversalApi.orElse(null)`. */ + fun isUniversalApi(isUniversalApi: Optional) = + isUniversalApi(isUniversalApi.getOrNull()) + + /** + * 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 + } + + /** Name of the organization */ + 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 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 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( + apiUrl, + isUniversalApi, + name, + proxyUrl, + realtimeUrl, + additionalProperties.toMutableMap(), + ) + } + + 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 a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @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 other is Body && + apiUrl == other.apiUrl && + isUniversalApi == other.isUniversalApi && + name == other.name && + proxyUrl == other.proxyUrl && + realtimeUrl == other.realtimeUrl && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(apiUrl, isUniversalApi, name, proxyUrl, realtimeUrl, additionalProperties) + } + + 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 { + if (this === other) { + return true + } + + return other is OrganizationUpdateParams && + organizationId == other.organizationId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(organizationId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "OrganizationUpdateParams{organizationId=$organizationId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..e50e673d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutput.kt @@ -0,0 +1,386 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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 + +class PatchOrganizationMembersOutput +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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. + * + * @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 orgId(): String = orgId.getRequired("org_id") + + /** + * @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 status(): Status = status.getRequired("status") + + /** + * If invite emails failed to send for some reason, the patch operation will still complete, but + * we will return an error message here + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun sendEmailError(): Optional = sendEmailError.getOptional("send_email_error") + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + + /** + * Returns the raw JSON value of [sendEmailError]. + * + * Unlike [sendEmailError], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("send_email_error") + @ExcludeMissing + fun _sendEmailError(): JsonField = sendEmailError + + @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 + * [PatchOrganizationMembersOutput]. + * + * The following fields are required: + * ```java + * .orgId() + * .status() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PatchOrganizationMembersOutput]. */ + class Builder internal constructor() { + + private var orgId: JsonField? = null + private var status: JsonField? = null + private var sendEmailError: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(patchOrganizationMembersOutput: PatchOrganizationMembersOutput) = apply { + orgId = patchOrganizationMembersOutput.orgId + status = patchOrganizationMembersOutput.status + sendEmailError = patchOrganizationMembersOutput.sendEmailError + additionalProperties = + patchOrganizationMembersOutput.additionalProperties.toMutableMap() + } + + /** The id of the org that was modified. */ + fun orgId(orgId: String) = orgId(JsonField.of(orgId)) + + /** + * 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 status(status: Status) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [Status] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun status(status: JsonField) = apply { this.status = status } + + /** + * If invite emails failed to send for some reason, the patch operation will still complete, + * but we will return an error message here + */ + fun sendEmailError(sendEmailError: String?) = + sendEmailError(JsonField.ofNullable(sendEmailError)) + + /** Alias for calling [Builder.sendEmailError] with `sendEmailError.orElse(null)`. */ + fun sendEmailError(sendEmailError: Optional) = + sendEmailError(sendEmailError.getOrNull()) + + /** + * Sets [Builder.sendEmailError] to an arbitrary JSON value. + * + * You should usually call [Builder.sendEmailError] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sendEmailError(sendEmailError: JsonField) = apply { + this.sendEmailError = sendEmailError + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [PatchOrganizationMembersOutput]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .orgId() + * .status() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PatchOrganizationMembersOutput = + PatchOrganizationMembersOutput( + checkRequired("orgId", orgId), + checkRequired("status", status), + sendEmailError, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SUCCESS = of("success") + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + /** An enum containing [Status]'s known values. */ + enum class Known { + SUCCESS + } + + /** + * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Status] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SUCCESS, + /** An enum member indicating that [Status] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SUCCESS -> Value.SUCCESS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SUCCESS -> Known.SUCCESS + else -> throw BraintrustInvalidDataException("Unknown Status: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Status && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PatchOrganizationMembersOutput && + orgId == other.orgId && + status == other.status && + sendEmailError == other.sendEmailError && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(orgId, status, sendEmailError, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PatchOrganizationMembersOutput{orgId=$orgId, status=$status, sendEmailError=$sendEmailError, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..50e97a37 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Permission.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.errors.BraintrustInvalidDataException +import com.fasterxml.jackson.annotation.JsonCreator + +/** + * Each permission permits a certain type of operation on an object in the system + * + * Permissions can be assigned to to objects on an individual basis, or grouped into roles + */ +class Permission @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CREATE = of("create") + + @JvmField val READ = of("read") + + @JvmField val UPDATE = of("update") + + @JvmField val DELETE = of("delete") + + @JvmField val CREATE_ACLS = of("create_acls") + + @JvmField val READ_ACLS = of("read_acls") + + @JvmField val UPDATE_ACLS = of("update_acls") + + @JvmField val DELETE_ACLS = of("delete_acls") + + @JvmStatic fun of(value: String) = Permission(JsonField.of(value)) + } + + /** An enum containing [Permission]'s known values. */ + enum class Known { + CREATE, + READ, + UPDATE, + DELETE, + CREATE_ACLS, + READ_ACLS, + UPDATE_ACLS, + DELETE_ACLS, + } + + /** + * An enum containing [Permission]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Permission] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + CREATE, + READ, + UPDATE, + DELETE, + CREATE_ACLS, + READ_ACLS, + UPDATE_ACLS, + DELETE_ACLS, + /** An enum member indicating that [Permission] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + CREATE -> Value.CREATE + READ -> Value.READ + UPDATE -> Value.UPDATE + DELETE -> Value.DELETE + CREATE_ACLS -> Value.CREATE_ACLS + READ_ACLS -> Value.READ_ACLS + UPDATE_ACLS -> Value.UPDATE_ACLS + DELETE_ACLS -> Value.DELETE_ACLS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + CREATE -> Known.CREATE + READ -> Known.READ + UPDATE -> Known.UPDATE + DELETE -> Known.DELETE + CREATE_ACLS -> Known.CREATE_ACLS + READ_ACLS -> Known.READ_ACLS + UPDATE_ACLS -> Known.UPDATE_ACLS + DELETE_ACLS -> Known.DELETE_ACLS + else -> throw BraintrustInvalidDataException("Unknown Permission: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { BraintrustInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): Permission = 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 + } + + return other is Permission && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Project.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Project.kt index d767c848..43f57b67 100644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Project.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Project.kt @@ -6,217 +6,403 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.checkRequired +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 com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.time.OffsetDateTime +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull -@JsonDeserialize(builder = Project.Builder::class) -@NoAutoDetect class Project +@JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val id: JsonField, - private val orgId: 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: Map, + private val additionalProperties: MutableMap, ) { - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Unique identifier for the project */ + @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 + * + * @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 id(): String = id.getRequired("id") - /** Unique id for the organization that the project belongs under */ - fun orgId(): String = orgId.getRequired("org_id") - - /** Name of the project */ + /** + * 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") - /** Date of project creation */ - fun created(): Optional = Optional.ofNullable(created.getNullable("created")) - - /** Date of project deletion, or null if the project is still active */ - fun deletedAt(): Optional = - Optional.ofNullable(deletedAt.getNullable("deleted_at")) - - /** Identifies the user who created the project */ - fun userId(): Optional = Optional.ofNullable(userId.getNullable("user_id")) - - /** Unique identifier for the project */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** Unique id for the organization that the project belongs under */ - @JsonProperty("org_id") @ExcludeMissing fun _orgId() = orgId - - /** Name of the project */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Date of project creation */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Date of project deletion, or null if the project is still active */ - @JsonProperty("deleted_at") @ExcludeMissing fun _deletedAt() = deletedAt + /** + * Unique id for the organization that the project 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 orgId(): String = orgId.getRequired("org_id") - /** Identifies the user who created the project */ - @JsonProperty("user_id") @ExcludeMissing fun _userId() = userId + /** + * Date of project creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Date of project deletion, or null if the project 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") + + /** + * @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") + + /** + * Identifies the user who created the project + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [settings]. + * + * Unlike [settings], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("settings") @ExcludeMissing fun _settings(): JsonField = settings + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } @JsonAnyGetter @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Project = apply { - if (!validated) { - id() - orgId() - name() - created() - deletedAt() - userId() - validated = true - } - } + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) fun toBuilder() = Builder().from(this) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Project && - this.id == other.id && - this.orgId == other.orgId && - this.name == other.name && - this.created == other.created && - this.deletedAt == other.deletedAt && - this.userId == other.userId && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - orgId, - name, - created, - deletedAt, - userId, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Project{id=$id, orgId=$orgId, name=$name, created=$created, deletedAt=$deletedAt, userId=$userId, additionalProperties=$additionalProperties}" - companion object { + /** + * Returns a mutable builder for constructing an instance of [Project]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .orgId() + * ``` + */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Project]. */ + class Builder internal constructor() { - private var id: JsonField = JsonMissing.of() - private var orgId: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() + private var id: JsonField? = null + private var name: JsonField? = null + private var orgId: JsonField? = null private var created: JsonField = JsonMissing.of() private var deletedAt: JsonField = JsonMissing.of() + private var settings: JsonField = JsonMissing.of() private var userId: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(project: Project) = apply { - this.id = project.id - this.orgId = project.orgId - this.name = project.name - this.created = project.created - this.deletedAt = project.deletedAt - this.userId = project.userId - additionalProperties(project.additionalProperties) + id = project.id + name = project.name + orgId = project.orgId + created = project.created + deletedAt = project.deletedAt + settings = project.settings + userId = project.userId + additionalProperties = project.additionalProperties.toMutableMap() } /** Unique identifier for the project */ fun id(id: String) = id(JsonField.of(id)) - /** Unique identifier for the project */ - @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } - - /** Unique id for the organization that the project belongs under */ - fun orgId(orgId: String) = orgId(JsonField.of(orgId)) - - /** Unique id for the organization that the project belongs under */ - @JsonProperty("org_id") - @ExcludeMissing - fun orgId(orgId: JsonField) = apply { this.orgId = orgId } + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } /** Name of the project */ fun name(name: String) = name(JsonField.of(name)) - /** Name of the project */ - @JsonProperty("name") - @ExcludeMissing + /** + * 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 } - /** Date of project creation */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) + /** Unique id for the organization that the project belongs under */ + fun orgId(orgId: String) = orgId(JsonField.of(orgId)) + + /** + * 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 } /** Date of project creation */ - @JsonProperty("created") - @ExcludeMissing + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun created(created: JsonField) = apply { this.created = created } /** Date of project deletion, or null if the project is still active */ - fun deletedAt(deletedAt: OffsetDateTime) = deletedAt(JsonField.of(deletedAt)) - - /** Date of project deletion, or null if the project is still active */ - @JsonProperty("deleted_at") - @ExcludeMissing + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } - /** Identifies the user who created the project */ - fun userId(userId: String) = userId(JsonField.of(userId)) + 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 } /** Identifies the user who created the project */ - @JsonProperty("user_id") - @ExcludeMissing + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ fun userId(userId: JsonField) = apply { this.userId = userId } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Project]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .orgId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ fun build(): Project = Project( - id, - orgId, - name, + checkRequired("id", id), + checkRequired("name", name), + checkRequired("orgId", orgId), created, deletedAt, + settings, userId, - additionalProperties.toUnmodifiable(), + 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 + } + + return other is Project && + id == other.id && + name == other.name && + orgId == other.orgId && + created == other.created && + deletedAt == other.deletedAt && + settings == other.settings && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, name, orgId, created, deletedAt, settings, userId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Project{id=$id, name=$name, orgId=$orgId, created=$created, deletedAt=$deletedAt, settings=$settings, userId=$userId, additionalProperties=$additionalProperties}" } 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 old mode 100644 new mode 100755 index 6a037704..e4fc5033 --- 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 @@ -3,276 +3,498 @@ 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.toUnmodifiable -import com.braintrustdata.api.models.* +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.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 com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Create a new project. If there is an existing project with the same name as the one specified in + * the request, will return the existing project unmodified + */ class ProjectCreateParams -constructor( - private val name: String, - private val orgName: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun name(): String = name - - fun orgName(): Optional = Optional.ofNullable(orgName) - - @JvmSynthetic - internal fun getBody(): ProjectCreateBody { - return ProjectCreateBody( - name, - orgName, - additionalBodyProperties, - ) +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * 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 = body.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 = body.orgName() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [ProjectCreateParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + private var body: Body.Builder = Body.builder() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - @JsonDeserialize(builder = ProjectCreateBody.Builder::class) - @NoAutoDetect - class ProjectCreateBody - internal constructor( - private val name: String?, - private val orgName: String?, - private val additionalProperties: Map, - ) { + @JvmSynthetic + internal fun from(projectCreateParams: ProjectCreateParams) = apply { + body = projectCreateParams.body.toBuilder() + additionalHeaders = projectCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = projectCreateParams.additionalQueryParams.toBuilder() + } - private var hashCode: Int = 0 + /** + * 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 */ - @JsonProperty("name") fun name(): String? = name + 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) } /** * 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. */ - @JsonProperty("org_name") fun orgName(): String? = orgName + fun orgName(orgName: String?) = apply { body.orgName(orgName) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) - fun toBuilder() = Builder().from(this) + /** + * 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) } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - return other is ProjectCreateBody && - this.name == other.name && - this.orgName == other.orgName && - this.additionalProperties == other.additionalProperties + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - orgName, - additionalProperties, - ) + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - return hashCode + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - override fun toString() = - "ProjectCreateBody{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - @JvmStatic fun builder() = Builder() + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - class Builder { + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - private var name: String? = null - private var orgName: String? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(projectCreateBody: ProjectCreateBody) = apply { - this.name = projectCreateBody.name - this.orgName = projectCreateBody.orgName - additionalProperties(projectCreateBody.additionalProperties) - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - /** Name of the project */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** - * 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. - */ - @JsonProperty("org_name") - fun orgName(orgName: String) = apply { this.orgName = orgName } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.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 build(): ProjectCreateBody = - ProjectCreateBody( - checkNotNull(name) { "`name` is required but was not set" }, - orgName, - additionalProperties.toUnmodifiable(), - ) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - } - fun _additionalQueryParams(): Map> = additionalQueryParams + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun _additionalHeaders(): Map> = additionalHeaders + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun _additionalBodyProperties(): Map = additionalBodyProperties + 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) } - return other is ProjectCreateParams && - this.name == other.name && - this.orgName == other.orgName && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - override fun hashCode(): Int { - return Objects.hash( - name, - orgName, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - override fun toString() = - "ProjectCreateParams{name=$name, orgName=$orgName, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - fun toBuilder() = Builder().from(this) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - companion object { + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - @JvmStatic fun builder() = Builder() + 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 [ProjectCreateParams]. + * + * 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(): ProjectCreateParams = + ProjectCreateParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) } - @NoAutoDetect - class Builder { + fun _body(): Body = body - private var name: String? = null - private var orgName: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + override fun _headers(): Headers = additionalHeaders - @JvmSynthetic - internal fun from(projectCreateParams: ProjectCreateParams) = apply { - this.name = projectCreateParams.name - this.orgName = projectCreateParams.orgName - additionalQueryParams(projectCreateParams.additionalQueryParams) - additionalHeaders(projectCreateParams.additionalHeaders) - additionalBodyProperties(projectCreateParams.additionalBodyProperties) - } + override fun _queryParams(): QueryParams = additionalQueryParams - /** Name of the project */ - fun name(name: String) = apply { this.name = name } + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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(orgName: String) = apply { this.orgName = orgName } + fun orgName(): Optional = orgName.getOptional("org_name") - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } + /** + * 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 - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + /** + * 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 - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + fun toBuilder() = Builder().from(this) - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + companion object { - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } + private var name: JsonField? = null + private var orgName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + orgName = body.orgName + additionalProperties = body.additionalProperties.toMutableMap() + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + /** 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()) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + orgName() + validated = true } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun build(): ProjectCreateParams = - ProjectCreateParams( - checkNotNull(name) { "`name` is required but was not set" }, - orgName, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) + /** + * Returns a 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 other is Body && + name == other.name && + orgName == other.orgName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, orgName, additionalProperties) } + + 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 + } + + return other is ProjectCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index 830d84e9..3cfacf7a --- 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,141 +3,172 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Delete a project object by its id */ class ProjectDeleteParams -constructor( - private val projectId: String, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, +private constructor( + private val projectId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, -) { +) : Params { - fun projectId(): String = projectId - - @JvmSynthetic - internal fun getBody(): Optional> { - return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + /** Additional body properties to send with the request. */ fun _additionalBodyProperties(): Map = additionalBodyProperties - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectDeleteParams && - this.projectId == other.projectId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - override fun hashCode(): Int { - return Objects.hash( - projectId, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "ProjectDeleteParams{projectId=$projectId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ProjectDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectDeleteParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ProjectDeleteParams]. */ + class Builder internal constructor() { private var projectId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(projectDeleteParams: ProjectDeleteParams) = apply { - this.projectId = projectDeleteParams.projectId - additionalQueryParams(projectDeleteParams.additionalQueryParams) - additionalHeaders(projectDeleteParams.additionalHeaders) - additionalBodyProperties(projectDeleteParams.additionalBodyProperties) + projectId = projectDeleteParams.projectId + additionalHeaders = projectDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = projectDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = projectDeleteParams.additionalBodyProperties.toMutableMap() } /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + fun projectId(projectId: String?) = apply { this.projectId = projectId } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(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 putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } fun additionalBodyProperties(additionalBodyProperties: Map) = apply { this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + putAllAdditionalBodyProperties(additionalBodyProperties) } fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + additionalBodyProperties.put(key, value) } fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = @@ -145,12 +176,56 @@ constructor( this.additionalBodyProperties.putAll(additionalBodyProperties) } + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [ProjectDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ProjectDeleteParams = ProjectDeleteParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), + projectId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), ) } + + 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 + } + + return other is ProjectDeleteParams && + projectId == other.projectId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(projectId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "ProjectDeleteParams{projectId=$projectId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } 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 old mode 100644 new mode 100755 index 99ee938e..abd9a6c9 --- 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,192 +2,124 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +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.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects -import java.util.Optional -import java.util.stream.Stream -import java.util.stream.StreamSupport +import kotlin.jvm.optionals.getOrNull +/** @see ProjectService.list */ class ProjectListPage private constructor( - private val projectService: ProjectService, + private val service: ProjectService, private val params: ProjectListParams, - private val response: Response, -) { + private val response: ProjectListPageResponse, +) : Page { - 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 items(): List = objects() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectListPage && - this.projectService == other.projectService && - this.params == other.params && - this.response == other.response - } - - override fun hashCode(): Int { - return Objects.hash( - projectService, - params, - response, - ) - } - - override fun toString() = - "ProjectListPage{projectService=$projectService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } + override fun hasNextPage(): Boolean = items().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() - ) + fun nextPageParams(): ProjectListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() } else { - Optional.of( - ProjectListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() } - } - - fun getNextPage(): Optional { - return getNextPageParams().map { projectService.list(it) } - } - - fun autoPager(): AutoPager = AutoPager(this) - - companion object { - - @JvmStatic - fun of(projectService: ProjectService, params: ProjectListParams, response: Response) = - ProjectListPage( - projectService, - params, - response, - ) - } - @JsonDeserialize(builder = Response.Builder::class) - @NoAutoDetect - class Response - constructor( - private val objects: JsonField>, - private val additionalProperties: Map, - ) { + override fun nextPage(): ProjectListPage = service.list(nextPageParams()) - private var validated: Boolean = false + fun autoPager(): AutoPager = AutoPager.from(this) - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** The parameters that were used to request this page. */ + fun params(): ProjectListParams = params - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) + /** The response that this page was parsed from. */ + fun response(): ProjectListPageResponse = response - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun toBuilder() = Builder().from(this) - fun validate(): Response = apply { - if (!validated) { - objects().map { it.validate() } - validated = true - } - } + companion object { - fun toBuilder() = Builder().from(this) + /** + * 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 equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** A builder for [ProjectListPage]. */ + class Builder internal constructor() { - return other is Response && - this.objects == other.objects && - this.additionalProperties == other.additionalProperties - } + private var service: ProjectService? = null + private var params: ProjectListParams? = null + private var response: ProjectListPageResponse? = null - override fun hashCode(): Int { - return Objects.hash(objects, additionalProperties) + @JvmSynthetic + internal fun from(projectListPage: ProjectListPage) = apply { + service = projectListPage.service + params = projectListPage.params + response = projectListPage.response } - override fun toString() = - "ProjectListPage.Response{objects=$objects, additionalProperties=$additionalProperties}" - - companion object { + 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), + ) + } - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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)) - - @JsonProperty("objects") - fun objects(objects: JsonField>) = apply { this.objects = objects } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(objects, additionalProperties.toUnmodifiable()) - } + return other is ProjectListPage && + service == other.service && + params == other.params && + response == other.response } - class AutoPager - constructor( - private val firstPage: ProjectListPage, - ) : Iterable { - - override fun iterator(): Iterator = iterator { - var page = firstPage - var index = 0 - while (true) { - while (index < page.objects().size) { - yield(page.objects()[index++]) - } - page = page.getNextPage().orElse(null) ?: break - index = 0 - } - } + override fun hashCode(): Int = Objects.hash(service, params, response) - fun stream(): Stream { - return StreamSupport.stream(spliterator(), false) - } - } + 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 old mode 100644 new mode 100755 index 4892f561..e583e63c --- 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,202 +2,138 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +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.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize 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 +/** @see ProjectServiceAsync.list */ class ProjectListPageAsync private constructor( - private val projectService: ProjectServiceAsync, + private val service: ProjectServiceAsync, + private val streamHandlerExecutor: Executor, private val params: ProjectListParams, - private val response: Response, -) { + private val response: ProjectListPageResponse, +) : PageAsync { - 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 items(): List = objects() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectListPageAsync && - this.projectService == other.projectService && - this.params == other.params && - this.response == other.response - } - - override fun hashCode(): Int { - return Objects.hash( - projectService, - params, - response, - ) - } - - override fun toString() = - "ProjectListPageAsync{projectService=$projectService, params=$params, response=$response}" - - fun hasNextPage(): Boolean { - return !objects().isEmpty() - } - - fun getNextPageParams(): Optional { - if (!hasNextPage()) { - return Optional.empty() - } + override fun hasNextPage(): Boolean = items().isNotEmpty() - return if (params.endingBefore().isPresent) { - Optional.of( - ProjectListParams.builder() - .from(params) - .endingBefore(objects().first().id()) - .build() - ) + fun nextPageParams(): ProjectListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() } else { - Optional.of( - ProjectListParams.builder() - .from(params) - .startingAfter(objects().last().id()) - .build() - ) + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() } - } - fun getNextPage(): CompletableFuture> { - return getNextPageParams() - .map { projectService.list(it).thenApply { Optional.of(it) } } - .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } - } + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) - fun autoPager(): AutoPager = AutoPager(this) + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) - companion object { + /** The parameters that were used to request this page. */ + fun params(): ProjectListParams = params - @JvmStatic - fun of(projectService: ProjectServiceAsync, params: ProjectListParams, response: Response) = - ProjectListPageAsync( - projectService, - params, - response, - ) - } + /** The response that this page was parsed from. */ + fun response(): ProjectListPageResponse = response - @JsonDeserialize(builder = Response.Builder::class) - @NoAutoDetect - class Response - constructor( - private val objects: JsonField>, - private val additionalProperties: Map, - ) { + fun toBuilder() = Builder().from(this) - private var validated: Boolean = false + companion object { - fun objects(): List = objects.getNullable("objects") ?: listOf() + /** + * Returns a mutable builder for constructing an instance of [ProjectListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } - @JsonProperty("objects") - fun _objects(): Optional>> = Optional.ofNullable(objects) + /** A builder for [ProjectListPageAsync]. */ + class Builder internal constructor() { - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + private var service: ProjectServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ProjectListParams? = null + private var response: ProjectListPageResponse? = null - fun validate(): Response = apply { - if (!validated) { - objects().map { it.validate() } - validated = true - } + @JvmSynthetic + internal fun from(projectListPageAsync: ProjectListPageAsync) = apply { + service = projectListPageAsync.service + streamHandlerExecutor = projectListPageAsync.streamHandlerExecutor + params = projectListPageAsync.params + response = projectListPageAsync.response } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Response && - this.objects == other.objects && - this.additionalProperties == other.additionalProperties - } + fun service(service: ProjectServiceAsync) = apply { this.service = service } - override fun hashCode(): Int { - return Objects.hash(objects, additionalProperties) + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor } - override fun toString() = - "ProjectListPageAsync.Response{objects=$objects, additionalProperties=$additionalProperties}" - - companion object { + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectListPageAsync = + ProjectListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - 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)) - - @JsonProperty("objects") - fun objects(objects: JsonField>) = apply { this.objects = objects } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun build() = Response(objects, additionalProperties.toUnmodifiable()) - } + return other is ProjectListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response } - class AutoPager - constructor( - private val firstPage: ProjectListPageAsync, - ) { - - fun forEach(action: Predicate, executor: Executor): CompletableFuture { - fun CompletableFuture>.forEach( - action: (Project) -> Boolean, - executor: Executor - ): CompletableFuture = - thenComposeAsync( - { page -> - page - .filter { it.objects().all(action) } - .map { it.getNextPage().forEach(action, executor) } - .orElseGet { CompletableFuture.completedFuture(null) } - }, - executor - ) - return CompletableFuture.completedFuture(Optional.of(firstPage)) - .forEach(action::test, executor) - } + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) - fun toList(executor: Executor): CompletableFuture> { - val values = mutableListOf() - return forEach(values::add, executor).thenApply { values } - } - } + override fun toString() = + "ProjectListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..eb9f328d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is ProjectListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 old mode 100644 new mode 100755 index 60f4f76c..b541d16e --- 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,182 +2,400 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +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.core.toImmutable import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * List out all projects. The projects are sorted by creation date, with the most recently-created + * projects coming first + */ class ProjectListParams -constructor( +private constructor( private val endingBefore: String?, + private val ids: Ids?, private val limit: Long?, private val orgName: String?, private val projectName: String?, private val startingAfter: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { - + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ fun limit(): Optional = Optional.ofNullable(limit) + /** Filter search results to within a particular organization */ fun orgName(): Optional = Optional.ofNullable(orgName) + /** Name of the project to search for */ fun projectName(): Optional = Optional.ofNullable(projectName) + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ fun startingAfter(): Optional = Optional.ofNullable(startingAfter) - @JvmSynthetic - internal fun getQueryParams(): Map> { - val params = mutableMapOf>() - this.endingBefore?.let { params.put("ending_before", listOf(it.toString())) } - this.limit?.let { params.put("limit", listOf(it.toString())) } - this.orgName?.let { params.put("org_name", listOf(it.toString())) } - this.projectName?.let { params.put("project_name", listOf(it.toString())) } - this.startingAfter?.let { params.put("starting_after", listOf(it.toString())) } - params.putAll(additionalQueryParams) - return params.toUnmodifiable() - } - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - return other is ProjectListParams && - this.endingBefore == other.endingBefore && - this.limit == other.limit && - this.orgName == other.orgName && - this.projectName == other.projectName && - this.startingAfter == other.startingAfter && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } - - override fun hashCode(): Int { - return Objects.hash( - endingBefore, - limit, - orgName, - projectName, - startingAfter, - additionalQueryParams, - additionalHeaders, - ) - } - - override fun toString() = - "ProjectListParams{endingBefore=$endingBefore, limit=$limit, orgName=$orgName, projectName=$projectName, startingAfter=$startingAfter, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ProjectListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectListParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ProjectListParams]. */ + class Builder internal constructor() { private var endingBefore: String? = null + private var ids: Ids? = null private var limit: Long? = null private var orgName: String? = null private var projectName: String? = null private var startingAfter: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(projectListParams: ProjectListParams) = apply { - this.endingBefore = projectListParams.endingBefore - this.limit = projectListParams.limit - this.orgName = projectListParams.orgName - this.projectName = projectListParams.projectName - this.startingAfter = projectListParams.startingAfter - additionalQueryParams(projectListParams.additionalQueryParams) - additionalHeaders(projectListParams.additionalHeaders) + endingBefore = projectListParams.endingBefore + ids = projectListParams.ids + limit = projectListParams.limit + orgName = projectListParams.orgName + projectName = projectListParams.projectName + startingAfter = projectListParams.startingAfter + additionalHeaders = projectListParams.additionalHeaders.toBuilder() + additionalQueryParams = projectListParams.additionalQueryParams.toBuilder() } /** - * A cursor for pagination. For example, if the initial item in the last page you fetched - * had an id of `foo`, pass `ending_before=foo` to fetch the previous page. Note: you may - * only pass one of `starting_after` and `ending_before` + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times */ - fun endingBefore(endingBefore: String) = apply { this.endingBefore = endingBefore } + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) /** Limit the number of objects to return */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(limit: Long?) = apply { this.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()) /** Filter search results to within a particular organization */ - fun orgName(orgName: String) = apply { this.orgName = orgName } + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) /** Name of the project to search for */ - fun projectName(projectName: String) = apply { this.projectName = projectName } + fun projectName(projectName: String?) = apply { this.projectName = projectName } + + /** Alias for calling [Builder.projectName] with `projectName.orElse(null)`. */ + fun projectName(projectName: Optional) = projectName(projectName.getOrNull()) /** - * A cursor for pagination. For example, if the final item in the last page you fetched had - * an id of `foo`, pass `starting_after=foo` to fetch the next page. Note: you may only pass - * one of `starting_after` and `ending_before` + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` */ - fun startingAfter(startingAfter: String) = apply { this.startingAfter = startingAfter } + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [ProjectListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ProjectListParams = ProjectListParams( endingBefore, + ids, limit, orgName, projectName, startingAfter, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectListParams && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + projectName == other.projectName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + ids, + limit, + orgName, + projectName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ProjectListParams{endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, projectName=$projectName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index 30fef506..f1c32bd7 --- 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 @@ -4,631 +4,470 @@ 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.toUnmodifiable +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.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Log feedback for a set of project logs events */ class ProjectLogFeedbackParams -constructor( - private val projectId: String, - private val feedback: List, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { +private constructor( + private val projectId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** + * 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 = body.feedback() + + /** + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _feedback(): JsonField> = body._feedback() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun projectId(): String = projectId + fun toBuilder() = Builder().from(this) - fun feedback(): List = feedback + companion object { - @JvmSynthetic - internal fun getBody(): ProjectLogFeedbackBody { - return ProjectLogFeedbackBody(feedback, additionalBodyProperties) + /** + * Returns a mutable builder for constructing an instance of [ProjectLogFeedbackParams]. + * + * The following fields are required: + * ```java + * .feedback() + * ``` + */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [ProjectLogFeedbackParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" + @JvmSynthetic + internal fun from(projectLogFeedbackParams: ProjectLogFeedbackParams) = apply { + projectId = projectLogFeedbackParams.projectId + body = projectLogFeedbackParams.body.toBuilder() + additionalHeaders = projectLogFeedbackParams.additionalHeaders.toBuilder() + additionalQueryParams = projectLogFeedbackParams.additionalQueryParams.toBuilder() } - } - - @JsonDeserialize(builder = ProjectLogFeedbackBody.Builder::class) - @NoAutoDetect - class ProjectLogFeedbackBody - internal constructor( - private val feedback: List?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** A list of project logs feedback items */ - @JsonProperty("feedback") fun feedback(): List? = feedback - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } - fun toBuilder() = Builder().from(this) + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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() } - return other is ProjectLogFeedbackBody && - this.feedback == other.feedback && - this.additionalProperties == other.additionalProperties - } + /** A list of project logs feedback items */ + fun feedback(feedback: List) = apply { body.feedback(feedback) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(feedback, additionalProperties) - } - return hashCode + /** + * 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 { + body.feedback(feedback) } - override fun toString() = - "ProjectLogFeedbackBody{feedback=$feedback, additionalProperties=$additionalProperties}" - - companion object { + /** + * Adds a single [FeedbackProjectLogsItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFeedback(feedback: FeedbackProjectLogsItem) = apply { body.addFeedback(feedback) } - @JvmStatic fun builder() = Builder() + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - class Builder { - - private var feedback: List? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(projectLogFeedbackBody: ProjectLogFeedbackBody) = apply { - this.feedback = projectLogFeedbackBody.feedback - additionalProperties(projectLogFeedbackBody.additionalProperties) - } - - /** A list of project logs feedback items */ - @JsonProperty("feedback") - fun feedback(feedback: List) = apply { this.feedback = feedback } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun build(): ProjectLogFeedbackBody = - ProjectLogFeedbackBody( - checkNotNull(feedback) { "`feedback` is required but was not set" } - .toUnmodifiable(), - additionalProperties.toUnmodifiable() - ) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - return other is ProjectLogFeedbackParams && - this.projectId == other.projectId && - this.feedback == other.feedback && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - override fun hashCode(): Int { - return Objects.hash( - projectId, - feedback, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - override fun toString() = - "ProjectLogFeedbackParams{projectId=$projectId, feedback=$feedback, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - fun toBuilder() = Builder().from(this) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - companion object { + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmStatic fun builder() = Builder() - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - @NoAutoDetect - class Builder { + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - private var projectId: String? = null - private var feedback: MutableList = mutableListOf() - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(projectLogFeedbackParams: ProjectLogFeedbackParams) = apply { - this.projectId = projectLogFeedbackParams.projectId - this.feedback(projectLogFeedbackParams.feedback) - additionalQueryParams(projectLogFeedbackParams.additionalQueryParams) - additionalHeaders(projectLogFeedbackParams.additionalHeaders) - additionalBodyProperties(projectLogFeedbackParams.additionalBodyProperties) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - /** A list of project logs feedback items */ - fun feedback(feedback: List) = apply { - this.feedback.clear() - this.feedback.addAll(feedback) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - /** A list of project logs feedback items */ - fun addFeedback(feedback: Feedback) = apply { this.feedback.add(feedback) } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + putAllAdditionalQueryParams(additionalQueryParams) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - + /** + * Returns an immutable instance of [ProjectLogFeedbackParams]. + * + * 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(): ProjectLogFeedbackParams = ProjectLogFeedbackParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - checkNotNull(feedback) { "`feedback` is required but was not set" } - .toUnmodifiable(), - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), + projectId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } - @JsonDeserialize(builder = Feedback.Builder::class) - @NoAutoDetect - class Feedback - private constructor( - private val id: String?, - private val scores: Scores?, - private val expected: JsonValue?, - private val comment: String?, - private val metadata: Metadata?, - private val source: Source?, - private val additionalProperties: Map, - ) { + fun _body(): Body = body - private var hashCode: Int = 0 + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId ?: "" + else -> "" + } - /** - * 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` - */ - @JsonProperty("id") fun id(): String? = id + override fun _headers(): Headers = additionalHeaders - /** - * 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 - */ - @JsonProperty("scores") fun scores(): Scores? = scores + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val feedback: JsonField>, + private val additionalProperties: MutableMap, + ) { + + @JsonCreator + private constructor( + @JsonProperty("feedback") + @ExcludeMissing + feedback: JsonField> = JsonMissing.of() + ) : this(feedback, mutableMapOf()) /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not + * 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). */ - @JsonProperty("expected") fun expected(): JsonValue? = expected - - /** An optional comment string to log about the project logs event */ - @JsonProperty("comment") fun comment(): String? = comment + fun feedback(): List = feedback.getRequired("feedback") /** - * 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. + * Returns the raw JSON value of [feedback]. + * + * Unlike [feedback], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("metadata") fun metadata(): Metadata? = metadata + @JsonProperty("feedback") + @ExcludeMissing + fun _feedback(): JsonField> = feedback - /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ - @JsonProperty("source") fun source(): Source? = source + @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) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Feedback && - this.id == other.id && - this.scores == other.scores && - this.expected == other.expected && - this.comment == other.comment && - this.metadata == other.metadata && - this.source == other.source && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - scores, - expected, - comment, - metadata, - source, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Feedback{id=$id, scores=$scores, expected=$expected, comment=$comment, metadata=$metadata, source=$source, additionalProperties=$additionalProperties}" - companion object { + /** + * Returns a mutable builder for constructing an instance of [Body]. + * + * The following fields are required: + * ```java + * .feedback() + * ``` + */ @JvmStatic fun builder() = Builder() } - class Builder { + /** A builder for [Body]. */ + class Builder internal constructor() { - private var id: String? = null - private var scores: Scores? = null - private var expected: JsonValue? = null - private var comment: String? = null - private var metadata: Metadata? = null - private var source: Source? = null + private var feedback: JsonField>? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(feedback: Feedback) = apply { - this.id = feedback.id - this.scores = feedback.scores - this.expected = feedback.expected - this.comment = feedback.comment - this.metadata = feedback.metadata - this.source = feedback.source - additionalProperties(feedback.additionalProperties) + internal fun from(body: Body) = apply { + feedback = body.feedback.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() } - /** - * 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` - */ - @JsonProperty("id") fun id(id: String) = apply { this.id = id } - - /** - * 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 - */ - @JsonProperty("scores") fun scores(scores: Scores) = apply { this.scores = scores } + /** A list of project logs feedback items */ + fun feedback(feedback: List) = feedback(JsonField.of(feedback)) /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not + * 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. */ - @JsonProperty("expected") - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** An optional comment string to log about the project logs event */ - @JsonProperty("comment") fun comment(comment: String) = apply { this.comment = comment } + fun feedback(feedback: JsonField>) = apply { + this.feedback = feedback.map { it.toMutableList() } + } /** - * 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. + * Adds a single [FeedbackProjectLogsItem] to [Builder.feedback]. + * + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("metadata") - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } - - /** The source of the feedback. Must be one of "external" (default), "app", or "api" */ - @JsonProperty("source") fun source(source: Source) = apply { this.source = source } + 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() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Feedback = - Feedback( - checkNotNull(id) { "`id` is required but was not set" }, - scores, - expected, - comment, - metadata, - source, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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. - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + /** + * 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(), + ) + } - companion object { + private var validated: Boolean = false - @JvmStatic fun builder() = Builder() + fun validate(): Body = apply { + if (validated) { + return@apply } - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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) - } + feedback().forEach { it.validate() } + validated = true + } - fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - } /** - * 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 + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { + @JvmSynthetic + internal fun validity(): Int = + (feedback.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) - @JvmStatic fun builder() = Builder() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } + return other is Body && + feedback == other.feedback && + additionalProperties == other.additionalProperties } - class Source - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Source && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val APP = Source(JsonField.of("app")) - - @JvmField val API = Source(JsonField.of("api")) - - @JvmField val EXTERNAL = Source(JsonField.of("external")) + private val hashCode: Int by lazy { Objects.hash(feedback, additionalProperties) } - @JvmStatic fun of(value: String) = Source(JsonField.of(value)) - } + override fun hashCode(): Int = hashCode - enum class Known { - APP, - API, - EXTERNAL, - } + override fun toString() = + "Body{feedback=$feedback, additionalProperties=$additionalProperties}" + } - enum class Value { - APP, - API, - EXTERNAL, - _UNKNOWN, - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun value(): Value = - when (this) { - APP -> Value.APP - API -> Value.API - EXTERNAL -> Value.EXTERNAL - else -> Value._UNKNOWN - } + return other is ProjectLogFeedbackParams && + projectId == other.projectId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } - fun known(): Known = - when (this) { - APP -> Known.APP - API -> Known.API - EXTERNAL -> Known.EXTERNAL - else -> throw BraintrustInvalidDataException("Unknown Source: $value") - } + override fun hashCode(): Int = + Objects.hash(projectId, body, additionalHeaders, additionalQueryParams) - fun asString(): String = _value().asStringOrThrow() - } - } + override fun toString() = + "ProjectLogFeedbackParams{projectId=$projectId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index 456fa8fa..8ee83088 --- 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,120 +2,131 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with the + * parameters in the URL query rather than in the request body. For more complex queries, use the + * `POST /btql` endpoint. + */ class ProjectLogFetchParams -constructor( - private val projectId: String, +private constructor( + private val projectId: String?, private val limit: Long?, private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { - - fun projectId(): String = projectId - + private val maxXactId: String?, + private val version: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** + * 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(): Optional = Optional.ofNullable(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(): Optional = Optional.ofNullable(maxRootSpanId) - fun maxXactId(): Optional = Optional.ofNullable(maxXactId) - - fun version(): Optional = Optional.ofNullable(version) - - @JvmSynthetic - internal fun getQueryParams(): Map> { - val params = mutableMapOf>() - this.limit?.let { params.put("limit", listOf(it.toString())) } - this.maxRootSpanId?.let { params.put("max_root_span_id", listOf(it.toString())) } - this.maxXactId?.let { params.put("max_xact_id", listOf(it.toString())) } - this.version?.let { params.put("version", listOf(it.toString())) } - params.putAll(additionalQueryParams) - return params.toUnmodifiable() - } - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectLogFetchParams && - this.projectId == other.projectId && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } - - override fun hashCode(): Int { - return Objects.hash( - projectId, - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams, - additionalHeaders, - ) - } - - override fun toString() = - "ProjectLogFetchParams{projectId=$projectId, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + /** + * 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(): Optional = Optional.ofNullable(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(): Optional = Optional.ofNullable(version) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + @JvmStatic fun none(): ProjectLogFetchParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectLogFetchParams]. */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ProjectLogFetchParams]. */ + class Builder internal constructor() { private var projectId: String? = null private var limit: Long? = null private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + private var maxXactId: String? = null + private var version: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() @JvmSynthetic internal fun from(projectLogFetchParams: ProjectLogFetchParams) = apply { - this.projectId = projectLogFetchParams.projectId - this.limit = projectLogFetchParams.limit - this.maxRootSpanId = projectLogFetchParams.maxRootSpanId - this.maxXactId = projectLogFetchParams.maxXactId - this.version = projectLogFetchParams.version - additionalQueryParams(projectLogFetchParams.additionalQueryParams) - additionalHeaders(projectLogFetchParams.additionalHeaders) + projectId = projectLogFetchParams.projectId + limit = projectLogFetchParams.limit + maxRootSpanId = projectLogFetchParams.maxRootSpanId + maxXactId = projectLogFetchParams.maxXactId + version = projectLogFetchParams.version + additionalHeaders = projectLogFetchParams.additionalHeaders.toBuilder() + additionalQueryParams = projectLogFetchParams.additionalQueryParams.toBuilder() } /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) /** + * 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, @@ -128,80 +139,224 @@ constructor( * with more individual rows than the specified limit if you are fetching events containing * traces. */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(limit: Long?) = apply { this.limit = limit } /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. */ - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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: Long) = apply { this.maxXactId = maxXactId } + fun maxRootSpanId(maxRootSpanId: String?) = apply { this.maxRootSpanId = maxRootSpanId } + + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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 version(version: Long) = apply { this.version = version } + fun maxXactId(maxXactId: String?) = apply { this.maxXactId = maxXactId } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + /** 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. + */ + fun version(version: String?) = apply { this.version = version } + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [ProjectLogFetchParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ProjectLogFetchParams = ProjectLogFetchParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, + projectId, limit, maxRootSpanId, maxXactId, version, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + } + + return other is ProjectLogFetchParams && + projectId == other.projectId && + limit == other.limit && + maxRootSpanId == other.maxRootSpanId && + maxXactId == other.maxXactId && + version == other.version && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + projectId, + limit, + maxRootSpanId, + maxXactId, + version, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ProjectLogFetchParams{projectId=$projectId, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 old mode 100644 new mode 100755 index a90335fa..4099db79 --- 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 @@ -4,88 +4,226 @@ 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.toUnmodifiable +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the + * parameters in the request body rather than in the URL query. For more complex queries, use the + * `POST /btql` endpoint. + */ class ProjectLogFetchPostParams -constructor( - private val projectId: String, - private val filters: List?, - private val limit: Long?, - private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun projectId(): String = projectId - - fun filters(): Optional> = Optional.ofNullable(filters) - - fun limit(): Optional = Optional.ofNullable(limit) - - fun maxRootSpanId(): Optional = Optional.ofNullable(maxRootSpanId) - - fun maxXactId(): Optional = Optional.ofNullable(maxXactId) - - fun version(): Optional = Optional.ofNullable(version) - - @JvmSynthetic - internal fun getBody(): ProjectLogFetchPostBody { - return ProjectLogFetchPostBody( - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalBodyProperties, - ) +private constructor( + private val projectId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun cursor(): Optional = body.cursor() + + /** + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun limit(): Optional = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxRootSpanId(): Optional = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun maxXactId(): Optional = body.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 = body.version() + + /** + * Returns the raw JSON value of [cursor]. + * + * Unlike [cursor], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _cursor(): JsonField = body._cursor() + + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _limit(): JsonField = body._limit() + + /** + * Returns the raw JSON value of [maxRootSpanId]. + * + * Unlike [maxRootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxRootSpanId(): JsonField = body._maxRootSpanId() + + /** + * Returns the raw JSON value of [maxXactId]. + * + * Unlike [maxXactId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _maxXactId(): JsonField = body._maxXactId() + + /** + * Returns the raw JSON value of [version]. + * + * Unlike [version], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _version(): JsonField = body._version() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectLogFetchPostParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of [ProjectLogFetchPostParams]. + */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [ProjectLogFetchPostParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" + @JvmSynthetic + internal fun from(projectLogFetchPostParams: ProjectLogFetchPostParams) = apply { + projectId = projectLogFetchPostParams.projectId + body = projectLogFetchPostParams.body.toBuilder() + additionalHeaders = projectLogFetchPostParams.additionalHeaders.toBuilder() + additionalQueryParams = projectLogFetchPostParams.additionalQueryParams.toBuilder() } - } - @JsonDeserialize(builder = ProjectLogFetchPostBody.Builder::class) - @NoAutoDetect - class ProjectLogFetchPostBody - internal constructor( - private val filters: List?, - private val limit: Long?, - private val maxRootSpanId: String?, - private val maxXactId: Long?, - private val version: Long?, - private val additionalProperties: Map, - ) { + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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 + * latest to earliest. + * + * The string can be obtained directly from the `cursor` property of the previous fetch + * query + */ + fun cursor(cursor: String?) = apply { body.cursor(cursor) } - private var hashCode: Int = 0 + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * 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. */ - @JsonProperty("filters") fun filters(): List? = filters + fun cursor(cursor: JsonField) = apply { body.cursor(cursor) } /** + * 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, @@ -98,259 +236,282 @@ constructor( * with more individual rows than the specified limit if you are fetching events containing * traces. */ - @JsonProperty("limit") fun limit(): Long? = limit + fun limit(limit: Long?) = apply { body.limit(limit) } /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. */ - @JsonProperty("max_root_span_id") fun maxRootSpanId(): String? = maxRootSpanId + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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. */ - @JsonProperty("max_xact_id") fun maxXactId(): Long? = maxXactId + fun limit(limit: JsonField) = apply { body.limit(limit) } /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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. */ - @JsonProperty("version") fun version(): Long? = version + fun maxRootSpanId(maxRootSpanId: String?) = apply { body.maxRootSpanId(maxRootSpanId) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - fun toBuilder() = Builder().from(this) + /** + * 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 { + body.maxRootSpanId(maxRootSpanId) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** + * 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?) = apply { body.maxXactId(maxXactId) } - return other is ProjectLogFetchPostBody && - this.filters == other.filters && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties, - ) - } - return hashCode - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - override fun toString() = - "ProjectLogFetchPostBody{filters=$filters, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" + /** + * 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 { body.maxXactId(maxXactId) } - companion object { + /** + * 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?) = apply { body.version(version) } - @JvmStatic fun builder() = Builder() - } + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) - class Builder { + /** + * 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) } - private var filters: List? = null - private var limit: Long? = null - private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - @JvmSynthetic - internal fun from(projectLogFetchPostBody: ProjectLogFetchPostBody) = apply { - this.filters = projectLogFetchPostBody.filters - this.limit = projectLogFetchPostBody.limit - this.maxRootSpanId = projectLogFetchPostBody.maxRootSpanId - this.maxXactId = projectLogFetchPostBody.maxXactId - this.version = projectLogFetchPostBody.version - additionalProperties(projectLogFetchPostBody.additionalProperties) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters - * are supported, but we may add more in the future - */ - @JsonProperty("filters") - fun filters(filters: List) = apply { this.filters = filters } + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - /** - * 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. - */ - @JsonProperty("limit") fun limit(limit: Long) = apply { this.limit = limit } + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) + } - /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine - * `max_root_span_id` as the maximum of the `root_span_id` field over all rows. See the - * documentation for `limit` for an overview of paginating fetch queries. - */ - @JsonProperty("max_root_span_id") - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` - * as the maximum of the `_xact_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. - */ - @JsonProperty("max_xact_id") - fun maxXactId(maxXactId: Long) = apply { this.maxXactId = maxXactId } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - /** - * You may specify a version id to retrieve a snapshot of the 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. - */ - @JsonProperty("version") fun version(version: Long) = apply { this.version = version } + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - fun build(): ProjectLogFetchPostBody = - ProjectLogFetchPostBody( - filters?.toUnmodifiable(), - limit, - maxRootSpanId, - maxXactId, - version, - additionalProperties.toUnmodifiable(), - ) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - } - fun _additionalQueryParams(): Map> = additionalQueryParams + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun _additionalHeaders(): Map> = additionalHeaders + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - fun _additionalBodyProperties(): Map = additionalBodyProperties + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - return other is ProjectLogFetchPostParams && - this.projectId == other.projectId && - this.filters == other.filters && - this.limit == other.limit && - this.maxRootSpanId == other.maxRootSpanId && - this.maxXactId == other.maxXactId && - this.version == other.version && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - override fun hashCode(): Int { - return Objects.hash( - projectId, - filters, - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - override fun toString() = - "ProjectLogFetchPostParams{projectId=$projectId, filters=$filters, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun toBuilder() = Builder().from(this) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - companion object { + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - @JvmStatic fun builder() = Builder() - } + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - @NoAutoDetect - class Builder { + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - private var projectId: String? = null - private var filters: MutableList = mutableListOf() - private var limit: Long? = null - private var maxRootSpanId: String? = null - private var maxXactId: Long? = null - private var version: Long? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - @JvmSynthetic - internal fun from(projectLogFetchPostParams: ProjectLogFetchPostParams) = apply { - this.projectId = projectLogFetchPostParams.projectId - this.filters(projectLogFetchPostParams.filters ?: listOf()) - this.limit = projectLogFetchPostParams.limit - this.maxRootSpanId = projectLogFetchPostParams.maxRootSpanId - this.maxXactId = projectLogFetchPostParams.maxXactId - this.version = projectLogFetchPostParams.version - additionalQueryParams(projectLogFetchPostParams.additionalQueryParams) - additionalHeaders(projectLogFetchPostParams.additionalHeaders) - additionalBodyProperties(projectLogFetchPostParams.additionalBodyProperties) + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + 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) + } /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * Returns an immutable instance of [ProjectLogFetchPostParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. */ - fun filters(filters: List) = apply { - this.filters.clear() - this.filters.addAll(filters) + fun build(): ProjectLogFetchPostParams = + ProjectLogFetchPostParams( + projectId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + /** - * A list of filters on the events to fetch. Currently, only path-lookup type filters are - * supported, but we may add more in the future + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun addFilter(filter: Filter) = apply { this.filters.add(filter) } + fun cursor(): Optional = cursor.getOptional("cursor") /** + * 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, @@ -362,279 +523,378 @@ 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun limit(limit: Long) = apply { this.limit = limit } + fun limit(): Optional = limit.getOptional("limit") /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_root_span_id` - * as the maximum of the `root_span_id` field over all rows. See the documentation for - * `limit` for an overview of paginating fetch queries. + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxRootSpanId(maxRootSpanId: String) = apply { this.maxRootSpanId = maxRootSpanId } + fun maxRootSpanId(): Optional = maxRootSpanId.getOptional("max_root_span_id") /** - * Together, `max_xact_id` and `max_root_span_id` form a cursor for paginating event - * fetches. Given a previous fetch with a list of rows, you can determine `max_xact_id` as - * the maximum of the `_xact_id` field over all rows. See the documentation for `limit` for - * an overview of paginating fetch queries. + * 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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). */ - fun maxXactId(maxXactId: Long) = apply { this.maxXactId = maxXactId } + fun maxXactId(): Optional = maxXactId.getOptional("max_xact_id") /** - * You may specify a version id to retrieve a snapshot of the 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. + * 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(version: Long) = apply { this.version = version } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } + fun version(): Optional = version.getOptional("version") - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + /** + * 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 - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + /** + * Returns the raw JSON value of [limit]. + * + * Unlike [limit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("limit") @ExcludeMissing fun _limit(): JsonField = limit - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + /** + * 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 removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + /** + * 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 additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } + /** + * 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 putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } + fun toBuilder() = Builder().from(this) - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + companion object { - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) - } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) + 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() + + @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 build(): ProjectLogFetchPostParams = - ProjectLogFetchPostParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - if (filters.size == 0) null else filters.toUnmodifiable(), - limit, - maxRootSpanId, - maxXactId, - version, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } + /** + * 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)) - /** - * A path-lookup filter describes an equality comparison against a specific sub-field in the - * event row. For instance, if you wish to filter on the value of `c` in `{"input": {"a": {"b": - * {"c": "hello"}}}}`, pass `path=["input", "a", "b", "c"]` and `value="hello"` - */ - @JsonDeserialize(builder = Filter.Builder::class) - @NoAutoDetect - class Filter - private constructor( - private val type: Type?, - private val path: List?, - private val value: JsonValue?, - private val additionalProperties: Map, - ) { + /** Alias for calling [Builder.cursor] with `cursor.orElse(null)`. */ + fun cursor(cursor: Optional) = cursor(cursor.getOrNull()) - private var hashCode: Int = 0 + /** + * 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 } - /** Denotes the type of filter as a path-lookup filter */ - @JsonProperty("type") fun type(): Type? = type + /** + * 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)) - /** - * List of fields describing the path to the value to be checked against. For instance, if - * you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": "hello"}}}}`, pass - * `path=["input", "a", "b", "c"]` - */ - @JsonProperty("path") fun path(): List? = path + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) - /** - * The value to compare equality-wise against the event value at the specified `path`. The - * value must be a "primitive", that is, any JSON-serializable object except for objects and - * arrays. For instance, if you wish to filter on the value of "input.a.b.c" in the object - * `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `value="hello"` - */ - @JsonProperty("value") fun value(): JsonValue? = value + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + /** + * 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 toBuilder() = Builder().from(this) + /** + * 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)) - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + /** Alias for calling [Builder.maxRootSpanId] with `maxRootSpanId.orElse(null)`. */ + fun maxRootSpanId(maxRootSpanId: Optional) = + maxRootSpanId(maxRootSpanId.getOrNull()) - return other is Filter && - this.type == other.type && - this.path == other.path && - this.value == other.value && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - type, - path, - value, - additionalProperties, - ) + /** + * 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 } - return hashCode - } - - override fun toString() = - "Filter{type=$type, path=$path, value=$value, additionalProperties=$additionalProperties}" - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var type: Type? = null - private var path: List? = null - private var value: JsonValue? = null - private var additionalProperties: MutableMap = mutableMapOf() + /** + * 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)) - @JvmSynthetic - internal fun from(filter: Filter) = apply { - this.type = filter.type - this.path = filter.path - this.value = filter.value - additionalProperties(filter.additionalProperties) - } + /** Alias for calling [Builder.maxXactId] with `maxXactId.orElse(null)`. */ + fun maxXactId(maxXactId: Optional) = maxXactId(maxXactId.getOrNull()) - /** Denotes the type of filter as a path-lookup filter */ - @JsonProperty("type") fun type(type: Type) = apply { this.type = type } + /** + * 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 } /** - * List of fields describing the path to the value to be checked against. For instance, - * if you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": - * "hello"}}}}`, pass `path=["input", "a", "b", "c"]` + * 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. */ - @JsonProperty("path") fun path(path: List) = apply { this.path = path } + fun version(version: String?) = version(JsonField.ofNullable(version)) + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) /** - * The value to compare equality-wise against the event value at the specified `path`. - * The value must be a "primitive", that is, any JSON-serializable object except for - * objects and arrays. For instance, if you wish to filter on the value of "input.a.b.c" - * in the object `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `value="hello"` + * 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. */ - @JsonProperty("value") fun value(value: JsonValue) = apply { this.value = value } + fun version(version: JsonField) = apply { this.version = version } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) + putAllAdditionalProperties(additionalProperties) } - @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) + additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map) = apply { this.additionalProperties.putAll(additionalProperties) } - fun build(): Filter = - Filter( - checkNotNull(type) { "`type` is required but was not set" }, - checkNotNull(path) { "`path` is required but was not set" }.toUnmodifiable(), - value, - additionalProperties.toUnmodifiable(), - ) - } + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + /** + * 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(), + ) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + private var validated: Boolean = false - return other is Type && this.value == other.value + fun validate(): Body = apply { + if (validated) { + return@apply } - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() + cursor() + limit() + maxRootSpanId() + maxXactId() + version() + validated = true + } - companion object { + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - @JvmField val PATH_LOOKUP = Type(JsonField.of("path_lookup")) + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @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) - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } - enum class Known { - PATH_LOOKUP, - } + return other is Body && + cursor == other.cursor && + limit == other.limit && + maxRootSpanId == other.maxRootSpanId && + maxXactId == other.maxXactId && + version == other.version && + additionalProperties == other.additionalProperties + } - enum class Value { - PATH_LOOKUP, - _UNKNOWN, - } + private val hashCode: Int by lazy { + Objects.hash(cursor, limit, maxRootSpanId, maxXactId, version, additionalProperties) + } - fun value(): Value = - when (this) { - PATH_LOOKUP -> Value.PATH_LOOKUP - else -> Value._UNKNOWN - } + override fun hashCode(): Int = hashCode - fun known(): Known = - when (this) { - PATH_LOOKUP -> Known.PATH_LOOKUP - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } + override fun toString() = + "Body{cursor=$cursor, limit=$limit, maxRootSpanId=$maxRootSpanId, maxXactId=$maxXactId, version=$version, additionalProperties=$additionalProperties}" + } - fun asString(): String = _value().asStringOrThrow() + override fun equals(other: Any?): Boolean { + if (this === other) { + return true } + + return other is ProjectLogFetchPostParams && + projectId == other.projectId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = + Objects.hash(projectId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectLogFetchPostParams{projectId=$projectId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostResponse.kt deleted file mode 100644 index 7604fa42..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostResponse.kt +++ /dev/null @@ -1,1482 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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 com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.time.OffsetDateTime -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = ProjectLogFetchPostResponse.Builder::class) -@NoAutoDetect -class ProjectLogFetchPostResponse -private constructor( - private val events: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** A list of fetched events */ - fun events(): List = events.getRequired("events") - - /** A list of fetched events */ - @JsonProperty("events") @ExcludeMissing fun _events() = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): ProjectLogFetchPostResponse = apply { - if (!validated) { - events().forEach { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectLogFetchPostResponse && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ProjectLogFetchPostResponse{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(projectLogFetchPostResponse: ProjectLogFetchPostResponse) = apply { - this.events = projectLogFetchPostResponse.events - additionalProperties(projectLogFetchPostResponse.additionalProperties) - } - - /** A list of fetched events */ - fun events(events: List) = events(JsonField.of(events)) - - /** A list of fetched events */ - @JsonProperty("events") - @ExcludeMissing - fun events(events: JsonField>) = apply { this.events = events } - - 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(): ProjectLogFetchPostResponse = - ProjectLogFetchPostResponse( - events.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } - - @JsonDeserialize(builder = Event.Builder::class) - @NoAutoDetect - class Event - private constructor( - private val id: JsonField, - private val _xactId: JsonField, - private val created: JsonField, - private val orgId: JsonField, - private val projectId: JsonField, - private val logId: JsonField, - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanId: JsonField, - private val spanParents: JsonField>, - private val rootSpanId: JsonField, - private val spanAttributes: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): String = id.getRequired("id") - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the project logs (see the `version` parameter) - */ - fun _xactId(): Long = _xactId.getRequired("_xact_id") - - /** The timestamp the project logs event was created */ - fun created(): Optional = - Optional.ofNullable(created.getNullable("created")) - - /** Unique id for the organization that the project belongs under */ - fun orgId(): String = orgId.getRequired("org_id") - - /** Unique identifier for the project */ - fun projectId(): String = projectId.getRequired("project_id") - - /** A literal 'g' which identifies the log as a project log */ - fun logId(): LogId = logId.getRequired("log_id") - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable object). - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question. - */ - fun output(): JsonValue = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate while digging - * into analyses. However, we may later use these values to re-score outputs or fine-tune - * your models. - */ - fun expected(): JsonValue = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare logs. - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * project logs event. Use "start" and "end" to track the time span over which the project - * logs event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) - - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) - - /** - * A unique identifier used to link different project logs events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - fun spanId(): String = spanId.getRequired("span_id") - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) - - /** The `span_id` of the root of the trace this project logs event belongs to */ - fun rootSpanId(): String = rootSpanId.getRequired("root_span_id") - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the project logs (see the `version` parameter) - */ - @JsonProperty("_xact_id") @ExcludeMissing fun __xactId() = _xactId - - /** The timestamp the project logs event was created */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Unique id for the organization that the project belongs under */ - @JsonProperty("org_id") @ExcludeMissing fun _orgId() = orgId - - /** Unique identifier for the project */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId - - /** A literal 'g' which identifies the log as a project log */ - @JsonProperty("log_id") @ExcludeMissing fun _logId() = logId - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable object). - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question. - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate while digging - * into analyses. However, we may later use these values to re-score outputs or fine-tune - * your models. - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare logs. - */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * project logs event. Use "start" and "end" to track the time span over which the project - * logs event was produced - */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics - - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context - - /** - * A unique identifier used to link different project logs events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - @JsonProperty("span_id") @ExcludeMissing fun _spanId() = spanId - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - @JsonProperty("span_parents") @ExcludeMissing fun _spanParents() = spanParents - - /** The `span_id` of the root of the trace this project logs event belongs to */ - @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId() = rootSpanId - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Event = apply { - if (!validated) { - id() - _xactId() - created() - orgId() - projectId() - logId() - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanId() - spanParents() - rootSpanId() - spanAttributes().map { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Event && - this.id == other.id && - this._xactId == other._xactId && - this.created == other.created && - this.orgId == other.orgId && - this.projectId == other.projectId && - this.logId == other.logId && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanId == other.spanId && - this.spanParents == other.spanParents && - this.rootSpanId == other.rootSpanId && - this.spanAttributes == other.spanAttributes && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - _xactId, - created, - orgId, - projectId, - logId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents, - rootSpanId, - spanAttributes, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Event{id=$id, _xactId=$_xactId, created=$created, orgId=$orgId, projectId=$projectId, logId=$logId, input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanId=$spanId, spanParents=$spanParents, rootSpanId=$rootSpanId, spanAttributes=$spanAttributes, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var id: JsonField = JsonMissing.of() - private var _xactId: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var orgId: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var logId: JsonField = JsonMissing.of() - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanId: JsonField = JsonMissing.of() - private var spanParents: JsonField> = JsonMissing.of() - private var rootSpanId: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(event: Event) = apply { - this.id = event.id - this._xactId = event._xactId - this.created = event.created - this.orgId = event.orgId - this.projectId = event.projectId - this.logId = event.logId - this.input = event.input - this.output = event.output - this.expected = event.expected - this.scores = event.scores - this.metadata = event.metadata - this.metrics = event.metrics - this.context = event.context - this.spanId = event.spanId - this.spanParents = event.spanParents - this.rootSpanId = event.rootSpanId - this.spanAttributes = event.spanAttributes - additionalProperties(event.additionalProperties) - } - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the project logs (see the `version` - * parameter) - */ - fun _xactId(_xactId: Long) = _xactId(JsonField.of(_xactId)) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the project logs (see the `version` - * parameter) - */ - @JsonProperty("_xact_id") - @ExcludeMissing - fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } - - /** The timestamp the project logs event was created */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** The timestamp the project logs event was created */ - @JsonProperty("created") - @ExcludeMissing - fun created(created: JsonField) = apply { this.created = created } - - /** Unique id for the organization that the project belongs under */ - fun orgId(orgId: String) = orgId(JsonField.of(orgId)) - - /** Unique id for the organization that the project belongs under */ - @JsonProperty("org_id") - @ExcludeMissing - fun orgId(orgId: JsonField) = apply { this.orgId = orgId } - - /** Unique identifier for the project */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** A literal 'g' which identifies the log as a project log */ - fun logId(logId: LogId) = logId(JsonField.of(logId)) - - /** A literal 'g' which identifies the log as a project log */ - @JsonProperty("log_id") - @ExcludeMissing - fun logId(logId: JsonField) = apply { this.logId = logId } - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question. - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * while digging into analyses. However, we may later use these values to re-score - * outputs or fine-tune your models. - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** - * A unique identifier used to link different project logs events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - fun spanId(spanId: String) = spanId(JsonField.of(spanId)) - - /** - * A unique identifier used to link different project logs events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - @JsonProperty("span_id") - @ExcludeMissing - fun spanId(spanId: JsonField) = apply { this.spanId = spanId } - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty - * for the root span of a trace, and should most often contain just one parent element - * for subspans - */ - fun spanParents(spanParents: List) = spanParents(JsonField.of(spanParents)) - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty - * for the root span of a trace, and should most often contain just one parent element - * for subspans - */ - @JsonProperty("span_parents") - @ExcludeMissing - fun spanParents(spanParents: JsonField>) = apply { - this.spanParents = spanParents - } - - /** The `span_id` of the root of the trace this project logs event belongs to */ - fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) - - /** The `span_id` of the root of the trace this project logs event belongs to */ - @JsonProperty("root_span_id") - @ExcludeMissing - fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - 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(): Event = - Event( - id, - _xactId, - created, - orgId, - projectId, - logId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents.map { it.toUnmodifiable() }, - rootSpanId, - spanAttributes, - additionalProperties.toUnmodifiable(), - ) - } - - class LogId - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is LogId && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val G = LogId(JsonField.of("g")) - - @JvmStatic fun of(value: String) = LogId(JsonField.of(value)) - } - - enum class Known { - G, - } - - enum class Value { - G, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - G -> Value.G - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - G -> Known.G - else -> throw BraintrustInvalidDataException("Unknown LogId: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - - /** - * 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 - */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the project logs event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the project logs event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the project logs event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") @ExcludeMissing fun _callerFilename() = callerFilename - - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } - - /** The function in code which created the project logs event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) - - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } - - /** Name of the file in code where the project logs event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) - - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } - - /** Line of code where the project logs event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) - - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } - - 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(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * project logs event. Use "start" and "end" to track the time span over which the project - * logs event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare logs. - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchResponse.kt deleted file mode 100644 index 429c38f2..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogFetchResponse.kt +++ /dev/null @@ -1,1482 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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 com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.time.OffsetDateTime -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = ProjectLogFetchResponse.Builder::class) -@NoAutoDetect -class ProjectLogFetchResponse -private constructor( - private val events: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** A list of fetched events */ - fun events(): List = events.getRequired("events") - - /** A list of fetched events */ - @JsonProperty("events") @ExcludeMissing fun _events() = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): ProjectLogFetchResponse = apply { - if (!validated) { - events().forEach { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectLogFetchResponse && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ProjectLogFetchResponse{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(projectLogFetchResponse: ProjectLogFetchResponse) = apply { - this.events = projectLogFetchResponse.events - additionalProperties(projectLogFetchResponse.additionalProperties) - } - - /** A list of fetched events */ - fun events(events: List) = events(JsonField.of(events)) - - /** A list of fetched events */ - @JsonProperty("events") - @ExcludeMissing - fun events(events: JsonField>) = apply { this.events = events } - - 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(): ProjectLogFetchResponse = - ProjectLogFetchResponse( - events.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } - - @JsonDeserialize(builder = Event.Builder::class) - @NoAutoDetect - class Event - private constructor( - private val id: JsonField, - private val _xactId: JsonField, - private val created: JsonField, - private val orgId: JsonField, - private val projectId: JsonField, - private val logId: JsonField, - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanId: JsonField, - private val spanParents: JsonField>, - private val rootSpanId: JsonField, - private val spanAttributes: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust will - * generate one for you - */ - fun id(): String = id.getRequired("id") - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the project logs (see the `version` parameter) - */ - fun _xactId(): Long = _xactId.getRequired("_xact_id") - - /** The timestamp the project logs event was created */ - fun created(): Optional = - Optional.ofNullable(created.getNullable("created")) - - /** Unique id for the organization that the project belongs under */ - fun orgId(): String = orgId.getRequired("org_id") - - /** Unique identifier for the project */ - fun projectId(): String = projectId.getRequired("project_id") - - /** A literal 'g' which identifies the log as a project log */ - fun logId(): LogId = logId.getRequired("log_id") - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable object). - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question. - */ - fun output(): JsonValue = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate while digging - * into analyses. However, we may later use these values to re-score outputs or fine-tune - * your models. - */ - fun expected(): JsonValue = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare logs. - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - fun metadata(): Optional = Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * project logs event. Use "start" and "end" to track the time span over which the project - * logs event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) - - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) - - /** - * A unique identifier used to link different project logs events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - fun spanId(): String = spanId.getRequired("span_id") - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - fun spanParents(): Optional> = - Optional.ofNullable(spanParents.getNullable("span_parents")) - - /** The `span_id` of the root of the trace this project logs event belongs to */ - fun rootSpanId(): String = rootSpanId.getRequired("root_span_id") - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust will - * generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be used - * to retrieve a versioned snapshot of the project logs (see the `version` parameter) - */ - @JsonProperty("_xact_id") @ExcludeMissing fun __xactId() = _xactId - - /** The timestamp the project logs event was created */ - @JsonProperty("created") @ExcludeMissing fun _created() = created - - /** Unique id for the organization that the project belongs under */ - @JsonProperty("org_id") @ExcludeMissing fun _orgId() = orgId - - /** Unique identifier for the project */ - @JsonProperty("project_id") @ExcludeMissing fun _projectId() = projectId - - /** A literal 'g' which identifies the log as a project log */ - @JsonProperty("log_id") @ExcludeMissing fun _logId() = logId - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable object). - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or not. - * For example, in an app that generates SQL queries, the `output` should be the _result_ of - * the SQL query generated by the model, not the query itself, because there may be multiple - * valid queries that answer a single question. - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently does - * not compare `output` to `expected` for you, since there are so many different ways to do - * that correctly. Instead, these values are just used to help you navigate while digging - * into analyses. However, we may later use these values to re-score outputs or fine-tune - * your models. - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare logs. - */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * project logs event. Use "start" and "end" to track the time span over which the project - * logs event was produced - */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics - - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context - - /** - * A unique identifier used to link different project logs events together as part of a full - * trace. See the [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for - * full details on tracing - */ - @JsonProperty("span_id") @ExcludeMissing fun _spanId() = spanId - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty for - * the root span of a trace, and should most often contain just one parent element for - * subspans - */ - @JsonProperty("span_parents") @ExcludeMissing fun _spanParents() = spanParents - - /** The `span_id` of the root of the trace this project logs event belongs to */ - @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId() = rootSpanId - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Event = apply { - if (!validated) { - id() - _xactId() - created() - orgId() - projectId() - logId() - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanId() - spanParents() - rootSpanId() - spanAttributes().map { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Event && - this.id == other.id && - this._xactId == other._xactId && - this.created == other.created && - this.orgId == other.orgId && - this.projectId == other.projectId && - this.logId == other.logId && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanId == other.spanId && - this.spanParents == other.spanParents && - this.rootSpanId == other.rootSpanId && - this.spanAttributes == other.spanAttributes && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - id, - _xactId, - created, - orgId, - projectId, - logId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents, - rootSpanId, - spanAttributes, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Event{id=$id, _xactId=$_xactId, created=$created, orgId=$orgId, projectId=$projectId, logId=$logId, input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanId=$spanId, spanParents=$spanParents, rootSpanId=$rootSpanId, spanAttributes=$spanAttributes, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var id: JsonField = JsonMissing.of() - private var _xactId: JsonField = JsonMissing.of() - private var created: JsonField = JsonMissing.of() - private var orgId: JsonField = JsonMissing.of() - private var projectId: JsonField = JsonMissing.of() - private var logId: JsonField = JsonMissing.of() - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanId: JsonField = JsonMissing.of() - private var spanParents: JsonField> = JsonMissing.of() - private var rootSpanId: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(event: Event) = apply { - this.id = event.id - this._xactId = event._xactId - this.created = event.created - this.orgId = event.orgId - this.projectId = event.projectId - this.logId = event.logId - this.input = event.input - this.output = event.output - this.expected = event.expected - this.scores = event.scores - this.metadata = event.metadata - this.metrics = event.metrics - this.context = event.context - this.spanId = event.spanId - this.spanParents = event.spanParents - this.rootSpanId = event.rootSpanId - this.spanAttributes = event.spanAttributes - additionalProperties(event.additionalProperties) - } - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the project logs (see the `version` - * parameter) - */ - fun _xactId(_xactId: Long) = _xactId(JsonField.of(_xactId)) - - /** - * The transaction id of an event is unique to the network operation that processed the - * event insertion. Transaction ids are monotonically increasing over time and can be - * used to retrieve a versioned snapshot of the project logs (see the `version` - * parameter) - */ - @JsonProperty("_xact_id") - @ExcludeMissing - fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } - - /** The timestamp the project logs event was created */ - fun created(created: OffsetDateTime) = created(JsonField.of(created)) - - /** The timestamp the project logs event was created */ - @JsonProperty("created") - @ExcludeMissing - fun created(created: JsonField) = apply { this.created = created } - - /** Unique id for the organization that the project belongs under */ - fun orgId(orgId: String) = orgId(JsonField.of(orgId)) - - /** Unique id for the organization that the project belongs under */ - @JsonProperty("org_id") - @ExcludeMissing - fun orgId(orgId: JsonField) = apply { this.orgId = orgId } - - /** Unique identifier for the project */ - fun projectId(projectId: String) = projectId(JsonField.of(projectId)) - - /** Unique identifier for the project */ - @JsonProperty("project_id") - @ExcludeMissing - fun projectId(projectId: JsonField) = apply { this.projectId = projectId } - - /** A literal 'g' which identifies the log as a project log */ - fun logId(logId: LogId) = logId(JsonField.of(logId)) - - /** A literal 'g' which identifies the log as a project log */ - @JsonProperty("log_id") - @ExcludeMissing - fun logId(logId: JsonField) = apply { this.logId = logId } - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question. - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * while digging into analyses. However, we may later use these values to re-score - * outputs or fine-tune your models. - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** - * A unique identifier used to link different project logs events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - fun spanId(spanId: String) = spanId(JsonField.of(spanId)) - - /** - * A unique identifier used to link different project logs events together as part of a - * full trace. See the - * [tracing guide](https://www.braintrustdata.com/docs/guides/tracing) for full details - * on tracing - */ - @JsonProperty("span_id") - @ExcludeMissing - fun spanId(spanId: JsonField) = apply { this.spanId = spanId } - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty - * for the root span of a trace, and should most often contain just one parent element - * for subspans - */ - fun spanParents(spanParents: List) = spanParents(JsonField.of(spanParents)) - - /** - * An array of the parent `span_ids` of this project logs event. This should be empty - * for the root span of a trace, and should most often contain just one parent element - * for subspans - */ - @JsonProperty("span_parents") - @ExcludeMissing - fun spanParents(spanParents: JsonField>) = apply { - this.spanParents = spanParents - } - - /** The `span_id` of the root of the trace this project logs event belongs to */ - fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) - - /** The `span_id` of the root of the trace this project logs event belongs to */ - @JsonProperty("root_span_id") - @ExcludeMissing - fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - 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(): Event = - Event( - id, - _xactId, - created, - orgId, - projectId, - logId, - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanId, - spanParents.map { it.toUnmodifiable() }, - rootSpanId, - spanAttributes, - additionalProperties.toUnmodifiable(), - ) - } - - class LogId - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is LogId && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val G = LogId(JsonField.of("g")) - - @JvmStatic fun of(value: String) = LogId(JsonField.of(value)) - } - - enum class Known { - G, - } - - enum class Value { - G, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - G -> Value.G - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - G -> Known.G - else -> throw BraintrustInvalidDataException("Unknown LogId: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - - /** - * 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 - */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the project logs event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the project logs event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the project logs event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") @ExcludeMissing fun _callerFilename() = callerFilename - - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } - - /** The function in code which created the project logs event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) - - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } - - /** Name of the file in code where the project logs event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) - - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } - - /** Line of code where the project logs event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) - - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } - - 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(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything else that would be - * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, - * but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced the - * project logs event. Use "start" and "end" to track the time span over which the project - * logs event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the project logs - * event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to what - * you expect and diagnose failures. For example, a summarization app might have one score - * that tells you how accurate the summary is, and another that measures the word similarity - * between the generated and grouth truth summary. The word similarity score could help you - * determine whether the summarization was covering similar concepts or not. You can use - * these scores to help you sort, filter, and compare logs. - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } -} 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 old mode 100644 new mode 100755 index 209c89e9..c242c2bc --- 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 @@ -2,2979 +2,469 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.BaseDeserializer -import com.braintrustdata.api.core.BaseSerializer 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.getOrThrow -import com.braintrustdata.api.core.toUnmodifiable +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.toImmutable import com.braintrustdata.api.errors.BraintrustInvalidDataException -import com.braintrustdata.api.models.* import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Insert a set of events into the project logs */ class ProjectLogInsertParams -constructor( - private val projectId: String, - private val events: List, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun projectId(): String = projectId - - fun events(): List = events - - @JvmSynthetic - internal fun getBody(): ProjectLogInsertBody { - return ProjectLogInsertBody(events, additionalBodyProperties) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } - } - - @JsonDeserialize(builder = ProjectLogInsertBody.Builder::class) - @NoAutoDetect - class ProjectLogInsertBody - internal constructor( - private val events: List?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** A list of project logs events to insert */ - @JsonProperty("events") fun events(): List? = events - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectLogInsertBody && - this.events == other.events && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(events, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ProjectLogInsertBody{events=$events, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var events: List? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(projectLogInsertBody: ProjectLogInsertBody) = apply { - this.events = projectLogInsertBody.events - additionalProperties(projectLogInsertBody.additionalProperties) - } - - /** A list of project logs events to insert */ - @JsonProperty("events") fun events(events: List) = apply { this.events = events } - - 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(): ProjectLogInsertBody = - ProjectLogInsertBody( - checkNotNull(events) { "`events` is required but was not set" } - .toUnmodifiable(), - additionalProperties.toUnmodifiable() - ) - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectLogInsertParams && - this.projectId == other.projectId && - this.events == other.events && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int { - return Objects.hash( - projectId, - events, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "ProjectLogInsertParams{projectId=$projectId, events=$events, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" +private constructor( + private val projectId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** + * 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 = body.events() + + /** + * Returns the raw JSON value of [events]. + * + * Unlike [events], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _events(): JsonField> = body._events() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams fun toBuilder() = Builder().from(this) companion object { + /** + * Returns a mutable builder for constructing an instance of [ProjectLogInsertParams]. + * + * The following fields are required: + * ```java + * .events() + * ``` + */ @JvmStatic fun builder() = Builder() } - @NoAutoDetect - class Builder { + /** A builder for [ProjectLogInsertParams]. */ + class Builder internal constructor() { private var projectId: String? = null - private var events: MutableList = mutableListOf() - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + 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(projectLogInsertParams: ProjectLogInsertParams) = apply { - this.projectId = projectLogInsertParams.projectId - this.events(projectLogInsertParams.events) - additionalQueryParams(projectLogInsertParams.additionalQueryParams) - additionalHeaders(projectLogInsertParams.additionalHeaders) - additionalBodyProperties(projectLogInsertParams.additionalBodyProperties) + projectId = projectLogInsertParams.projectId + body = projectLogInsertParams.body.toBuilder() + additionalHeaders = projectLogInsertParams.additionalHeaders.toBuilder() + additionalQueryParams = projectLogInsertParams.additionalQueryParams.toBuilder() } /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + fun projectId(projectId: String?) = apply { this.projectId = projectId } - /** A list of project logs events to insert */ - fun events(events: List) = apply { - this.events.clear() - this.events.addAll(events) - } + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [events] + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } /** A list of project logs events to insert */ - fun addEvent(event: Event) = apply { this.events.add(event) } + fun events(events: List) = apply { body.events(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 { body.events(events) } + + /** + * Adds a single [InsertProjectLogsEvent] to [events]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addEvent(event: InsertProjectLogsEvent) = apply { body.addEvent(event) } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } fun additionalHeaders(additionalHeaders: Map>) = apply { this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + putAllAdditionalHeaders(additionalHeaders) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun build(): ProjectLogInsertParams = - ProjectLogInsertParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - checkNotNull(events) { "`events` is required but was not set" }.toUnmodifiable(), - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - @JsonDeserialize(using = Event.Deserializer::class) - @JsonSerialize(using = Event.Serializer::class) - class Event - private constructor( - private val insertProjectLogsEventReplace: InsertProjectLogsEventReplace? = null, - private val insertProjectLogsEventMerge: InsertProjectLogsEventMerge? = null, - private val _json: JsonValue? = null, - ) { + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - private var validated: Boolean = false + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } - fun insertProjectLogsEventReplace(): Optional = - Optional.ofNullable(insertProjectLogsEventReplace) - fun insertProjectLogsEventMerge(): Optional = - Optional.ofNullable(insertProjectLogsEventMerge) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } - fun isInsertProjectLogsEventReplace(): Boolean = insertProjectLogsEventReplace != null - fun isInsertProjectLogsEventMerge(): Boolean = insertProjectLogsEventMerge != null + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun asInsertProjectLogsEventReplace(): InsertProjectLogsEventReplace = - insertProjectLogsEventReplace.getOrThrow("insertProjectLogsEventReplace") - fun asInsertProjectLogsEventMerge(): InsertProjectLogsEventMerge = - insertProjectLogsEventMerge.getOrThrow("insertProjectLogsEventMerge") + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun _json(): Optional = Optional.ofNullable(_json) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } - fun accept(visitor: Visitor): T { - return when { - insertProjectLogsEventReplace != null -> - visitor.visitInsertProjectLogsEventReplace(insertProjectLogsEventReplace) - insertProjectLogsEventMerge != null -> - visitor.visitInsertProjectLogsEventMerge(insertProjectLogsEventMerge) - else -> visitor.unknown(_json) - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun validate(): Event = apply { - if (!validated) { - if (insertProjectLogsEventReplace == null && insertProjectLogsEventMerge == null) { - throw BraintrustInvalidDataException("Unknown Event: $_json") - } - insertProjectLogsEventReplace?.validate() - insertProjectLogsEventMerge?.validate() - validated = true - } + 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 other is Event && - this.insertProjectLogsEventReplace == other.insertProjectLogsEventReplace && - this.insertProjectLogsEventMerge == other.insertProjectLogsEventMerge + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) } - override fun hashCode(): Int { - return Objects.hash(insertProjectLogsEventReplace, insertProjectLogsEventMerge) + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) } - override fun toString(): String { - return when { - insertProjectLogsEventReplace != null -> - "Event{insertProjectLogsEventReplace=$insertProjectLogsEventReplace}" - insertProjectLogsEventMerge != null -> - "Event{insertProjectLogsEventMerge=$insertProjectLogsEventMerge}" - _json != null -> "Event{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Event") - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) } - companion object { + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - @JvmStatic - fun ofInsertProjectLogsEventReplace( - insertProjectLogsEventReplace: InsertProjectLogsEventReplace - ) = Event(insertProjectLogsEventReplace = insertProjectLogsEventReplace) + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - @JvmStatic - fun ofInsertProjectLogsEventMerge( - insertProjectLogsEventMerge: InsertProjectLogsEventMerge - ) = Event(insertProjectLogsEventMerge = insertProjectLogsEventMerge) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) } - interface Visitor { - - fun visitInsertProjectLogsEventReplace( - insertProjectLogsEventReplace: InsertProjectLogsEventReplace - ): T + /** + * Returns an immutable instance of [ProjectLogInsertParams]. + * + * 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(): ProjectLogInsertParams = + ProjectLogInsertParams( + projectId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } - fun visitInsertProjectLogsEventMerge( - insertProjectLogsEventMerge: InsertProjectLogsEventMerge - ): T + fun _body(): Body = body - fun unknown(json: JsonValue?): T { - throw BraintrustInvalidDataException("Unknown Event: $json") - } + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId ?: "" + else -> "" } - class Deserializer : BaseDeserializer(Event::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Event { - val json = JsonValue.fromJsonNode(node) - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return Event(insertProjectLogsEventReplace = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return Event(insertProjectLogsEventMerge = it, _json = json) - } + override fun _headers(): Headers = additionalHeaders - return Event(_json = json) - } - } + override fun _queryParams(): QueryParams = additionalQueryParams - class Serializer : BaseSerializer(Event::class) { - - override fun serialize( - value: Event, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.insertProjectLogsEventReplace != null -> - generator.writeObject(value.insertProjectLogsEventReplace) - value.insertProjectLogsEventMerge != null -> - generator.writeObject(value.insertProjectLogsEventMerge) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Event") - } - } - } + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val events: JsonField>, + private val additionalProperties: MutableMap, + ) { - @JsonDeserialize(builder = InsertProjectLogsEventReplace.Builder::class) - @NoAutoDetect - class InsertProjectLogsEventReplace + @JsonCreator private constructor( - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanAttributes: JsonField, - private val id: JsonField, - private val _objectDelete: JsonField, - private val _isMerge: JsonField, - private val _parentId: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question. - */ - fun output(): JsonValue = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * while digging into analyses. However, we may later use these values to re-score - * outputs or fine-tune your models. - */ - fun expected(): JsonValue = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) - - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) + @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 - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) + fun toBuilder() = Builder().from(this) - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - fun _isMerge(): Optional = - Optional.ofNullable(_isMerge.getNullable("_is_merge")) + companion object { /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical relationships - * are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). + * Returns a mutable builder for constructing an instance of [Body]. * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", - * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the - * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": - * "What comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, - * only the root span row `"abc"` will show up in the summary view. You can view the - * full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" - * row. - */ - fun _parentId(): Optional = - Optional.ofNullable(_parentId.getNullable("_parent_id")) - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question. - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * while digging into analyses. However, we may later use these values to re-score - * outputs or fine-tune your models. - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. + * The following fields are required: + * ```java + * .events() + * ``` */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics + @JvmStatic fun builder() = Builder() + } - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context + /** A builder for [Body]. */ + class Builder internal constructor() { - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes + private var events: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id + @JvmSynthetic + internal fun from(body: Body) = apply { + events = body.events.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - @JsonProperty("_object_delete") @ExcludeMissing fun __objectDelete() = _objectDelete + /** A list of project logs events to insert */ + fun events(events: List) = events(JsonField.of(events)) /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row + * Sets [Builder.events] to an arbitrary JSON value. * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` + * 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. */ - @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge() = _isMerge + fun events(events: JsonField>) = apply { + this.events = events.map { it.toMutableList() } + } /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical relationships - * are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). + * Adds a single [InsertProjectLogsEvent] to [events]. * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", - * "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the - * parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": - * "What comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, - * only the root span row `"abc"` will show up in the summary view. You can view the - * full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" - * row. + * @throws IllegalStateException if the field was previously set to a non-list. */ - @JsonProperty("_parent_id") @ExcludeMissing fun __parentId() = _parentId - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): InsertProjectLogsEventReplace = apply { - if (!validated) { - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanAttributes().map { it.validate() } - id() - _objectDelete() - _isMerge() - _parentId() - validated = true - } + fun addEvent(event: InsertProjectLogsEvent) = apply { + events = + (events ?: JsonField.of(mutableListOf())).also { + checkKnown("events", it).add(event) + } } - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InsertProjectLogsEventReplace && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanAttributes == other.spanAttributes && - this.id == other.id && - this._objectDelete == other._objectDelete && - this._isMerge == other._isMerge && - this._parentId == other._parentId && - this.additionalProperties == other.additionalProperties + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - _objectDelete, - _isMerge, - _parentId, - additionalProperties, - ) - } - return hashCode + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) } - override fun toString() = - "InsertProjectLogsEventReplace{input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanAttributes=$spanAttributes, id=$id, _objectDelete=$_objectDelete, _isMerge=$_isMerge, _parentId=$_parentId, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) } - class Builder { - - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var id: JsonField = JsonMissing.of() - private var _objectDelete: JsonField = JsonMissing.of() - private var _isMerge: JsonField = JsonMissing.of() - private var _parentId: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(insertProjectLogsEventReplace: InsertProjectLogsEventReplace) = - apply { - this.input = insertProjectLogsEventReplace.input - this.output = insertProjectLogsEventReplace.output - this.expected = insertProjectLogsEventReplace.expected - this.scores = insertProjectLogsEventReplace.scores - this.metadata = insertProjectLogsEventReplace.metadata - this.metrics = insertProjectLogsEventReplace.metrics - this.context = insertProjectLogsEventReplace.context - this.spanAttributes = insertProjectLogsEventReplace.spanAttributes - this.id = insertProjectLogsEventReplace.id - this._objectDelete = insertProjectLogsEventReplace._objectDelete - this._isMerge = insertProjectLogsEventReplace._isMerge - this._parentId = insertProjectLogsEventReplace._parentId - additionalProperties(insertProjectLogsEventReplace.additionalProperties) - } - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct - * or not. For example, in an app that generates SQL queries, the `output` should be - * the _result_ of the SQL query generated by the model, not the query itself, - * because there may be multiple valid queries that answer a single question. - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd - * compare to `output` to determine if your `output` value is correct or not. - * Braintrust currently does not compare `output` to `expected` for you, since there - * are so many different ways to do that correctly. Instead, these values are just - * used to help you navigate while digging into analyses. However, we may later use - * these values to re-score outputs or fine-tune your models. - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare logs. - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare logs. - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the project logs event. Use "start" and "end" to track the time span - * over which the project logs event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the project logs event. Use "start" and "end" to track the time span - * over which the project logs event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - /** - * A unique identifier for the project logs event. If you don't provide one, - * BrainTrust will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the project logs event. If you don't provide one, - * BrainTrust will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - fun _objectDelete(_objectDelete: Boolean) = - _objectDelete(JsonField.of(_objectDelete)) - - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - @JsonProperty("_object_delete") - @ExcludeMissing - fun _objectDelete(_objectDelete: JsonField) = apply { - this._objectDelete = _objectDelete - } - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - fun _isMerge(_isMerge: Boolean) = _isMerge(JsonField.of(_isMerge)) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - @JsonProperty("_is_merge") - @ExcludeMissing - fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } - - /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical - * relationships are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). - * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": - * "bar", "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a - * sub-span of the parent row by logging `{"_parent_id": "abc", "id": "llm_call", - * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": - * {"tokens": 1}}`. In the webapp, only the root span row `"abc"` will show up in - * the summary view. You can view the full trace hierarchy (in this case, the - * `"llm_call"` row) by clicking on the "abc" row. - */ - fun _parentId(_parentId: String) = _parentId(JsonField.of(_parentId)) - - /** - * Use the `_parent_id` field to create this row as a subspan of an existing row. It - * cannot be specified alongside `_is_merge=true`. Tracking hierarchical - * relationships are important for tracing (see the - * [guide](https://www.braintrustdata.com/docs/guides/tracing) for full details). - * - * For example, say we have logged a row `{"id": "abc", "input": "foo", "output": - * "bar", "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a - * sub-span of the parent row by logging `{"_parent_id": "abc", "id": "llm_call", - * "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": - * {"tokens": 1}}`. In the webapp, only the root span row `"abc"` will show up in - * the summary view. You can view the full trace hierarchy (in this case, the - * `"llm_call"` row) by clicking on the "abc" row. - */ - @JsonProperty("_parent_id") - @ExcludeMissing - fun _parentId(_parentId: JsonField) = apply { this._parentId = _parentId } - - 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 removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } - fun build(): InsertProjectLogsEventReplace = - InsertProjectLogsEventReplace( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - _objectDelete, - _isMerge, - _parentId, - additionalProperties.toUnmodifiable(), - ) + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) } /** - * 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 + * 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. */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the project logs event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the project logs event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the project logs event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun _callerFilename() = callerFilename - - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } + fun build(): Body = + Body( + checkRequired("events", events).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } - class Builder { + private var validated: Boolean = false - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() + fun validate(): Body = apply { + if (validated) { + return@apply + } - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } + events().forEach { it.validate() } + validated = true + } - /** The function in code which created the project logs event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } + /** + * Returns 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) - /** Name of the file in code where the project logs event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } + return other is Body && + events == other.events && + additionalProperties == other.additionalProperties + } - /** Line of code where the project logs event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) + private val hashCode: Int by lazy { Objects.hash(events, additionalProperties) } - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } + override fun hashCode(): Int = hashCode - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + override fun toString() = "Body{events=$events, additionalProperties=$additionalProperties}" + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } - fun putAllAdditionalProperties(additionalProperties: Map) = - apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } + return other is ProjectLogInsertParams && + projectId == other.projectId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { + override fun hashCode(): Int = + Objects.hash(projectId, body, additionalHeaders, additionalQueryParams) - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue - fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } - - @JsonDeserialize(builder = InsertProjectLogsEventMerge.Builder::class) - @NoAutoDetect - class InsertProjectLogsEventMerge - private constructor( - private val input: JsonValue, - private val output: JsonValue, - private val expected: JsonValue, - private val scores: JsonField, - private val metadata: JsonField, - private val metrics: JsonField, - private val context: JsonField, - private val spanAttributes: JsonField, - private val id: JsonField, - private val _objectDelete: JsonField, - private val _isMerge: JsonField, - private val _mergePaths: JsonField>>, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - fun input(): JsonValue = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question. - */ - fun output(): JsonValue = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * while digging into analyses. However, we may later use these values to re-score - * outputs or fine-tune your models. - */ - fun expected(): JsonValue = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - fun scores(): Optional = Optional.ofNullable(scores.getNullable("scores")) - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - fun metadata(): Optional = - Optional.ofNullable(metadata.getNullable("metadata")) - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - fun metrics(): Optional = Optional.ofNullable(metrics.getNullable("metrics")) - - /** - * 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 - */ - fun context(): Optional = Optional.ofNullable(context.getNullable("context")) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(): Optional = - Optional.ofNullable(spanAttributes.getNullable("span_attributes")) - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - fun id(): Optional = Optional.ofNullable(id.getNullable("id")) - - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - fun _objectDelete(): Optional = - Optional.ofNullable(_objectDelete.getNullable("_object_delete")) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - fun _isMerge(): Boolean = _isMerge.getRequired("_is_merge") - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only be - * specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where each - * path is a list of field names. The deep merge will not descend below any of the - * specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be - * `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, - * "output": {"d": 40}}`. In this case, due to the merge paths, we have replaced - * `input.a` and `output`, but have still deep-merged `input` and `input.c`. - */ - fun _mergePaths(): Optional>> = - Optional.ofNullable(_mergePaths.getNullable("_merge_paths")) - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - @JsonProperty("input") @ExcludeMissing fun _input() = input - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct or - * not. For example, in an app that generates SQL queries, the `output` should be the - * _result_ of the SQL query generated by the model, not the query itself, because there - * may be multiple valid queries that answer a single question. - */ - @JsonProperty("output") @ExcludeMissing fun _output() = output - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to - * `output` to determine if your `output` value is correct or not. Braintrust currently - * does not compare `output` to `expected` for you, since there are so many different - * ways to do that correctly. Instead, these values are just used to help you navigate - * while digging into analyses. However, we may later use these values to re-score - * outputs or fine-tune your models. - */ - @JsonProperty("expected") @ExcludeMissing fun _expected() = expected - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - @JsonProperty("scores") @ExcludeMissing fun _scores() = scores - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics - - /** - * 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 - */ - @JsonProperty("context") @ExcludeMissing fun _context() = context - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") @ExcludeMissing fun _spanAttributes() = spanAttributes - - /** - * A unique identifier for the project logs event. If you don't provide one, BrainTrust - * will generate one for you - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - @JsonProperty("_object_delete") @ExcludeMissing fun __objectDelete() = _objectDelete - - /** - * The `_is_merge` field controls how the row is merged with any existing row with the - * same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is deep-merged - * into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, - * "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": - * 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": - * 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the - * new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}` - */ - @JsonProperty("_is_merge") @ExcludeMissing fun __isMerge() = _isMerge - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only be - * specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where each - * path is a list of field names. The deep merge will not descend below any of the - * specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be - * `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, - * "output": {"d": 40}}`. In this case, due to the merge paths, we have replaced - * `input.a` and `output`, but have still deep-merged `input` and `input.c`. - */ - @JsonProperty("_merge_paths") @ExcludeMissing fun __mergePaths() = _mergePaths - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): InsertProjectLogsEventMerge = apply { - if (!validated) { - input() - output() - expected() - scores().map { it.validate() } - metadata().map { it.validate() } - metrics().map { it.validate() } - context().map { it.validate() } - spanAttributes().map { it.validate() } - id() - _objectDelete() - _isMerge() - _mergePaths() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is InsertProjectLogsEventMerge && - this.input == other.input && - this.output == other.output && - this.expected == other.expected && - this.scores == other.scores && - this.metadata == other.metadata && - this.metrics == other.metrics && - this.context == other.context && - this.spanAttributes == other.spanAttributes && - this.id == other.id && - this._objectDelete == other._objectDelete && - this._isMerge == other._isMerge && - this._mergePaths == other._mergePaths && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - _objectDelete, - _isMerge, - _mergePaths, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "InsertProjectLogsEventMerge{input=$input, output=$output, expected=$expected, scores=$scores, metadata=$metadata, metrics=$metrics, context=$context, spanAttributes=$spanAttributes, id=$id, _objectDelete=$_objectDelete, _isMerge=$_isMerge, _mergePaths=$_mergePaths, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var input: JsonValue = JsonMissing.of() - private var output: JsonValue = JsonMissing.of() - private var expected: JsonValue = JsonMissing.of() - private var scores: JsonField = JsonMissing.of() - private var metadata: JsonField = JsonMissing.of() - private var metrics: JsonField = JsonMissing.of() - private var context: JsonField = JsonMissing.of() - private var spanAttributes: JsonField = JsonMissing.of() - private var id: JsonField = JsonMissing.of() - private var _objectDelete: JsonField = JsonMissing.of() - private var _isMerge: JsonField = JsonMissing.of() - private var _mergePaths: JsonField>> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(insertProjectLogsEventMerge: InsertProjectLogsEventMerge) = - apply { - this.input = insertProjectLogsEventMerge.input - this.output = insertProjectLogsEventMerge.output - this.expected = insertProjectLogsEventMerge.expected - this.scores = insertProjectLogsEventMerge.scores - this.metadata = insertProjectLogsEventMerge.metadata - this.metrics = insertProjectLogsEventMerge.metrics - this.context = insertProjectLogsEventMerge.context - this.spanAttributes = insertProjectLogsEventMerge.spanAttributes - this.id = insertProjectLogsEventMerge.id - this._objectDelete = insertProjectLogsEventMerge._objectDelete - this._isMerge = insertProjectLogsEventMerge._isMerge - this._mergePaths = insertProjectLogsEventMerge._mergePaths - additionalProperties(insertProjectLogsEventMerge.additionalProperties) - } - - /** - * The arguments that uniquely define a user input(an arbitrary, JSON serializable - * object). - */ - @JsonProperty("input") - @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } - - /** - * The output of your application, including post-processing (an arbitrary, JSON - * serializable object), that allows you to determine whether the result is correct - * or not. For example, in an app that generates SQL queries, the `output` should be - * the _result_ of the SQL query generated by the model, not the query itself, - * because there may be multiple valid queries that answer a single question. - */ - @JsonProperty("output") - @ExcludeMissing - fun output(output: JsonValue) = apply { this.output = output } - - /** - * The ground truth value (an arbitrary, JSON serializable object) that you'd - * compare to `output` to determine if your `output` value is correct or not. - * Braintrust currently does not compare `output` to `expected` for you, since there - * are so many different ways to do that correctly. Instead, these values are just - * used to help you navigate while digging into analyses. However, we may later use - * these values to re-score outputs or fine-tune your models. - */ - @JsonProperty("expected") - @ExcludeMissing - fun expected(expected: JsonValue) = apply { this.expected = expected } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare logs. - */ - fun scores(scores: Scores) = scores(JsonField.of(scores)) - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give - * you a variety of signals that help you determine how accurate the outputs are - * compared to what you expect and diagnose failures. For example, a summarization - * app might have one score that tells you how accurate the summary is, and another - * that measures the word similarity between the generated and grouth truth summary. - * The word similarity score could help you determine whether the summarization was - * covering similar concepts or not. You can use these scores to help you sort, - * filter, and compare logs. - */ - @JsonProperty("scores") - @ExcludeMissing - fun scores(scores: JsonField) = apply { this.scores = scores } - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) - - /** - * 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 example, you could log the `prompt`, example's `id`, or - * anything else that would be useful to slice/dice later. The values in `metadata` - * can be any JSON-serializable type, but its keys must be strings - */ - @JsonProperty("metadata") - @ExcludeMissing - fun metadata(metadata: JsonField) = apply { this.metadata = metadata } - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the project logs event. Use "start" and "end" to track the time span - * over which the project logs event was produced - */ - fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) - - /** - * Metrics are numerical measurements tracking the execution of the code that - * produced the project logs event. Use "start" and "end" to track the time span - * over which the project logs event was produced - */ - @JsonProperty("metrics") - @ExcludeMissing - fun metrics(metrics: JsonField) = apply { this.metrics = metrics } - - /** - * 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 - */ - fun context(context: Context) = context(JsonField.of(context)) - - /** - * 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 - */ - @JsonProperty("context") - @ExcludeMissing - fun context(context: JsonField) = apply { this.context = context } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - fun spanAttributes(spanAttributes: SpanAttributes) = - spanAttributes(JsonField.of(spanAttributes)) - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonProperty("span_attributes") - @ExcludeMissing - fun spanAttributes(spanAttributes: JsonField) = apply { - this.spanAttributes = spanAttributes - } - - /** - * A unique identifier for the project logs event. If you don't provide one, - * BrainTrust will generate one for you - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * A unique identifier for the project logs event. If you don't provide one, - * BrainTrust will generate one for you - */ - @JsonProperty("id") - @ExcludeMissing - fun id(id: JsonField) = apply { this.id = id } - - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - fun _objectDelete(_objectDelete: Boolean) = - _objectDelete(JsonField.of(_objectDelete)) - - /** - * Pass `_object_delete=true` to mark the project logs event deleted. Deleted events - * will not show up in subsequent fetches for this project logs - */ - @JsonProperty("_object_delete") - @ExcludeMissing - fun _objectDelete(_objectDelete: JsonField) = apply { - this._objectDelete = _objectDelete - } - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - fun _isMerge(_isMerge: Boolean) = _isMerge(JsonField.of(_isMerge)) - - /** - * The `_is_merge` field controls how the row is merged with any existing row with - * the same id in the DB. By default (or when set to `false`), the existing row is - * completely replaced by the new row. When set to `true`, the new row is - * deep-merged into the existing row - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", - * "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": - * 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": - * {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": - * 20}}` - */ - @JsonProperty("_is_merge") - @ExcludeMissing - fun _isMerge(_isMerge: JsonField) = apply { this._isMerge = _isMerge } - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only - * be specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where - * each path is a list of field names. The deep merge will not descend below any of - * the specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will - * be `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": - * "baz"}, "output": {"d": 40}}`. In this case, due to the merge paths, we have - * replaced `input.a` and `output`, but have still deep-merged `input` and - * `input.c`. - */ - fun _mergePaths(_mergePaths: List>) = - _mergePaths(JsonField.of(_mergePaths)) - - /** - * The `_merge_paths` field allows controlling the depth of the merge. It can only - * be specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where - * each path is a list of field names. The deep merge will not descend below any of - * the specified merge paths. - * - * For example, say there is an existing row in the DB `{"id": "foo", "input": {"a": - * {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as - * `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": - * {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will - * be `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": - * "baz"}, "output": {"d": 40}}`. In this case, due to the merge paths, we have - * replaced `input.a` and `output`, but have still deep-merged `input` and - * `input.c`. - */ - @JsonProperty("_merge_paths") - @ExcludeMissing - fun _mergePaths(_mergePaths: JsonField>>) = apply { - this._mergePaths = _mergePaths - } - - 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(): InsertProjectLogsEventMerge = - InsertProjectLogsEventMerge( - input, - output, - expected, - scores, - metadata, - metrics, - context, - spanAttributes, - id, - _objectDelete, - _isMerge, - _mergePaths.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable(), - ) - } - - /** - * 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 - */ - @JsonDeserialize(builder = Context.Builder::class) - @NoAutoDetect - class Context - private constructor( - private val callerFunctionname: JsonField, - private val callerFilename: JsonField, - private val callerLineno: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** The function in code which created the project logs event */ - fun callerFunctionname(): Optional = - Optional.ofNullable(callerFunctionname.getNullable("caller_functionname")) - - /** Name of the file in code where the project logs event was created */ - fun callerFilename(): Optional = - Optional.ofNullable(callerFilename.getNullable("caller_filename")) - - /** Line of code where the project logs event was created */ - fun callerLineno(): Optional = - Optional.ofNullable(callerLineno.getNullable("caller_lineno")) - - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun _callerFunctionname() = callerFunctionname - - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun _callerFilename() = callerFilename - - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno() = callerLineno - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Context = apply { - if (!validated) { - callerFunctionname() - callerFilename() - callerLineno() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Context && - this.callerFunctionname == other.callerFunctionname && - this.callerFilename == other.callerFilename && - this.callerLineno == other.callerLineno && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Context{callerFunctionname=$callerFunctionname, callerFilename=$callerFilename, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var callerFunctionname: JsonField = JsonMissing.of() - private var callerFilename: JsonField = JsonMissing.of() - private var callerLineno: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(context: Context) = apply { - this.callerFunctionname = context.callerFunctionname - this.callerFilename = context.callerFilename - this.callerLineno = context.callerLineno - additionalProperties(context.additionalProperties) - } - - /** The function in code which created the project logs event */ - fun callerFunctionname(callerFunctionname: String) = - callerFunctionname(JsonField.of(callerFunctionname)) - - /** The function in code which created the project logs event */ - @JsonProperty("caller_functionname") - @ExcludeMissing - fun callerFunctionname(callerFunctionname: JsonField) = apply { - this.callerFunctionname = callerFunctionname - } - - /** Name of the file in code where the project logs event was created */ - fun callerFilename(callerFilename: String) = - callerFilename(JsonField.of(callerFilename)) - - /** Name of the file in code where the project logs event was created */ - @JsonProperty("caller_filename") - @ExcludeMissing - fun callerFilename(callerFilename: JsonField) = apply { - this.callerFilename = callerFilename - } - - /** Line of code where the project logs event was created */ - fun callerLineno(callerLineno: Long) = callerLineno(JsonField.of(callerLineno)) - - /** Line of code where the project logs event was created */ - @JsonProperty("caller_lineno") - @ExcludeMissing - fun callerLineno(callerLineno: JsonField) = apply { - this.callerLineno = callerLineno - } - - 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(): Context = - Context( - callerFunctionname, - callerFilename, - callerLineno, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * 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 example, you could log the `prompt`, example's `id`, or anything - * else that would be useful to slice/dice later. The values in `metadata` can be any - * JSON-serializable type, but its keys must be strings - */ - @JsonDeserialize(builder = Metadata.Builder::class) - @NoAutoDetect - class Metadata - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metadata = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metadata && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Metadata{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metadata: Metadata) = apply { - additionalProperties(metadata.additionalProperties) - } - - 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(): Metadata = Metadata(additionalProperties.toUnmodifiable()) - } - } - - /** - * Metrics are numerical measurements tracking the execution of the code that produced - * the project logs event. Use "start" and "end" to track the time span over which the - * project logs event was produced - */ - @JsonDeserialize(builder = Metrics.Builder::class) - @NoAutoDetect - class Metrics - private constructor( - private val start: JsonField, - private val end: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - fun start(): Optional = Optional.ofNullable(start.getNullable("start")) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - fun end(): Optional = Optional.ofNullable(end.getNullable("end")) - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event started - */ - @JsonProperty("start") @ExcludeMissing fun _start() = start - - /** - * A unix timestamp recording when the section of code which produced the project - * logs event finished - */ - @JsonProperty("end") @ExcludeMissing fun _end() = end - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Metrics = apply { - if (!validated) { - start() - end() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Metrics && - this.start == other.start && - this.end == other.end && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - start, - end, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "Metrics{start=$start, end=$end, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var start: JsonField = JsonMissing.of() - private var end: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(metrics: Metrics) = apply { - this.start = metrics.start - this.end = metrics.end - additionalProperties(metrics.additionalProperties) - } - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event started - */ - fun start(start: Double) = start(JsonField.of(start)) - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event started - */ - @JsonProperty("start") - @ExcludeMissing - fun start(start: JsonField) = apply { this.start = start } - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event finished - */ - fun end(end: Double) = end(JsonField.of(end)) - - /** - * A unix timestamp recording when the section of code which produced the - * project logs event finished - */ - @JsonProperty("end") - @ExcludeMissing - fun end(end: JsonField) = apply { this.end = end } - - 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(): Metrics = - Metrics( - start, - end, - additionalProperties.toUnmodifiable(), - ) - } - } - - /** - * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a - * variety of signals that help you determine how accurate the outputs are compared to - * what you expect and diagnose failures. For example, a summarization app might have - * one score that tells you how accurate the summary is, and another that measures the - * word similarity between the generated and grouth truth summary. The word similarity - * score could help you determine whether the summarization was covering similar - * concepts or not. You can use these scores to help you sort, filter, and compare logs. - */ - @JsonDeserialize(builder = Scores.Builder::class) - @NoAutoDetect - class Scores - private constructor( - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Scores = apply { - if (!validated) { - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Scores && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(additionalProperties) - } - return hashCode - } - - override fun toString() = "Scores{additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(scores: Scores) = apply { - additionalProperties(scores.additionalProperties) - } - - 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(): Scores = Scores(additionalProperties.toUnmodifiable()) - } - } - - /** Human-identifying attributes of the span, such as name, type, etc. */ - @JsonDeserialize(builder = SpanAttributes.Builder::class) - @NoAutoDetect - class SpanAttributes - private constructor( - private val name: JsonField, - private val type: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** Name of the span, for display purposes only */ - fun name(): Optional = Optional.ofNullable(name.getNullable("name")) - - /** Type of the span, for display purposes only */ - fun type(): Optional = Optional.ofNullable(type.getNullable("type")) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** Type of the span, for display purposes only */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): SpanAttributes = apply { - if (!validated) { - name() - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is SpanAttributes && - this.name == other.name && - this.type == other.type && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - type, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(spanAttributes: SpanAttributes) = apply { - this.name = spanAttributes.name - this.type = spanAttributes.type - additionalProperties(spanAttributes.additionalProperties) - } - - /** Name of the span, for display purposes only */ - fun name(name: String) = name(JsonField.of(name)) - - /** Name of the span, for display purposes only */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** Type of the span, for display purposes only */ - fun type(type: Type) = type(JsonField.of(type)) - - /** Type of the span, for display purposes only */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - 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(): SpanAttributes = - SpanAttributes( - name, - type, - additionalProperties.toUnmodifiable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) { - - @com.fasterxml.jackson.annotation.JsonValue - fun _value(): JsonField = value - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is Type && this.value == other.value - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - - companion object { - - @JvmField val LLM = Type(JsonField.of("llm")) - - @JvmField val SCORE = Type(JsonField.of("score")) - - @JvmField val FUNCTION = Type(JsonField.of("function")) - - @JvmField val EVAL = Type(JsonField.of("eval")) - - @JvmField val TASK = Type(JsonField.of("task")) - - @JvmField val TOOL = Type(JsonField.of("tool")) - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - } - - enum class Value { - LLM, - SCORE, - FUNCTION, - EVAL, - TASK, - TOOL, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - LLM -> Value.LLM - SCORE -> Value.SCORE - FUNCTION -> Value.FUNCTION - EVAL -> Value.EVAL - TASK -> Value.TASK - TOOL -> Value.TOOL - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - LLM -> Known.LLM - SCORE -> Known.SCORE - FUNCTION -> Known.FUNCTION - EVAL -> Known.EVAL - TASK -> Known.TASK - TOOL -> Known.TOOL - else -> throw BraintrustInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - } - } - } - } + override fun toString() = + "ProjectLogInsertParams{projectId=$projectId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogInsertResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogInsertResponse.kt deleted file mode 100644 index 57cb17fc..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogInsertResponse.kt +++ /dev/null @@ -1,122 +0,0 @@ -// 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.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -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.Objects - -@JsonDeserialize(builder = ProjectLogInsertResponse.Builder::class) -@NoAutoDetect -class ProjectLogInsertResponse -private constructor( - private val rowIds: JsonField>, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - private var hashCode: Int = 0 - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as input - */ - fun rowIds(): List = rowIds.getRequired("row_ids") - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as input - */ - @JsonProperty("row_ids") @ExcludeMissing fun _rowIds() = rowIds - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): ProjectLogInsertResponse = apply { - if (!validated) { - rowIds() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectLogInsertResponse && - this.rowIds == other.rowIds && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(rowIds, additionalProperties) - } - return hashCode - } - - override fun toString() = - "ProjectLogInsertResponse{rowIds=$rowIds, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var rowIds: JsonField> = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(projectLogInsertResponse: ProjectLogInsertResponse) = apply { - this.rowIds = projectLogInsertResponse.rowIds - additionalProperties(projectLogInsertResponse.additionalProperties) - } - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as - * input - */ - fun rowIds(rowIds: List) = rowIds(JsonField.of(rowIds)) - - /** - * The ids of all rows that were inserted, aligning one-to-one with the rows provided as - * input - */ - @JsonProperty("row_ids") - @ExcludeMissing - fun rowIds(rowIds: JsonField>) = apply { this.rowIds = rowIds } - - 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(): ProjectLogInsertResponse = - ProjectLogInsertResponse( - rowIds.map { it.toUnmodifiable() }, - additionalProperties.toUnmodifiable() - ) - } -} 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 new file mode 100755 index 00000000..49befc6b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectLogsEvent.kt @@ -0,0 +1,2104 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ProjectLogsEvent +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The transaction id of an event is unique to the network operation that processed the event + * insertion. Transaction ids are monotonically increasing over time and can be used to retrieve + * a versioned snapshot of the project logs (see the `version` parameter) + * + * @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 _xactId(): String = _xactId.getRequired("_xact_id") + + /** + * The timestamp the project logs event was created + * + * @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 created(): OffsetDateTime = created.getRequired("created") + + /** + * A literal 'g' which identifies the log as a project log + * + * @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 logId(): LogId = logId.getRequired("log_id") + + /** + * Unique id for the organization that the project 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 orgId(): String = orgId.getRequired("org_id") + + /** + * Unique identifier for 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 projectId(): String = projectId.getRequired("project_id") + + /** + * A unique identifier for the trace this project logs event belongs 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 rootSpanId(): String = rootSpanId.getRequired("root_span_id") + + /** + * A unique identifier used to link different project logs events together as part of a full + * trace. See the [tracing guide](https://www.braintrust.dev/docs/guides/tracing) for full + * details on tracing + * + * @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 spanId(): String = spanId.getRequired("span_id") + + /** + * 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun context(): Optional = context.getOptional("context") + + /** The error that occurred, if any. */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonValue = error + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does not + * compare `output` to `expected` for you, since there are so many different ways to do that + * correctly. Instead, these values are just used to help you navigate while digging into + * analyses. However, we may later use these values to re-score outputs or fine-tune your + * models. + */ + @JsonProperty("expected") @ExcludeMissing fun _expected(): JsonValue = expected + + /** The arguments that uniquely define a user input (an arbitrary, JSON serializable object). */ + @JsonProperty("input") @ExcludeMissing fun _input(): JsonValue = input + + /** + * Whether this span is a root span + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isRoot(): Optional = isRoot.getOptional("is_root") + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + * + * @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") + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * project logs event. Use "start" and "end" to track the time span over which the project logs + * event was produced + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metrics(): Optional = metrics.getOptional("metrics") + + /** + * Indicates the event was copied from another object. + * + * @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 output of your application, including post-processing (an arbitrary, JSON serializable + * object), that allows you to determine whether the result is correct or not. For example, in + * an app that generates SQL queries, the `output` should be the _result_ of the SQL query + * generated by the model, not the query itself, because there may be multiple valid queries + * that answer a single question. + */ + @JsonProperty("output") @ExcludeMissing fun _output(): JsonValue = output + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare logs. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scores(): Optional = scores.getOptional("scores") + + /** + * Human-identifying attributes of the span, such as name, type, etc. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 + * root span of a trace, and should most often contain just one parent element for subspans + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanParents(): Optional> = spanParents.getOptional("span_parents") + + /** + * A list of tags to log + * + * @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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_xactId]. + * + * Unlike [_xactId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_xact_id") @ExcludeMissing fun __xactId(): JsonField = _xactId + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [logId]. + * + * Unlike [logId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("log_id") @ExcludeMissing fun _logId(): JsonField = logId + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [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 [rootSpanId]. + * + * Unlike [rootSpanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("root_span_id") @ExcludeMissing fun _rootSpanId(): JsonField = rootSpanId + + /** + * Returns the raw JSON value of [spanId]. + * + * Unlike [spanId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_id") @ExcludeMissing fun _spanId(): JsonField = spanId + + /** + * Returns the raw JSON value of [context]. + * + * Unlike [context], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("context") @ExcludeMissing fun _context(): JsonField = context + + /** + * Returns the raw JSON value of [isRoot]. + * + * Unlike [isRoot], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("is_root") @ExcludeMissing fun _isRoot(): JsonField = isRoot + + /** + * 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 [metrics]. + * + * Unlike [metrics], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metrics") @ExcludeMissing fun _metrics(): JsonField = metrics + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [spanAttributes]. + * + * Unlike [spanAttributes], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_attributes") + @ExcludeMissing + fun _spanAttributes(): JsonField = spanAttributes + + /** + * Returns the raw JSON value of [spanParents]. + * + * Unlike [spanParents], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("span_parents") + @ExcludeMissing + fun _spanParents(): JsonField> = spanParents + + /** + * 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 [ProjectLogsEvent]. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .created() + * .logId() + * .orgId() + * .projectId() + * .rootSpanId() + * .spanId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectLogsEvent]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var _xactId: JsonField? = null + private var created: JsonField? = null + private var logId: JsonField? = null + private var orgId: JsonField? = null + private var projectId: JsonField? = null + private var rootSpanId: JsonField? = null + private var spanId: JsonField? = null + private var context: JsonField = JsonMissing.of() + private var error: JsonValue = JsonMissing.of() + private var expected: JsonValue = JsonMissing.of() + private var input: JsonValue = JsonMissing.of() + private var isRoot: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var metrics: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var output: JsonValue = JsonMissing.of() + private var scores: JsonField = JsonMissing.of() + private var spanAttributes: JsonField = JsonMissing.of() + private var spanParents: JsonField>? = null + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectLogsEvent: ProjectLogsEvent) = apply { + id = projectLogsEvent.id + _xactId = projectLogsEvent._xactId + created = projectLogsEvent.created + logId = projectLogsEvent.logId + orgId = projectLogsEvent.orgId + projectId = projectLogsEvent.projectId + rootSpanId = projectLogsEvent.rootSpanId + spanId = projectLogsEvent.spanId + context = projectLogsEvent.context + error = projectLogsEvent.error + expected = projectLogsEvent.expected + input = projectLogsEvent.input + isRoot = projectLogsEvent.isRoot + metadata = projectLogsEvent.metadata + metrics = projectLogsEvent.metrics + origin = projectLogsEvent.origin + output = projectLogsEvent.output + scores = projectLogsEvent.scores + spanAttributes = projectLogsEvent.spanAttributes + spanParents = projectLogsEvent.spanParents.map { it.toMutableList() } + tags = projectLogsEvent.tags.map { it.toMutableList() } + additionalProperties = projectLogsEvent.additionalProperties.toMutableMap() + } + + /** + * A unique identifier for the project logs event. If you don't provide one, BrainTrust will + * generate one for you + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The transaction id of an event is unique to the network operation that processed the + * event insertion. Transaction ids are monotonically increasing over time and can be used + * to retrieve a versioned snapshot of the project logs (see the `version` parameter) + */ + fun _xactId(_xactId: String) = _xactId(JsonField.of(_xactId)) + + /** + * Sets [Builder._xactId] to an arbitrary JSON value. + * + * You should usually call [Builder._xactId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } + + /** The timestamp the project logs event was created */ + fun created(created: OffsetDateTime) = created(JsonField.of(created)) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** A literal 'g' which identifies the log as a project log */ + fun logId(logId: LogId) = logId(JsonField.of(logId)) + + /** + * Sets [Builder.logId] to an arbitrary JSON value. + * + * You should usually call [Builder.logId] with a well-typed [LogId] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun logId(logId: JsonField) = apply { this.logId = logId } + + /** Unique id for the organization that the project belongs under */ + fun orgId(orgId: String) = orgId(JsonField.of(orgId)) + + /** + * 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 } + + /** Unique identifier for the project */ + 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 } + + /** A unique identifier for the trace this project logs event belongs to */ + fun rootSpanId(rootSpanId: String) = rootSpanId(JsonField.of(rootSpanId)) + + /** + * Sets [Builder.rootSpanId] to an arbitrary JSON value. + * + * You should usually call [Builder.rootSpanId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rootSpanId(rootSpanId: JsonField) = apply { this.rootSpanId = rootSpanId } + + /** + * A unique identifier used to link different project logs events together as part of a full + * trace. See the [tracing guide](https://www.braintrust.dev/docs/guides/tracing) for full + * details on tracing + */ + fun spanId(spanId: String) = spanId(JsonField.of(spanId)) + + /** + * Sets [Builder.spanId] to an arbitrary JSON value. + * + * You should usually call [Builder.spanId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun spanId(spanId: JsonField) = apply { this.spanId = spanId } + + /** + * 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 + */ + fun context(context: Context?) = context(JsonField.ofNullable(context)) + + /** Alias for calling [Builder.context] with `context.orElse(null)`. */ + fun context(context: Optional) = context(context.getOrNull()) + + /** + * Sets [Builder.context] to an arbitrary JSON value. + * + * You should usually call [Builder.context] with a well-typed [Context] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun context(context: JsonField) = apply { this.context = context } + + /** The error that occurred, if any. */ + fun error(error: JsonValue) = apply { this.error = error } + + /** + * The ground truth value (an arbitrary, JSON serializable object) that you'd compare to + * `output` to determine if your `output` value is correct or not. Braintrust currently does + * not compare `output` to `expected` for you, since there are so many different ways to do + * that correctly. Instead, these values are just used to help you navigate while digging + * into analyses. However, we may later use these values to re-score outputs or fine-tune + * your models. + */ + fun expected(expected: JsonValue) = apply { this.expected = expected } + + /** + * The arguments that uniquely define a user input (an arbitrary, JSON serializable object). + */ + fun input(input: JsonValue) = apply { this.input = input } + + /** Whether this span is a root span */ + fun isRoot(isRoot: Boolean?) = isRoot(JsonField.ofNullable(isRoot)) + + /** + * Alias for [Builder.isRoot]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun isRoot(isRoot: Boolean) = isRoot(isRoot as Boolean?) + + /** Alias for calling [Builder.isRoot] with `isRoot.orElse(null)`. */ + fun isRoot(isRoot: Optional) = isRoot(isRoot.getOrNull()) + + /** + * Sets [Builder.isRoot] to an arbitrary JSON value. + * + * You should usually call [Builder.isRoot] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun isRoot(isRoot: JsonField) = apply { this.isRoot = isRoot } + + /** + * 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 example, you could log the `prompt`, example's `id`, or anything else that would be + * useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, + * but its keys must be strings + */ + 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 } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * project logs event. Use "start" and "end" to track the time span over which the project + * logs event was produced + */ + fun metrics(metrics: Metrics?) = metrics(JsonField.ofNullable(metrics)) + + /** Alias for calling [Builder.metrics] with `metrics.orElse(null)`. */ + fun metrics(metrics: Optional) = metrics(metrics.getOrNull()) + + /** + * Sets [Builder.metrics] to an arbitrary JSON value. + * + * You should usually call [Builder.metrics] with a well-typed [Metrics] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun metrics(metrics: JsonField) = apply { this.metrics = metrics } + + /** Indicates the event was copied from another object. */ + fun origin(origin: ObjectReference?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * Sets [Builder.origin] to an arbitrary JSON value. + * + * You should usually call [Builder.origin] with a well-typed [ObjectReference] 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 } + + /** + * The output of your application, including post-processing (an arbitrary, JSON + * serializable object), that allows you to determine whether the result is correct or not. + * For example, in an app that generates SQL queries, the `output` should be the _result_ of + * the SQL query generated by the model, not the query itself, because there may be multiple + * valid queries that answer a single question. + */ + fun output(output: JsonValue) = apply { this.output = output } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a + * variety of signals that help you determine how accurate the outputs are compared to what + * you expect and diagnose failures. For example, a summarization app might have one score + * that tells you how accurate the summary is, and another that measures the word similarity + * between the generated and grouth truth summary. The word similarity score could help you + * determine whether the summarization was covering similar concepts or not. You can use + * these scores to help you sort, filter, and compare logs. + */ + fun scores(scores: Scores?) = scores(JsonField.ofNullable(scores)) + + /** Alias for calling [Builder.scores] with `scores.orElse(null)`. */ + fun scores(scores: Optional) = scores(scores.getOrNull()) + + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed [Scores] 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 } + + /** Human-identifying attributes of the span, such as name, type, etc. */ + fun spanAttributes(spanAttributes: SpanAttributes?) = + spanAttributes(JsonField.ofNullable(spanAttributes)) + + /** Alias for calling [Builder.spanAttributes] with `spanAttributes.orElse(null)`. */ + fun spanAttributes(spanAttributes: Optional) = + spanAttributes(spanAttributes.getOrNull()) + + /** + * Sets [Builder.spanAttributes] to an arbitrary JSON value. + * + * You should usually call [Builder.spanAttributes] with a well-typed [SpanAttributes] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanAttributes(spanAttributes: JsonField) = apply { + this.spanAttributes = spanAttributes + } + + /** + * An array of the parent `span_ids` of this project logs event. This should be empty for + * the root span of a trace, and should most often contain just one parent element for + * subspans + */ + fun spanParents(spanParents: List?) = spanParents(JsonField.ofNullable(spanParents)) + + /** Alias for calling [Builder.spanParents] with `spanParents.orElse(null)`. */ + fun spanParents(spanParents: Optional>) = spanParents(spanParents.getOrNull()) + + /** + * Sets [Builder.spanParents] to an arbitrary JSON value. + * + * You should usually call [Builder.spanParents] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun spanParents(spanParents: JsonField>) = apply { + this.spanParents = spanParents.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [spanParents]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSpanParent(spanParent: String) = apply { + spanParents = + (spanParents ?: JsonField.of(mutableListOf())).also { + checkKnown("spanParents", it).add(spanParent) + } + } + + /** A list of tags to log */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectLogsEvent]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .created() + * .logId() + * .orgId() + * .projectId() + * .rootSpanId() + * .spanId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectLogsEvent = + ProjectLogsEvent( + checkRequired("id", id), + checkRequired("_xactId", _xactId), + checkRequired("created", created), + checkRequired("logId", logId), + checkRequired("orgId", orgId), + checkRequired("projectId", projectId), + checkRequired("rootSpanId", rootSpanId), + checkRequired("spanId", spanId), + context, + error, + expected, + input, + isRoot, + metadata, + metrics, + origin, + output, + scores, + spanAttributes, + (spanParents ?: JsonMissing.of()).map { it.toImmutable() }, + (tags ?: JsonMissing.of()).map { it.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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val G = of("g") + + @JvmStatic fun of(value: String) = LogId(JsonField.of(value)) + } + + /** An enum containing [LogId]'s known values. */ + enum class Known { + G + } + + /** + * An enum containing [LogId]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [LogId] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + G, + /** An enum member indicating that [LogId] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + G -> Value.G + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + G -> Known.G + else -> throw BraintrustInvalidDataException("Unknown LogId: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is LogId && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** + * 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 + */ + class Context + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = callerFilename.getOptional("caller_filename") + + /** + * The function in code which created the project logs event + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun callerFunctionname(): Optional = + callerFunctionname.getOptional("caller_functionname") + + /** + * Line of 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 callerLineno(): Optional = callerLineno.getOptional("caller_lineno") + + /** + * Returns the raw JSON value of [callerFilename]. + * + * Unlike [callerFilename], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_filename") + @ExcludeMissing + fun _callerFilename(): JsonField = callerFilename + + /** + * Returns the raw JSON value of [callerFunctionname]. + * + * Unlike [callerFunctionname], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonField = callerFunctionname + + /** + * Returns the raw JSON value of [callerLineno]. + * + * Unlike [callerLineno], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("caller_lineno") + @ExcludeMissing + fun _callerLineno(): JsonField = callerLineno + + @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 [Context]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Context]. */ + class Builder internal constructor() { + + private var callerFilename: JsonField = JsonMissing.of() + private var callerFunctionname: JsonField = JsonMissing.of() + private var callerLineno: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(context: Context) = apply { + callerFilename = context.callerFilename + callerFunctionname = context.callerFunctionname + callerLineno = context.callerLineno + additionalProperties = context.additionalProperties.toMutableMap() + } + + /** Name of the file in code where the project logs event was created */ + fun callerFilename(callerFilename: String?) = + callerFilename(JsonField.ofNullable(callerFilename)) + + /** Alias for calling [Builder.callerFilename] with `callerFilename.orElse(null)`. */ + fun callerFilename(callerFilename: Optional) = + callerFilename(callerFilename.getOrNull()) + + /** + * Sets [Builder.callerFilename] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFilename] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFilename(callerFilename: JsonField) = apply { + this.callerFilename = callerFilename + } + + /** The function in code which created the project logs event */ + fun callerFunctionname(callerFunctionname: String?) = + callerFunctionname(JsonField.ofNullable(callerFunctionname)) + + /** + * Alias for calling [Builder.callerFunctionname] with + * `callerFunctionname.orElse(null)`. + */ + fun callerFunctionname(callerFunctionname: Optional) = + callerFunctionname(callerFunctionname.getOrNull()) + + /** + * Sets [Builder.callerFunctionname] to an arbitrary JSON value. + * + * You should usually call [Builder.callerFunctionname] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerFunctionname(callerFunctionname: JsonField) = apply { + this.callerFunctionname = callerFunctionname + } + + /** Line of code where the project logs event was created */ + fun callerLineno(callerLineno: Long?) = callerLineno(JsonField.ofNullable(callerLineno)) + + /** + * Alias for [Builder.callerLineno]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun callerLineno(callerLineno: Long) = callerLineno(callerLineno as Long?) + + /** Alias for calling [Builder.callerLineno] with `callerLineno.orElse(null)`. */ + fun callerLineno(callerLineno: Optional) = callerLineno(callerLineno.getOrNull()) + + /** + * Sets [Builder.callerLineno] to an arbitrary JSON value. + * + * You should usually call [Builder.callerLineno] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun callerLineno(callerLineno: JsonField) = apply { + this.callerLineno = callerLineno + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Context]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Context = + Context( + callerFilename, + callerFunctionname, + callerLineno, + 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 + } + + return other is Context && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(callerFilename, callerFunctionname, callerLineno, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Context{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, additionalProperties=$additionalProperties}" + } + + /** + * 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 + * example, you could log the `prompt`, example's `id`, or anything else that would be useful to + * slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys + * must be strings + */ + class Metadata + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = model.getOptional("model") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + @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 [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var model: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + model = metadata.model + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + /** The model used for this example */ + fun model(model: String?) = model(JsonField.ofNullable(model)) + + /** Alias for calling [Builder.model] with `model.orElse(null)`. */ + fun model(model: Optional) = model(model.getOrNull()) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(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 + } + + return other is Metadata && + model == other.model && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(model, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metadata{model=$model, additionalProperties=$additionalProperties}" + } + + /** + * Metrics are numerical measurements tracking the execution of the code that produced the + * project logs event. Use "start" and "end" to track the time span over which the project logs + * event was produced + */ + class Metrics + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + fun _callerFilename(): JsonValue = callerFilename + + /** This metric is deprecated */ + @JsonProperty("caller_functionname") + @ExcludeMissing + fun _callerFunctionname(): JsonValue = callerFunctionname + + /** This metric is deprecated */ + @JsonProperty("caller_lineno") @ExcludeMissing fun _callerLineno(): JsonValue = callerLineno + + /** + * The number of tokens in the completion generated by the model (only set if this is an LLM + * span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun completionTokens(): Optional = completionTokens.getOptional("completion_tokens") + + /** + * A unix timestamp recording when the section of code which produced the project logs event + * finished + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun end(): Optional = end.getOptional("end") + + /** + * The number of tokens in the prompt used to generate the project logs event (only set if + * this is an LLM span) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun promptTokens(): Optional = promptTokens.getOptional("prompt_tokens") + + /** + * A unix timestamp recording when the section of code which produced the project logs event + * started + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun start(): Optional = start.getOptional("start") + + /** + * The total number of tokens in the input and output of the project logs event. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun tokens(): Optional = tokens.getOptional("tokens") + + /** + * Returns the raw JSON value of [completionTokens]. + * + * Unlike [completionTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("completion_tokens") + @ExcludeMissing + fun _completionTokens(): JsonField = completionTokens + + /** + * Returns the raw JSON value of [end]. + * + * Unlike [end], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end + + /** + * Returns the raw JSON value of [promptTokens]. + * + * Unlike [promptTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("prompt_tokens") + @ExcludeMissing + fun _promptTokens(): JsonField = promptTokens + + /** + * Returns the raw JSON value of [start]. + * + * Unlike [start], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start + + /** + * Returns the raw JSON value of [tokens]. + * + * Unlike [tokens], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tokens") @ExcludeMissing fun _tokens(): JsonField = tokens + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metrics]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metrics]. */ + class Builder internal constructor() { + + private var callerFilename: JsonValue = JsonMissing.of() + private var callerFunctionname: JsonValue = JsonMissing.of() + private var callerLineno: JsonValue = JsonMissing.of() + private var completionTokens: JsonField = JsonMissing.of() + private var end: JsonField = JsonMissing.of() + private var promptTokens: JsonField = JsonMissing.of() + private var start: JsonField = JsonMissing.of() + private var tokens: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metrics: Metrics) = apply { + callerFilename = metrics.callerFilename + callerFunctionname = metrics.callerFunctionname + callerLineno = metrics.callerLineno + completionTokens = metrics.completionTokens + end = metrics.end + promptTokens = metrics.promptTokens + start = metrics.start + tokens = metrics.tokens + additionalProperties = metrics.additionalProperties.toMutableMap() + } + + /** This metric is deprecated */ + fun callerFilename(callerFilename: JsonValue) = apply { + this.callerFilename = callerFilename + } + + /** This metric is deprecated */ + fun callerFunctionname(callerFunctionname: JsonValue) = apply { + this.callerFunctionname = callerFunctionname + } + + /** This metric is deprecated */ + fun callerLineno(callerLineno: JsonValue) = apply { this.callerLineno = callerLineno } + + /** + * The number of tokens in the completion generated by the model (only set if this is an + * LLM span) + */ + fun completionTokens(completionTokens: Long?) = + completionTokens(JsonField.ofNullable(completionTokens)) + + /** + * Alias for [Builder.completionTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun completionTokens(completionTokens: Long) = + completionTokens(completionTokens as Long?) + + /** + * Alias for calling [Builder.completionTokens] with `completionTokens.orElse(null)`. + */ + fun completionTokens(completionTokens: Optional) = + completionTokens(completionTokens.getOrNull()) + + /** + * Sets [Builder.completionTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.completionTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun completionTokens(completionTokens: JsonField) = apply { + this.completionTokens = completionTokens + } + + /** + * A unix timestamp recording when the section of code which produced the project logs + * event finished + */ + fun end(end: Double?) = end(JsonField.ofNullable(end)) + + /** + * Alias for [Builder.end]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun end(end: Double) = end(end as Double?) + + /** Alias for calling [Builder.end] with `end.orElse(null)`. */ + fun end(end: Optional) = end(end.getOrNull()) + + /** + * Sets [Builder.end] to an arbitrary JSON value. + * + * You should usually call [Builder.end] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun end(end: JsonField) = apply { this.end = end } + + /** + * The number of tokens in the prompt used to generate the project logs event (only set + * if this is an LLM span) + */ + fun promptTokens(promptTokens: Long?) = promptTokens(JsonField.ofNullable(promptTokens)) + + /** + * Alias for [Builder.promptTokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun promptTokens(promptTokens: Long) = promptTokens(promptTokens as Long?) + + /** Alias for calling [Builder.promptTokens] with `promptTokens.orElse(null)`. */ + fun promptTokens(promptTokens: Optional) = promptTokens(promptTokens.getOrNull()) + + /** + * Sets [Builder.promptTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.promptTokens] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptTokens(promptTokens: JsonField) = apply { + this.promptTokens = promptTokens + } + + /** + * A unix timestamp recording when the section of code which produced the project logs + * event started + */ + fun start(start: Double?) = start(JsonField.ofNullable(start)) + + /** + * Alias for [Builder.start]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun start(start: Double) = start(start as Double?) + + /** Alias for calling [Builder.start] with `start.orElse(null)`. */ + fun start(start: Optional) = start(start.getOrNull()) + + /** + * Sets [Builder.start] to an arbitrary JSON value. + * + * You should usually call [Builder.start] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun start(start: JsonField) = apply { this.start = start } + + /** The total number of tokens in the input and output of the project logs event. */ + fun tokens(tokens: Long?) = tokens(JsonField.ofNullable(tokens)) + + /** + * Alias for [Builder.tokens]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun tokens(tokens: Long) = tokens(tokens as Long?) + + /** Alias for calling [Builder.tokens] with `tokens.orElse(null)`. */ + fun tokens(tokens: Optional) = tokens(tokens.getOrNull()) + + /** + * Sets [Builder.tokens] to an arbitrary JSON value. + * + * You should usually call [Builder.tokens] with a well-typed [Long] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tokens(tokens: JsonField) = apply { this.tokens = tokens } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metrics]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metrics = + Metrics( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + 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 + } + + return other is Metrics && + callerFilename == other.callerFilename && + callerFunctionname == other.callerFunctionname && + callerLineno == other.callerLineno && + completionTokens == other.completionTokens && + end == other.end && + promptTokens == other.promptTokens && + start == other.start && + tokens == other.tokens && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + callerFilename, + callerFunctionname, + callerLineno, + completionTokens, + end, + promptTokens, + start, + tokens, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Metrics{callerFilename=$callerFilename, callerFunctionname=$callerFunctionname, callerLineno=$callerLineno, completionTokens=$completionTokens, end=$end, promptTokens=$promptTokens, start=$start, tokens=$tokens, additionalProperties=$additionalProperties}" + } + + /** + * A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety + * of signals that help you determine how accurate the outputs are compared to what you expect + * and diagnose failures. For example, a summarization app might have one score that tells you + * how accurate the summary is, and another that measures the word similarity between the + * generated and grouth truth summary. The word similarity score could help you determine + * whether the summarization was covering similar concepts or not. You can use these scores to + * help you sort, filter, and compare logs. + */ + class Scores + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Scores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scores: Scores) = apply { + additionalProperties = scores.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 [Scores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Scores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Scores{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectLogsEvent && + id == other.id && + _xactId == other._xactId && + created == other.created && + logId == other.logId && + orgId == other.orgId && + projectId == other.projectId && + rootSpanId == other.rootSpanId && + spanId == other.spanId && + context == other.context && + error == other.error && + expected == other.expected && + input == other.input && + isRoot == other.isRoot && + metadata == other.metadata && + metrics == other.metrics && + origin == other.origin && + output == other.output && + scores == other.scores && + spanAttributes == other.spanAttributes && + spanParents == other.spanParents && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _xactId, + created, + logId, + orgId, + projectId, + rootSpanId, + spanId, + context, + error, + expected, + input, + isRoot, + metadata, + metrics, + origin, + output, + scores, + spanAttributes, + spanParents, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectLogsEvent{id=$id, _xactId=$_xactId, created=$created, logId=$logId, orgId=$orgId, projectId=$projectId, rootSpanId=$rootSpanId, spanId=$spanId, context=$context, error=$error, expected=$expected, input=$input, isRoot=$isRoot, metadata=$metadata, metrics=$metrics, origin=$origin, output=$output, scores=$scores, spanAttributes=$spanAttributes, spanParents=$spanParents, tags=$tags, additionalProperties=$additionalProperties}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectReplaceParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectReplaceParams.kt deleted file mode 100644 index 3dec7fc4..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectReplaceParams.kt +++ /dev/null @@ -1,278 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -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.toUnmodifiable -import com.braintrustdata.api.models.* -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.Objects -import java.util.Optional - -class ProjectReplaceParams -constructor( - private val name: String, - private val orgName: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { - - fun name(): String = name - - fun orgName(): Optional = Optional.ofNullable(orgName) - - @JvmSynthetic - internal fun getBody(): ProjectReplaceBody { - return ProjectReplaceBody( - name, - orgName, - additionalBodyProperties, - ) - } - - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams - - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders - - @JsonDeserialize(builder = ProjectReplaceBody.Builder::class) - @NoAutoDetect - class ProjectReplaceBody - internal constructor( - private val name: String?, - private val orgName: String?, - private val additionalProperties: Map, - ) { - - private var hashCode: Int = 0 - - /** Name of the project */ - @JsonProperty("name") fun name(): String? = 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. - */ - @JsonProperty("org_name") fun orgName(): String? = orgName - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun toBuilder() = Builder().from(this) - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectReplaceBody && - this.name == other.name && - this.orgName == other.orgName && - this.additionalProperties == other.additionalProperties - } - - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = - Objects.hash( - name, - orgName, - additionalProperties, - ) - } - return hashCode - } - - override fun toString() = - "ProjectReplaceBody{name=$name, orgName=$orgName, additionalProperties=$additionalProperties}" - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var name: String? = null - private var orgName: String? = null - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(projectReplaceBody: ProjectReplaceBody) = apply { - this.name = projectReplaceBody.name - this.orgName = projectReplaceBody.orgName - additionalProperties(projectReplaceBody.additionalProperties) - } - - /** Name of the project */ - @JsonProperty("name") fun name(name: String) = 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. - */ - @JsonProperty("org_name") - fun orgName(orgName: String) = apply { this.orgName = orgName } - - 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(): ProjectReplaceBody = - ProjectReplaceBody( - checkNotNull(name) { "`name` is required but was not set" }, - orgName, - additionalProperties.toUnmodifiable(), - ) - } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - - fun _additionalHeaders(): Map> = additionalHeaders - - fun _additionalBodyProperties(): Map = additionalBodyProperties - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return other is ProjectReplaceParams && - this.name == other.name && - this.orgName == other.orgName && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } - - override fun hashCode(): Int { - return Objects.hash( - name, - orgName, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } - - override fun toString() = - "ProjectReplaceParams{name=$name, orgName=$orgName, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - @NoAutoDetect - class Builder { - - private var name: String? = null - private var orgName: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(projectReplaceParams: ProjectReplaceParams) = apply { - this.name = projectReplaceParams.name - this.orgName = projectReplaceParams.orgName - additionalQueryParams(projectReplaceParams.additionalQueryParams) - additionalHeaders(projectReplaceParams.additionalHeaders) - additionalBodyProperties(projectReplaceParams.additionalBodyProperties) - } - - /** Name of the project */ - fun name(name: String) = 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) = apply { this.orgName = orgName } - - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) - } - - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } - - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } - - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } - - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } - - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) - } - - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } - - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } - - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) - } - - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } - - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) - } - - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) - } - - fun build(): ProjectReplaceParams = - ProjectReplaceParams( - checkNotNull(name) { "`name` is required but was not set" }, - orgName, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) - } -} 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 old mode 100644 new mode 100755 index 37a0e287..6e52ff5a --- 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,126 +2,194 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** Get a project object by its id */ class ProjectRetrieveParams -constructor( - private val projectId: String, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { +private constructor( + private val projectId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { - fun projectId(): String = projectId + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" - } + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectRetrieveParams]. */ + @JvmStatic fun builder() = Builder() } - fun _additionalQueryParams(): Map> = additionalQueryParams + /** A builder for [ProjectRetrieveParams]. */ + class Builder internal constructor() { - fun _additionalHeaders(): Map> = additionalHeaders + private var projectId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + @JvmSynthetic + internal fun from(projectRetrieveParams: ProjectRetrieveParams) = apply { + projectId = projectRetrieveParams.projectId + additionalHeaders = projectRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = projectRetrieveParams.additionalQueryParams.toBuilder() } - return other is ProjectRetrieveParams && - this.projectId == other.projectId && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders - } + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } - override fun hashCode(): Int { - return Objects.hash( - projectId, - additionalQueryParams, - additionalHeaders, - ) - } + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) - override fun toString() = - "ProjectRetrieveParams{projectId=$projectId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - fun toBuilder() = Builder().from(this) + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - @JvmStatic fun builder() = Builder() - } + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @NoAutoDetect - class Builder { + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - private var projectId: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(projectRetrieveParams: ProjectRetrieveParams) = apply { - this.projectId = projectRetrieveParams.projectId - additionalQueryParams(projectRetrieveParams.additionalQueryParams) - additionalHeaders(projectRetrieveParams.additionalHeaders) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + 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 removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [ProjectRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): ProjectRetrieveParams = ProjectRetrieveParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + projectId, + additionalHeaders.build(), + additionalQueryParams.build(), ) } + + 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 + } + + return other is ProjectRetrieveParams && + projectId == other.projectId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(projectId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectRetrieveParams{projectId=$projectId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 new file mode 100755 index 00000000..2594b23c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScore.kt @@ -0,0 +1,886 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +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.allMaxBy +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.getOrThrow +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 com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** A project score is a user-configured score, which can be manually-labeled through the UI */ +class ProjectScore +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * Name of the project 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 name(): String = name.getRequired("name") + + /** + * 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") + + /** + * 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") + + /** + * @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 userId(): String = userId.getRequired("user_id") + + /** + * For categorical-type project scores, the list of all categories + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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 = config.getOptional("config") + + /** + * Date of project score creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * 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") + + /** + * An optional LexoRank-based string that sets the sort position for the score in the UI + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun position(): Optional = position.getOptional("position") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [scoreType]. + * + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("score_type") + @ExcludeMissing + fun _scoreType(): JsonField = scoreType + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + /** + * Returns the raw JSON value of [categories]. + * + * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("categories") + @ExcludeMissing + fun _categories(): JsonField = categories + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") @ExcludeMissing fun _config(): JsonField = config + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + @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 [ProjectScore]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .scoreType() + * .userId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScore]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var projectId: JsonField? = null + private var scoreType: JsonField? = null + private var userId: JsonField? = null + private var categories: JsonField = JsonMissing.of() + private var config: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var position: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectScore: ProjectScore) = apply { + id = projectScore.id + name = projectScore.name + projectId = projectScore.projectId + scoreType = projectScore.scoreType + userId = projectScore.userId + categories = projectScore.categories + config = projectScore.config + created = projectScore.created + description = projectScore.description + position = projectScore.position + additionalProperties = projectScore.additionalProperties.toMutableMap() + } + + /** Unique identifier for the project score */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** 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 userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + /** 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 } + + /** 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 config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [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 } + + /** Date of project score creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Textual description of the project score */ + 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 } + + /** An optional LexoRank-based string that sets the sort position for the score in the UI */ + fun position(position: String?) = position(JsonField.ofNullable(position)) + + /** Alias for calling [Builder.position] with `position.orElse(null)`. */ + fun position(position: Optional) = position(position.getOrNull()) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectScore]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .scoreType() + * .userId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectScore = + ProjectScore( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("scoreType", scoreType), + checkRequired("userId", userId), + categories, + config, + created, + description, + position, + 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) + class Categories + private constructor( + private val categorical: List? = null, + private val weighted: Weighted? = null, + private val minimum: List? = null, + private val _json: JsonValue? = null, + ) { + + /** For categorical-type project scores, the list of all categories */ + fun categorical(): Optional> = Optional.ofNullable(categorical) + + /** For weighted-type project scores, the weights of each score */ + fun weighted(): Optional = Optional.ofNullable(weighted) + + /** For minimum-type project scores, the list of included scores */ + fun minimum(): Optional> = Optional.ofNullable(minimum) + + fun isCategorical(): Boolean = categorical != null + + fun isWeighted(): Boolean = weighted != null + + fun isMinimum(): Boolean = minimum != null + + /** For categorical-type project scores, the list of all categories */ + fun asCategorical(): List = categorical.getOrThrow("categorical") + + /** For weighted-type project scores, the weights of each score */ + fun asWeighted(): Weighted = weighted.getOrThrow("weighted") + + /** For minimum-type project scores, the list of included scores */ + fun asMinimum(): List = minimum.getOrThrow("minimum") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Categories = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitCategorical(categorical: List) { + categorical.forEach { it.validate() } + } + + override fun visitWeighted(weighted: Weighted) { + weighted.validate() + } + + override fun visitMinimum(minimum: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 + } + + return other is Categories && + categorical == other.categorical && + weighted == other.weighted && + minimum == other.minimum + } + + override fun hashCode(): Int = Objects.hash(categorical, weighted, minimum) + + override fun toString(): String = + when { + categorical != null -> "Categories{categorical=$categorical}" + weighted != null -> "Categories{weighted=$weighted}" + minimum != null -> "Categories{minimum=$minimum}" + _json != null -> "Categories{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Categories") + } + + companion object { + + /** For categorical-type project scores, the list of all categories */ + @JvmStatic + fun ofCategorical(categorical: List) = + Categories(categorical = categorical.toImmutable()) + + /** For weighted-type project scores, the weights of each score */ + @JvmStatic fun ofWeighted(weighted: Weighted) = Categories(weighted = weighted) + + /** For minimum-type project scores, the list of included scores */ + @JvmStatic + fun ofMinimum(minimum: List) = Categories(minimum = minimum.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Categories] to a value of type [T]. + */ + interface Visitor { + + /** For categorical-type project scores, the list of all categories */ + fun visitCategorical(categorical: List): T + + /** For weighted-type project scores, the weights of each score */ + fun visitWeighted(weighted: Weighted): T + + /** For minimum-type project scores, the list of included scores */ + fun visitMinimum(minimum: List): T + + /** + * Maps an unknown variant of [Categories] to a value of type [T]. + * + * An instance of [Categories] 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 Categories: $json") + } + } + + internal class Deserializer : BaseDeserializer(Categories::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Categories { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Categories::class) { + + override fun serialize( + value: Categories, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.categorical != null -> generator.writeObject(value.categorical) + value.weighted != null -> generator.writeObject(value.weighted) + value.minimum != null -> generator.writeObject(value.minimum) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Categories") + } + } + } + + /** For weighted-type project scores, the weights of each score */ + class Weighted + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Weighted]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Weighted]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(weighted: Weighted) = apply { + additionalProperties = weighted.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 [Weighted]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Weighted && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Weighted{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectScore && + id == other.id && + name == other.name && + projectId == other.projectId && + scoreType == other.scoreType && + userId == other.userId && + categories == other.categories && + config == other.config && + created == other.created && + description == other.description && + position == other.position && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + projectId, + scoreType, + userId, + categories, + config, + created, + description, + position, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectScore{id=$id, name=$name, projectId=$projectId, scoreType=$scoreType, userId=$userId, categories=$categories, config=$config, created=$created, description=$description, position=$position, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..fb7903b4 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCategory.kt @@ -0,0 +1,211 @@ +// 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.checkRequired +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 */ +class ProjectScoreCategory +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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()) + + /** + * Name of the category + * + * @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") + + /** + * Numerical value of the category. Must be between 0 and 1, inclusive + * + * @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 value(): Double = value.getRequired("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 [ProjectScoreCategory]. + * + * The following fields are required: + * ```java + * .name() + * .value() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreCategory]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var value: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectScoreCategory: ProjectScoreCategory) = apply { + name = projectScoreCategory.name + value = projectScoreCategory.value + additionalProperties = projectScoreCategory.additionalProperties.toMutableMap() + } + + /** Name of the category */ + 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 } + + /** Numerical value of the category. Must be between 0 and 1, inclusive */ + fun value(value: Double) = value(JsonField.of(value)) + + /** + * Sets [Builder.value] to an arbitrary JSON value. + * + * You should usually call [Builder.value] with a well-typed [Double] 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 [ProjectScoreCategory]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .value() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectScoreCategory = + ProjectScoreCategory( + checkRequired("name", name), + checkRequired("value", value), + 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 + } + + return other is ProjectScoreCategory && + name == other.name && + value == other.value && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, value, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectScoreCategory{name=$name, value=$value, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..0ab1a525 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreConfig.kt @@ -0,0 +1,250 @@ +// 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.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 + +class ProjectScoreConfig +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 = 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 = 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 = online.getOptional("online") + + /** + * Returns the raw JSON value of [destination]. + * + * Unlike [destination], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("destination") @ExcludeMissing fun _destination(): JsonField = destination + + /** + * Returns the raw JSON value of [multiSelect]. + * + * Unlike [multiSelect], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("multi_select") + @ExcludeMissing + fun _multiSelect(): JsonField = multiSelect + + /** + * Returns the raw JSON value of [online]. + * + * Unlike [online], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("online") @ExcludeMissing fun _online(): JsonField = online + + @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 [ProjectScoreConfig]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreConfig]. */ + class Builder internal constructor() { + + private var destination: JsonField = JsonMissing.of() + private var multiSelect: JsonField = JsonMissing.of() + private var online: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectScoreConfig: ProjectScoreConfig) = apply { + destination = projectScoreConfig.destination + multiSelect = projectScoreConfig.multiSelect + online = projectScoreConfig.online + additionalProperties = projectScoreConfig.additionalProperties.toMutableMap() + } + + fun destination(destination: String?) = destination(JsonField.ofNullable(destination)) + + /** Alias for calling [Builder.destination] with `destination.orElse(null)`. */ + fun destination(destination: Optional) = destination(destination.getOrNull()) + + /** + * Sets [Builder.destination] to an arbitrary JSON value. + * + * You should usually call [Builder.destination] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun destination(destination: JsonField) = apply { this.destination = destination } + + fun multiSelect(multiSelect: Boolean?) = multiSelect(JsonField.ofNullable(multiSelect)) + + /** + * Alias for [Builder.multiSelect]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun multiSelect(multiSelect: Boolean) = multiSelect(multiSelect as Boolean?) + + /** Alias for calling [Builder.multiSelect] with `multiSelect.orElse(null)`. */ + fun multiSelect(multiSelect: Optional) = multiSelect(multiSelect.getOrNull()) + + /** + * Sets [Builder.multiSelect] to an arbitrary JSON value. + * + * You should usually call [Builder.multiSelect] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun multiSelect(multiSelect: JsonField) = apply { this.multiSelect = multiSelect } + + fun online(online: OnlineScoreConfig?) = online(JsonField.ofNullable(online)) + + /** Alias for calling [Builder.online] with `online.orElse(null)`. */ + fun online(online: Optional) = online(online.getOrNull()) + + /** + * Sets [Builder.online] to an arbitrary JSON value. + * + * You should usually call [Builder.online] with a well-typed [OnlineScoreConfig] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun online(online: JsonField) = apply { this.online = online } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectScoreConfig]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectScoreConfig = + 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 + } + + return other is ProjectScoreConfig && + destination == other.destination && + multiSelect == other.multiSelect && + online == other.online && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(destination, multiSelect, online, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectScoreConfig{destination=$destination, multiSelect=$multiSelect, online=$online, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..9f912fe6 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParams.kt @@ -0,0 +1,1146 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +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.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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Create a new project_score. If there is an existing project_score in the project with the same + * name as the one specified in the request, will return the existing project_score unmodified + */ +class ProjectScoreCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the project 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 name(): String = body.name() + + /** + * 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 = body.projectId() + + /** + * 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 = body.scoreType() + + /** + * For categorical-type project scores, the list of all categories + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun categories(): Optional = body.categories() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = body.config() + + /** + * 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 = body.description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [scoreType]. + * + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _scoreType(): JsonField = body._scoreType() + + /** + * Returns the raw JSON value of [categories]. + * + * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _categories(): JsonField = body._categories() + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _config(): JsonField = body._config() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .scoreType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreCreateParams]. */ + 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(projectScoreCreateParams: ProjectScoreCreateParams) = apply { + body = projectScoreCreateParams.body.toBuilder() + additionalHeaders = projectScoreCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreCreateParams.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] + * - [scoreType] + * - [categories] + * - [config] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the project score */ + 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 score 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) } + + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType) = apply { body.scoreType(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 { 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()) + + /** + * 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 { 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) } + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [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) } + + /** 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()) + + /** + * 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** A project score is a user-configured score, which can be manually-labeled through the UI */ + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * Name of the project 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 name(): String = name.getRequired("name") + + /** + * 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") + + /** + * 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") + + /** + * For categorical-type project scores, the list of all categories + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + 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 = config.getOptional("config") + + /** + * 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") + + /** + * 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 [scoreType]. + * + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("score_type") + @ExcludeMissing + fun _scoreType(): JsonField = scoreType + + /** + * 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 + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") + @ExcludeMissing + fun _config(): JsonField = config + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + @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() + * .scoreType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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 + } + + /** 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 + } + + /** 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 config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [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 } + + /** Textual description of the project score */ + 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + scoreType().validate() + categories().ifPresent { it.validate() } + config().ifPresent { it.validate() } + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + projectId == other.projectId && + scoreType == other.scoreType && + categories == other.categories && + config == other.config && + description == other.description && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + projectId, + scoreType, + categories, + config, + description, + additionalProperties, + ) + } + + 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 */ + @JsonDeserialize(using = Categories.Deserializer::class) + @JsonSerialize(using = Categories.Serializer::class) + class Categories + private constructor( + private val categorical: List? = null, + private val weighted: Weighted? = null, + private val minimum: List? = null, + private val _json: JsonValue? = null, + ) { + + /** For categorical-type project scores, the list of all categories */ + fun categorical(): Optional> = Optional.ofNullable(categorical) + + /** For weighted-type project scores, the weights of each score */ + fun weighted(): Optional = Optional.ofNullable(weighted) + + /** For minimum-type project scores, the list of included scores */ + fun minimum(): Optional> = Optional.ofNullable(minimum) + + fun isCategorical(): Boolean = categorical != null + + fun isWeighted(): Boolean = weighted != null + + fun isMinimum(): Boolean = minimum != null + + /** For categorical-type project scores, the list of all categories */ + fun asCategorical(): List = categorical.getOrThrow("categorical") + + /** For weighted-type project scores, the weights of each score */ + fun asWeighted(): Weighted = weighted.getOrThrow("weighted") + + /** For minimum-type project scores, the list of included scores */ + fun asMinimum(): List = minimum.getOrThrow("minimum") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Categories = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitCategorical(categorical: List) { + categorical.forEach { it.validate() } + } + + override fun visitWeighted(weighted: Weighted) { + weighted.validate() + } + + override fun visitMinimum(minimum: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 + } + + return other is Categories && + categorical == other.categorical && + weighted == other.weighted && + minimum == other.minimum + } + + override fun hashCode(): Int = Objects.hash(categorical, weighted, minimum) + + override fun toString(): String = + when { + categorical != null -> "Categories{categorical=$categorical}" + weighted != null -> "Categories{weighted=$weighted}" + minimum != null -> "Categories{minimum=$minimum}" + _json != null -> "Categories{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Categories") + } + + companion object { + + /** For categorical-type project scores, the list of all categories */ + @JvmStatic + fun ofCategorical(categorical: List) = + Categories(categorical = categorical.toImmutable()) + + /** For weighted-type project scores, the weights of each score */ + @JvmStatic fun ofWeighted(weighted: Weighted) = Categories(weighted = weighted) + + /** For minimum-type project scores, the list of included scores */ + @JvmStatic + fun ofMinimum(minimum: List) = Categories(minimum = minimum.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Categories] to a value of type [T]. + */ + interface Visitor { + + /** For categorical-type project scores, the list of all categories */ + fun visitCategorical(categorical: List): T + + /** For weighted-type project scores, the weights of each score */ + fun visitWeighted(weighted: Weighted): T + + /** For minimum-type project scores, the list of included scores */ + fun visitMinimum(minimum: List): T + + /** + * Maps an unknown variant of [Categories] to a value of type [T]. + * + * An instance of [Categories] 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 Categories: $json") + } + } + + internal class Deserializer : BaseDeserializer(Categories::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Categories { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Categories::class) { + + override fun serialize( + value: Categories, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.categorical != null -> generator.writeObject(value.categorical) + value.weighted != null -> generator.writeObject(value.weighted) + value.minimum != null -> generator.writeObject(value.minimum) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Categories") + } + } + } + + /** For weighted-type project scores, the weights of each score */ + class Weighted + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Weighted]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Weighted]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(weighted: Weighted) = apply { + additionalProperties = weighted.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 [Weighted]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Weighted && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Weighted{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectScoreCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectScoreCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..da4a7464 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParams.kt @@ -0,0 +1,238 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete a project_score object by its id */ +class ProjectScoreDeleteParams +private constructor( + private val projectScoreId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** ProjectScore id */ + fun projectScoreId(): Optional = Optional.ofNullable(projectScoreId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectScoreDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectScoreDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreDeleteParams]. */ + class Builder internal constructor() { + + private var projectScoreId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectScoreDeleteParams: ProjectScoreDeleteParams) = apply { + projectScoreId = projectScoreDeleteParams.projectScoreId + additionalHeaders = projectScoreDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + projectScoreDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** ProjectScore id */ + fun projectScoreId(projectScoreId: String?) = apply { this.projectScoreId = projectScoreId } + + /** Alias for calling [Builder.projectScoreId] with `projectScoreId.orElse(null)`. */ + fun projectScoreId(projectScoreId: Optional) = + projectScoreId(projectScoreId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [ProjectScoreDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectScoreDeleteParams = + ProjectScoreDeleteParams( + projectScoreId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is ProjectScoreDeleteParams && + projectScoreId == other.projectScoreId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash( + projectScoreId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) + + override fun toString() = + "ProjectScoreDeleteParams{projectScoreId=$projectScoreId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100755 index 00000000..67eda9d4 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPage.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.ProjectScoreService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see ProjectScoreService.list */ +class ProjectScoreListPage +private constructor( + private val service: ProjectScoreService, + private val params: ProjectScoreListParams, + private val response: ProjectScoreListPageResponse, +) : Page { + + /** + * Delegates to [ProjectScoreListPageResponse], but gracefully handles missing data. + * + * @see ProjectScoreListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ProjectScoreListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): ProjectScoreListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): ProjectScoreListParams = params + + /** The response that this page was parsed from. */ + fun response(): ProjectScoreListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreListPage]. */ + class Builder internal constructor() { + + private var service: ProjectScoreService? = null + private var params: ProjectScoreListParams? = null + private var response: ProjectScoreListPageResponse? = null + + @JvmSynthetic + internal fun from(projectScoreListPage: ProjectScoreListPage) = apply { + service = projectScoreListPage.service + params = projectScoreListPage.params + response = projectScoreListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectScoreListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..d946a037 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageAsync.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.ProjectScoreServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see ProjectScoreServiceAsync.list */ +class ProjectScoreListPageAsync +private constructor( + private val service: ProjectScoreServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: ProjectScoreListParams, + private val response: ProjectScoreListPageResponse, +) : PageAsync { + + /** + * Delegates to [ProjectScoreListPageResponse], but gracefully handles missing data. + * + * @see ProjectScoreListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ProjectScoreListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): ProjectScoreListParams = params + + /** The response that this page was parsed from. */ + fun response(): ProjectScoreListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreListPageAsync]. */ + class Builder internal constructor() { + + private var service: ProjectScoreServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ProjectScoreListParams? = null + private var response: ProjectScoreListPageResponse? = null + + @JvmSynthetic + internal fun from(projectScoreListPageAsync: ProjectScoreListPageAsync) = apply { + service = projectScoreListPageAsync.service + streamHandlerExecutor = projectScoreListPageAsync.streamHandlerExecutor + params = projectScoreListPageAsync.params + response = projectScoreListPageAsync.response + } + + fun service(service: ProjectScoreServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectScoreListPageAsync = + ProjectScoreListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectScoreListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "ProjectScoreListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..631c551e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is ProjectScoreListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..5e0dd49b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreListParams.kt @@ -0,0 +1,548 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +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 + */ +class ProjectScoreListParams +private constructor( + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val projectId: String?, + private val projectName: String?, + private val projectScoreName: String?, + private val scoreType: ScoreType?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** Name of the project to search for */ + fun projectName(): Optional = Optional.ofNullable(projectName) + + /** Name of the project_score to search for */ + fun projectScoreName(): Optional = Optional.ofNullable(projectScoreName) + + /** The type of the configured score */ + fun scoreType(): Optional = Optional.ofNullable(scoreType) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectScoreListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectScoreListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var projectId: String? = null + private var projectName: String? = null + private var projectScoreName: String? = null + private var scoreType: ScoreType? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(projectScoreListParams: ProjectScoreListParams) = apply { + endingBefore = projectScoreListParams.endingBefore + ids = projectScoreListParams.ids + limit = projectScoreListParams.limit + orgName = projectScoreListParams.orgName + projectId = projectScoreListParams.projectId + projectName = projectScoreListParams.projectName + projectScoreName = projectScoreListParams.projectScoreName + scoreType = projectScoreListParams.scoreType + startingAfter = projectScoreListParams.startingAfter + additionalHeaders = projectScoreListParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) + + /** Name of the project to search for */ + fun projectName(projectName: String?) = apply { this.projectName = projectName } + + /** Alias for calling [Builder.projectName] with `projectName.orElse(null)`. */ + fun projectName(projectName: Optional) = projectName(projectName.getOrNull()) + + /** Name of the project_score to search for */ + fun projectScoreName(projectScoreName: String?) = apply { + this.projectScoreName = projectScoreName + } + + /** Alias for calling [Builder.projectScoreName] with `projectScoreName.orElse(null)`. */ + fun projectScoreName(projectScoreName: Optional) = + projectScoreName(projectScoreName.getOrNull()) + + /** The type of the configured score */ + fun scoreType(scoreType: ScoreType?) = apply { this.scoreType = scoreType } + + /** Alias for calling [Builder.scoreType] with `scoreType.orElse(null)`. */ + fun scoreType(scoreType: Optional) = scoreType(scoreType.getOrNull()) + + /** Alias for calling [scoreType] with `ScoreType.ofProject(project)`. */ + fun scoreType(project: ProjectScoreType) = scoreType(ScoreType.ofProject(project)) + + /** + * Alias for calling [scoreType] with `ScoreType.ofProjectScoreTypes(projectScoreTypes)`. + */ + fun scoreTypeOfProjectScoreTypes(projectScoreTypes: List) = + scoreType(ScoreType.ofProjectScoreTypes(projectScoreTypes)) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ProjectScoreListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectScoreListParams = + ProjectScoreListParams( + endingBefore, + ids, + limit, + orgName, + projectId, + projectName, + projectScoreName, + scoreType, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + /** The type of the configured score */ + class ScoreType + private constructor( + private val project: ProjectScoreType? = null, + private val projectScoreTypes: List? = null, + ) { + + /** The type of the configured score */ + fun project(): Optional = Optional.ofNullable(project) + + /** The type of the configured score */ + fun projectScoreTypes(): Optional> = + Optional.ofNullable(projectScoreTypes) + + fun isProject(): Boolean = project != null + + fun isProjectScoreTypes(): Boolean = projectScoreTypes != null + + /** The type of the configured score */ + fun asProject(): ProjectScoreType = project.getOrThrow("project") + + /** The type of the configured score */ + fun asProjectScoreTypes(): List = + projectScoreTypes.getOrThrow("projectScoreTypes") + + fun accept(visitor: Visitor): T = + when { + project != null -> visitor.visitProject(project) + projectScoreTypes != null -> visitor.visitProjectScoreTypes(projectScoreTypes) + else -> throw IllegalStateException("Invalid ScoreType") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ScoreType && + project == other.project && + projectScoreTypes == other.projectScoreTypes + } + + override fun hashCode(): Int = Objects.hash(project, projectScoreTypes) + + override fun toString(): String = + when { + project != null -> "ScoreType{project=$project}" + projectScoreTypes != null -> "ScoreType{projectScoreTypes=$projectScoreTypes}" + else -> throw IllegalStateException("Invalid ScoreType") + } + + companion object { + + /** The type of the configured score */ + @JvmStatic fun ofProject(project: ProjectScoreType) = ScoreType(project = project) + + /** The type of the configured score */ + @JvmStatic + fun ofProjectScoreTypes(projectScoreTypes: List) = + ScoreType(projectScoreTypes = projectScoreTypes.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [ScoreType] to a value of type [T]. + */ + interface Visitor { + + /** The type of the configured score */ + fun visitProject(project: ProjectScoreType): T + + /** The type of the configured score */ + fun visitProjectScoreTypes(projectScoreTypes: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectScoreListParams && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + projectId == other.projectId && + projectName == other.projectName && + projectScoreName == other.projectScoreName && + scoreType == other.scoreType && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + ids, + limit, + orgName, + projectId, + projectName, + projectScoreName, + scoreType, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ProjectScoreListParams{endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, projectId=$projectId, projectName=$projectName, projectScoreName=$projectScoreName, scoreType=$scoreType, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..c745d420 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParams.kt @@ -0,0 +1,1147 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +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.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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Create or replace project_score. If there is an existing project_score in the project with the + * same name as the one specified in the request, will replace the existing project_score with the + * provided fields + */ +class ProjectScoreReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the project 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 name(): String = body.name() + + /** + * 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 = body.projectId() + + /** + * 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 = body.scoreType() + + /** + * For categorical-type project scores, the list of all categories + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun categories(): Optional = body.categories() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = body.config() + + /** + * 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 = body.description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [scoreType]. + * + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _scoreType(): JsonField = body._scoreType() + + /** + * Returns the raw JSON value of [categories]. + * + * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _categories(): JsonField = body._categories() + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _config(): JsonField = body._config() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .scoreType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreReplaceParams]. */ + 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(projectScoreReplaceParams: ProjectScoreReplaceParams) = apply { + body = projectScoreReplaceParams.body.toBuilder() + additionalHeaders = projectScoreReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreReplaceParams.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] + * - [scoreType] + * - [categories] + * - [config] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the project score */ + 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 score 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) } + + /** The type of the configured score */ + fun scoreType(scoreType: ProjectScoreType) = apply { body.scoreType(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 { 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()) + + /** + * 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 { 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) } + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [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) } + + /** 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()) + + /** + * 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** A project score is a user-configured score, which can be manually-labeled through the UI */ + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * Name of the project 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 name(): String = name.getRequired("name") + + /** + * 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") + + /** + * 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") + + /** + * For categorical-type project scores, the list of all categories + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + 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 = config.getOptional("config") + + /** + * 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") + + /** + * 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 [scoreType]. + * + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("score_type") + @ExcludeMissing + fun _scoreType(): JsonField = scoreType + + /** + * 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 + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") + @ExcludeMissing + fun _config(): JsonField = config + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + + @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() + * .scoreType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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 + } + + /** 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 + } + + /** 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 config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [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 } + + /** Textual description of the project score */ + 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + scoreType().validate() + categories().ifPresent { it.validate() } + config().ifPresent { it.validate() } + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + projectId == other.projectId && + scoreType == other.scoreType && + categories == other.categories && + config == other.config && + description == other.description && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + projectId, + scoreType, + categories, + config, + description, + additionalProperties, + ) + } + + 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 */ + @JsonDeserialize(using = Categories.Deserializer::class) + @JsonSerialize(using = Categories.Serializer::class) + class Categories + private constructor( + private val categorical: List? = null, + private val weighted: Weighted? = null, + private val minimum: List? = null, + private val _json: JsonValue? = null, + ) { + + /** For categorical-type project scores, the list of all categories */ + fun categorical(): Optional> = Optional.ofNullable(categorical) + + /** For weighted-type project scores, the weights of each score */ + fun weighted(): Optional = Optional.ofNullable(weighted) + + /** For minimum-type project scores, the list of included scores */ + fun minimum(): Optional> = Optional.ofNullable(minimum) + + fun isCategorical(): Boolean = categorical != null + + fun isWeighted(): Boolean = weighted != null + + fun isMinimum(): Boolean = minimum != null + + /** For categorical-type project scores, the list of all categories */ + fun asCategorical(): List = categorical.getOrThrow("categorical") + + /** For weighted-type project scores, the weights of each score */ + fun asWeighted(): Weighted = weighted.getOrThrow("weighted") + + /** For minimum-type project scores, the list of included scores */ + fun asMinimum(): List = minimum.getOrThrow("minimum") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Categories = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitCategorical(categorical: List) { + categorical.forEach { it.validate() } + } + + override fun visitWeighted(weighted: Weighted) { + weighted.validate() + } + + override fun visitMinimum(minimum: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 + } + + return other is Categories && + categorical == other.categorical && + weighted == other.weighted && + minimum == other.minimum + } + + override fun hashCode(): Int = Objects.hash(categorical, weighted, minimum) + + override fun toString(): String = + when { + categorical != null -> "Categories{categorical=$categorical}" + weighted != null -> "Categories{weighted=$weighted}" + minimum != null -> "Categories{minimum=$minimum}" + _json != null -> "Categories{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Categories") + } + + companion object { + + /** For categorical-type project scores, the list of all categories */ + @JvmStatic + fun ofCategorical(categorical: List) = + Categories(categorical = categorical.toImmutable()) + + /** For weighted-type project scores, the weights of each score */ + @JvmStatic fun ofWeighted(weighted: Weighted) = Categories(weighted = weighted) + + /** For minimum-type project scores, the list of included scores */ + @JvmStatic + fun ofMinimum(minimum: List) = Categories(minimum = minimum.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Categories] to a value of type [T]. + */ + interface Visitor { + + /** For categorical-type project scores, the list of all categories */ + fun visitCategorical(categorical: List): T + + /** For weighted-type project scores, the weights of each score */ + fun visitWeighted(weighted: Weighted): T + + /** For minimum-type project scores, the list of included scores */ + fun visitMinimum(minimum: List): T + + /** + * Maps an unknown variant of [Categories] to a value of type [T]. + * + * An instance of [Categories] 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 Categories: $json") + } + } + + internal class Deserializer : BaseDeserializer(Categories::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Categories { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Categories::class) { + + override fun serialize( + value: Categories, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.categorical != null -> generator.writeObject(value.categorical) + value.weighted != null -> generator.writeObject(value.weighted) + value.minimum != null -> generator.writeObject(value.minimum) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Categories") + } + } + } + + /** For weighted-type project scores, the weights of each score */ + class Weighted + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Weighted]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Weighted]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(weighted: Weighted) = apply { + additionalProperties = weighted.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 [Weighted]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Weighted && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Weighted{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectScoreReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectScoreReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..401cebac --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParams.kt @@ -0,0 +1,199 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a project_score object by its id */ +class ProjectScoreRetrieveParams +private constructor( + private val projectScoreId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** ProjectScore id */ + fun projectScoreId(): Optional = Optional.ofNullable(projectScoreId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectScoreRetrieveParams = builder().build() + + /** + * Returns a mutable builder for constructing an instance of [ProjectScoreRetrieveParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectScoreRetrieveParams]. */ + class Builder internal constructor() { + + private var projectScoreId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(projectScoreRetrieveParams: ProjectScoreRetrieveParams) = apply { + projectScoreId = projectScoreRetrieveParams.projectScoreId + additionalHeaders = projectScoreRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = projectScoreRetrieveParams.additionalQueryParams.toBuilder() + } + + /** ProjectScore id */ + fun projectScoreId(projectScoreId: String?) = apply { this.projectScoreId = projectScoreId } + + /** Alias for calling [Builder.projectScoreId] with `projectScoreId.orElse(null)`. */ + fun projectScoreId(projectScoreId: Optional) = + projectScoreId(projectScoreId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ProjectScoreRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectScoreRetrieveParams = + ProjectScoreRetrieveParams( + projectScoreId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is ProjectScoreRetrieveParams && + projectScoreId == other.projectScoreId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(projectScoreId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectScoreRetrieveParams{projectScoreId=$projectScoreId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..67cc2c66 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreType.kt @@ -0,0 +1,165 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.errors.BraintrustInvalidDataException +import com.fasterxml.jackson.annotation.JsonCreator + +/** The type of the configured score */ +class ProjectScoreType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val SLIDER = of("slider") + + @JvmField val CATEGORICAL = of("categorical") + + @JvmField val WEIGHTED = of("weighted") + + @JvmField val MINIMUM = of("minimum") + + @JvmField val MAXIMUM = of("maximum") + + @JvmField val ONLINE = of("online") + + @JvmField val FREE_FORM = of("free-form") + + @JvmStatic fun of(value: String) = ProjectScoreType(JsonField.of(value)) + } + + /** An enum containing [ProjectScoreType]'s known values. */ + enum class Known { + SLIDER, + CATEGORICAL, + WEIGHTED, + MINIMUM, + MAXIMUM, + ONLINE, + FREE_FORM, + } + + /** + * An enum containing [ProjectScoreType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ProjectScoreType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SLIDER, + CATEGORICAL, + WEIGHTED, + MINIMUM, + MAXIMUM, + ONLINE, + FREE_FORM, + /** + * An enum member indicating that [ProjectScoreType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + SLIDER -> Value.SLIDER + CATEGORICAL -> Value.CATEGORICAL + WEIGHTED -> Value.WEIGHTED + MINIMUM -> Value.MINIMUM + MAXIMUM -> Value.MAXIMUM + ONLINE -> Value.ONLINE + FREE_FORM -> Value.FREE_FORM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + SLIDER -> Known.SLIDER + CATEGORICAL -> Known.CATEGORICAL + WEIGHTED -> Known.WEIGHTED + MINIMUM -> Known.MINIMUM + MAXIMUM -> Known.MAXIMUM + ONLINE -> Known.ONLINE + FREE_FORM -> Known.FREE_FORM + else -> throw BraintrustInvalidDataException("Unknown ProjectScoreType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + 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 + } + + return other is ProjectScoreType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} 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 new file mode 100755 index 00000000..514c809a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParams.kt @@ -0,0 +1,1074 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +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.Params +import com.braintrustdata.api.core.allMaxBy +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.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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * Partially update a project_score object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ +class ProjectScoreUpdateParams +private constructor( + private val projectScoreId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** ProjectScore id */ + fun projectScoreId(): Optional = Optional.ofNullable(projectScoreId) + + /** + * For categorical-type project scores, the list of all categories + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun categories(): Optional = body.categories() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun config(): Optional = body.config() + + /** + * 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 = body.description() + + /** + * Name 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 name(): Optional = body.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 = body.scoreType() + + /** + * Returns the raw JSON value of [categories]. + * + * Unlike [categories], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _categories(): JsonField = body._categories() + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _config(): JsonField = body._config() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [scoreType]. + * + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _scoreType(): JsonField = body._scoreType() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectScoreUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectScoreUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** ProjectScore id */ + fun projectScoreId(projectScoreId: String?) = apply { this.projectScoreId = projectScoreId } + + /** Alias for calling [Builder.projectScoreId] with `projectScoreId.orElse(null)`. */ + fun projectScoreId(projectScoreId: Optional) = + projectScoreId(projectScoreId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [categories] + * - [config] + * - [description] + * - [name] + * - [scoreType] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** 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()) + + /** + * 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 { 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) } + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [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) } + + /** 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()) + + /** + * 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 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()) + + /** + * 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 type of the configured score */ + fun scoreType(scoreType: ProjectScoreType?) = apply { body.scoreType(scoreType) } + + /** Alias for calling [Builder.scoreType] with `scoreType.orElse(null)`. */ + fun scoreType(scoreType: Optional) = scoreType(scoreType.getOrNull()) + + /** + * 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) } + + 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 [ProjectScoreUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectScoreUpdateParams = + ProjectScoreUpdateParams( + projectScoreId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectScoreId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + /** A project score is a user-configured score, which can be manually-labeled through the UI */ + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * For categorical-type project scores, the list of all categories + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + 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 = config.getOptional("config") + + /** + * 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") + + /** + * Name 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 name(): Optional = name.getOptional("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") + + /** + * 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 + + /** + * Returns the raw JSON value of [config]. + * + * Unlike [config], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config") + @ExcludeMissing + fun _config(): JsonField = config + + /** + * Returns the raw JSON value of [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 [scoreType]. + * + * Unlike [scoreType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("score_type") + @ExcludeMissing + fun _scoreType(): JsonField = scoreType + + @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 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 + } + + /** 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 config(config: ProjectScoreConfig?) = config(JsonField.ofNullable(config)) + + /** Alias for calling [Builder.config] with `config.orElse(null)`. */ + fun config(config: Optional) = config(config.getOrNull()) + + /** + * Sets [Builder.config] to an arbitrary JSON value. + * + * You should usually call [Builder.config] with a well-typed [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 } + + /** Textual description of the project score */ + 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 score */ + 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 type of the configured score */ + fun scoreType(scoreType: ProjectScoreType?) = scoreType(JsonField.ofNullable(scoreType)) + + /** Alias for calling [Builder.scoreType] with `scoreType.orElse(null)`. */ + fun scoreType(scoreType: Optional) = scoreType(scoreType.getOrNull()) + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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( + categories, + config, + description, + name, + scoreType, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + 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 a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @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 other is Body && + categories == other.categories && + config == other.config && + description == other.description && + name == other.name && + scoreType == other.scoreType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(categories, config, description, name, scoreType, additionalProperties) + } + + 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 */ + @JsonDeserialize(using = Categories.Deserializer::class) + @JsonSerialize(using = Categories.Serializer::class) + class Categories + private constructor( + private val categorical: List? = null, + private val weighted: Weighted? = null, + private val minimum: List? = null, + private val _json: JsonValue? = null, + ) { + + /** For categorical-type project scores, the list of all categories */ + fun categorical(): Optional> = Optional.ofNullable(categorical) + + /** For weighted-type project scores, the weights of each score */ + fun weighted(): Optional = Optional.ofNullable(weighted) + + /** For minimum-type project scores, the list of included scores */ + fun minimum(): Optional> = Optional.ofNullable(minimum) + + fun isCategorical(): Boolean = categorical != null + + fun isWeighted(): Boolean = weighted != null + + fun isMinimum(): Boolean = minimum != null + + /** For categorical-type project scores, the list of all categories */ + fun asCategorical(): List = categorical.getOrThrow("categorical") + + /** For weighted-type project scores, the weights of each score */ + fun asWeighted(): Weighted = weighted.getOrThrow("weighted") + + /** For minimum-type project scores, the list of included scores */ + fun asMinimum(): List = minimum.getOrThrow("minimum") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Categories = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitCategorical(categorical: List) { + categorical.forEach { it.validate() } + } + + override fun visitWeighted(weighted: Weighted) { + weighted.validate() + } + + override fun visitMinimum(minimum: List) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 + } + + return other is Categories && + categorical == other.categorical && + weighted == other.weighted && + minimum == other.minimum + } + + override fun hashCode(): Int = Objects.hash(categorical, weighted, minimum) + + override fun toString(): String = + when { + categorical != null -> "Categories{categorical=$categorical}" + weighted != null -> "Categories{weighted=$weighted}" + minimum != null -> "Categories{minimum=$minimum}" + _json != null -> "Categories{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Categories") + } + + companion object { + + /** For categorical-type project scores, the list of all categories */ + @JvmStatic + fun ofCategorical(categorical: List) = + Categories(categorical = categorical.toImmutable()) + + /** For weighted-type project scores, the weights of each score */ + @JvmStatic fun ofWeighted(weighted: Weighted) = Categories(weighted = weighted) + + /** For minimum-type project scores, the list of included scores */ + @JvmStatic + fun ofMinimum(minimum: List) = Categories(minimum = minimum.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Categories] to a value of type [T]. + */ + interface Visitor { + + /** For categorical-type project scores, the list of all categories */ + fun visitCategorical(categorical: List): T + + /** For weighted-type project scores, the weights of each score */ + fun visitWeighted(weighted: Weighted): T + + /** For minimum-type project scores, the list of included scores */ + fun visitMinimum(minimum: List): T + + /** + * Maps an unknown variant of [Categories] to a value of type [T]. + * + * An instance of [Categories] 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 Categories: $json") + } + } + + internal class Deserializer : BaseDeserializer(Categories::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Categories { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Categories::class) { + + override fun serialize( + value: Categories, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.categorical != null -> generator.writeObject(value.categorical) + value.weighted != null -> generator.writeObject(value.weighted) + value.minimum != null -> generator.writeObject(value.minimum) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Categories") + } + } + } + + /** For weighted-type project scores, the weights of each score */ + class Weighted + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Weighted]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Weighted]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(weighted: Weighted) = apply { + additionalProperties = weighted.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 [Weighted]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Weighted && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Weighted{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectScoreUpdateParams && + projectScoreId == other.projectScoreId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(projectScoreId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectScoreUpdateParams{projectScoreId=$projectScoreId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..6d8d6a57 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectSettings.kt @@ -0,0 +1,690 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class ProjectSettings +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun baselineExperimentId(): Optional = + baselineExperimentId.getOptional("baseline_experiment_id") + + /** + * The key used to join two experiments (defaults to `input`) + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun comparisonKey(): Optional = comparisonKey.getOptional("comparison_key") + + /** + * The order of the fields to display in the trace view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun spanFieldOrder(): Optional> = + spanFieldOrder.getOptional("spanFieldOrder") + + /** + * Returns the raw JSON value of [baselineExperimentId]. + * + * Unlike [baselineExperimentId], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("baseline_experiment_id") + @ExcludeMissing + fun _baselineExperimentId(): JsonField = baselineExperimentId + + /** + * Returns the raw JSON value of [comparisonKey]. + * + * Unlike [comparisonKey], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("comparison_key") + @ExcludeMissing + fun _comparisonKey(): JsonField = comparisonKey + + /** + * Returns the raw JSON value of [spanFieldOrder]. + * + * Unlike [spanFieldOrder], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("spanFieldOrder") + @ExcludeMissing + fun _spanFieldOrder(): JsonField> = spanFieldOrder + + @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 [ProjectSettings]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectSettings]. */ + class Builder internal constructor() { + + private var baselineExperimentId: JsonField = JsonMissing.of() + private var comparisonKey: JsonField = JsonMissing.of() + private var spanFieldOrder: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectSettings: ProjectSettings) = apply { + baselineExperimentId = projectSettings.baselineExperimentId + comparisonKey = projectSettings.comparisonKey + spanFieldOrder = projectSettings.spanFieldOrder.map { it.toMutableList() } + additionalProperties = projectSettings.additionalProperties.toMutableMap() + } + + /** The id of the experiment to use as the default baseline for comparisons */ + fun baselineExperimentId(baselineExperimentId: String?) = + baselineExperimentId(JsonField.ofNullable(baselineExperimentId)) + + /** + * Alias for calling [Builder.baselineExperimentId] with + * `baselineExperimentId.orElse(null)`. + */ + fun baselineExperimentId(baselineExperimentId: Optional) = + baselineExperimentId(baselineExperimentId.getOrNull()) + + /** + * Sets [Builder.baselineExperimentId] to an arbitrary JSON value. + * + * You should usually call [Builder.baselineExperimentId] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun baselineExperimentId(baselineExperimentId: JsonField) = apply { + this.baselineExperimentId = baselineExperimentId + } + + /** The key used to join two experiments (defaults to `input`) */ + fun comparisonKey(comparisonKey: String?) = + comparisonKey(JsonField.ofNullable(comparisonKey)) + + /** Alias for calling [Builder.comparisonKey] with `comparisonKey.orElse(null)`. */ + fun comparisonKey(comparisonKey: Optional) = + comparisonKey(comparisonKey.getOrNull()) + + /** + * Sets [Builder.comparisonKey] to an arbitrary JSON value. + * + * You should usually call [Builder.comparisonKey] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun comparisonKey(comparisonKey: JsonField) = apply { + this.comparisonKey = comparisonKey + } + + /** The order of the fields to display in the trace view */ + fun spanFieldOrder(spanFieldOrder: List?) = + spanFieldOrder(JsonField.ofNullable(spanFieldOrder)) + + /** Alias for calling [Builder.spanFieldOrder] with `spanFieldOrder.orElse(null)`. */ + fun spanFieldOrder(spanFieldOrder: Optional>) = + spanFieldOrder(spanFieldOrder.getOrNull()) + + /** + * Sets [Builder.spanFieldOrder] to an arbitrary JSON value. + * + * You should usually call [Builder.spanFieldOrder] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun spanFieldOrder(spanFieldOrder: JsonField>) = apply { + this.spanFieldOrder = spanFieldOrder.map { it.toMutableList() } + } + + /** + * Adds a single [SpanFieldOrder] to [Builder.spanFieldOrder]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSpanFieldOrder(spanFieldOrder: SpanFieldOrder) = apply { + this.spanFieldOrder = + (this.spanFieldOrder ?: JsonField.of(mutableListOf())).also { + checkKnown("spanFieldOrder", it).add(spanFieldOrder) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectSettings]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectSettings = + ProjectSettings( + baselineExperimentId, + comparisonKey, + (spanFieldOrder ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun columnId(): String = columnId.getRequired("column_id") + + /** + * @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(): String = objectType.getRequired("object_type") + + /** + * @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 position(): String = position.getRequired("position") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun layout(): Optional = layout.getOptional("layout") + + /** + * Returns the raw JSON value of [columnId]. + * + * Unlike [columnId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("column_id") @ExcludeMissing fun _columnId(): JsonField = columnId + + /** + * 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 + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + /** + * Returns the raw JSON value of [layout]. + * + * Unlike [layout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("layout") @ExcludeMissing fun _layout(): JsonField = layout + + @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 [SpanFieldOrder]. + * + * The following fields are required: + * ```java + * .columnId() + * .objectType() + * .position() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanFieldOrder]. */ + class Builder internal constructor() { + + private var columnId: JsonField? = null + private var objectType: JsonField? = null + private var position: JsonField? = null + private var layout: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(spanFieldOrder: SpanFieldOrder) = apply { + columnId = spanFieldOrder.columnId + objectType = spanFieldOrder.objectType + position = spanFieldOrder.position + layout = spanFieldOrder.layout + additionalProperties = spanFieldOrder.additionalProperties.toMutableMap() + } + + fun columnId(columnId: String) = columnId(JsonField.of(columnId)) + + /** + * Sets [Builder.columnId] to an arbitrary JSON value. + * + * You should usually call [Builder.columnId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun columnId(columnId: JsonField) = apply { this.columnId = columnId } + + fun objectType(objectType: String) = objectType(JsonField.of(objectType)) + + /** + * Sets [Builder.objectType] to an arbitrary JSON value. + * + * You should usually call [Builder.objectType] with a well-typed [String] 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 position(position: String) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun layout(layout: Layout?) = layout(JsonField.ofNullable(layout)) + + /** Alias for calling [Builder.layout] with `layout.orElse(null)`. */ + fun layout(layout: Optional) = layout(layout.getOrNull()) + + /** + * Sets [Builder.layout] to an arbitrary JSON value. + * + * You should usually call [Builder.layout] with a well-typed [Layout] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun layout(layout: JsonField) = apply { this.layout = layout } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SpanFieldOrder]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .columnId() + * .objectType() + * .position() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanFieldOrder = + SpanFieldOrder( + checkRequired("columnId", columnId), + checkRequired("objectType", objectType), + checkRequired("position", position), + layout, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FULL = of("full") + + @JvmField val TWO_COLUMN = of("two_column") + + @JvmStatic fun of(value: String) = Layout(JsonField.of(value)) + } + + /** An enum containing [Layout]'s known values. */ + enum class Known { + FULL, + TWO_COLUMN, + } + + /** + * An enum containing [Layout]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Layout] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FULL, + TWO_COLUMN, + /** + * An enum member indicating that [Layout] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FULL -> Value.FULL + TWO_COLUMN -> Value.TWO_COLUMN + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + FULL -> Known.FULL + TWO_COLUMN -> Known.TWO_COLUMN + else -> throw BraintrustInvalidDataException("Unknown Layout: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Layout && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanFieldOrder && + columnId == other.columnId && + objectType == other.objectType && + position == other.position && + layout == other.layout && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(columnId, objectType, position, layout, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SpanFieldOrder{columnId=$columnId, objectType=$objectType, position=$position, layout=$layout, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectSettings && + baselineExperimentId == other.baselineExperimentId && + comparisonKey == other.comparisonKey && + spanFieldOrder == other.spanFieldOrder && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(baselineExperimentId, comparisonKey, spanFieldOrder, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectSettings{baselineExperimentId=$baselineExperimentId, comparisonKey=$comparisonKey, spanFieldOrder=$spanFieldOrder, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..20af1bb4 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTag.kt @@ -0,0 +1,407 @@ +// 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.checkRequired +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 + +/** + * A project tag is a user-configured tag for tracking and filtering your experiments, logs, and + * other data + */ +class ProjectTag +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * Name of the project tag + * + * @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 project tag 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") + + /** + * @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 userId(): String = userId.getRequired("user_id") + + /** + * 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") + + /** + * Date of project tag creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * 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") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + /** + * Returns the raw JSON value of [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 [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + + @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 [ProjectTag]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .userId() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTag]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var projectId: JsonField? = null + private var userId: JsonField? = null + private var color: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectTag: ProjectTag) = apply { + id = projectTag.id + name = projectTag.name + projectId = projectTag.projectId + userId = projectTag.userId + color = projectTag.color + created = projectTag.created + description = projectTag.description + additionalProperties = projectTag.additionalProperties.toMutableMap() + } + + /** Unique identifier for the project tag */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the project tag */ + 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 tag 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 } + + fun userId(userId: String) = userId(JsonField.of(userId)) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + /** 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 } + + /** Date of project tag creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** 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 } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ProjectTag]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .userId() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectTag = + ProjectTag( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("userId", userId), + color, + created, + description, + 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 + } + + return other is ProjectTag && + id == other.id && + name == other.name && + projectId == other.projectId && + userId == other.userId && + color == other.color && + created == other.created && + description == other.description && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, name, projectId, userId, color, created, description, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ProjectTag{id=$id, name=$name, projectId=$projectId, userId=$userId, color=$color, created=$created, description=$description, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..d37bfca2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagCreateParams.kt @@ -0,0 +1,639 @@ +// 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.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.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 + +/** + * Create a new project_tag. If there is an existing project_tag in the project with the same name + * as the one specified in the request, will return the existing project_tag unmodified + */ +class ProjectTagCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the project tag + * + * @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 = body.name() + + /** + * Unique identifier for the project that the project tag 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 = body.projectId() + + /** + * 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 = body.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 = body.description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [color]. + * + * Unlike [color], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _color(): JsonField = body._color() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 project tag 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") + + /** + * 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") + + /** + * 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 [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 + + @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() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var color: 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 + color = body.color + description = body.description + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the project tag */ + 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 tag 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 } + + /** 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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), + color, + description, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + color() + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + projectId == other.projectId && + color == other.color && + description == other.description && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, projectId, color, description, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, color=$color, description=$description, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectTagCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectTagCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..94aa9d2d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParams.kt @@ -0,0 +1,237 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete a project_tag object by its id */ +class ProjectTagDeleteParams +private constructor( + private val projectTagId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** ProjectTag id */ + fun projectTagId(): Optional = Optional.ofNullable(projectTagId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectTagDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectTagDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagDeleteParams]. */ + class Builder internal constructor() { + + private var projectTagId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(projectTagDeleteParams: ProjectTagDeleteParams) = apply { + projectTagId = projectTagDeleteParams.projectTagId + additionalHeaders = projectTagDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = projectTagDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + projectTagDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** ProjectTag id */ + fun projectTagId(projectTagId: String?) = apply { this.projectTagId = projectTagId } + + /** Alias for calling [Builder.projectTagId] with `projectTagId.orElse(null)`. */ + fun projectTagId(projectTagId: Optional) = projectTagId(projectTagId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [ProjectTagDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectTagDeleteParams = + ProjectTagDeleteParams( + projectTagId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is ProjectTagDeleteParams && + projectTagId == other.projectTagId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash( + projectTagId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) + + override fun toString() = + "ProjectTagDeleteParams{projectTagId=$projectTagId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100755 index 00000000..cdc55b4e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPage.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.ProjectTagService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see ProjectTagService.list */ +class ProjectTagListPage +private constructor( + private val service: ProjectTagService, + private val params: ProjectTagListParams, + private val response: ProjectTagListPageResponse, +) : Page { + + /** + * Delegates to [ProjectTagListPageResponse], but gracefully handles missing data. + * + * @see ProjectTagListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ProjectTagListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): ProjectTagListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): ProjectTagListParams = params + + /** The response that this page was parsed from. */ + fun response(): ProjectTagListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectTagListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagListPage]. */ + class Builder internal constructor() { + + private var service: ProjectTagService? = null + private var params: ProjectTagListParams? = null + private var response: ProjectTagListPageResponse? = null + + @JvmSynthetic + internal fun from(projectTagListPage: ProjectTagListPage) = apply { + service = projectTagListPage.service + params = projectTagListPage.params + response = projectTagListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectTagListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..7d7621fc --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageAsync.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.ProjectTagServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see ProjectTagServiceAsync.list */ +class ProjectTagListPageAsync +private constructor( + private val service: ProjectTagServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: ProjectTagListParams, + private val response: ProjectTagListPageResponse, +) : PageAsync { + + /** + * Delegates to [ProjectTagListPageResponse], but gracefully handles missing data. + * + * @see ProjectTagListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ProjectTagListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): ProjectTagListParams = params + + /** The response that this page was parsed from. */ + fun response(): ProjectTagListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ProjectTagListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagListPageAsync]. */ + class Builder internal constructor() { + + private var service: ProjectTagServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ProjectTagListParams? = null + private var response: ProjectTagListPageResponse? = null + + @JvmSynthetic + internal fun from(projectTagListPageAsync: ProjectTagListPageAsync) = apply { + service = projectTagListPageAsync.service + streamHandlerExecutor = projectTagListPageAsync.streamHandlerExecutor + params = projectTagListPageAsync.params + response = projectTagListPageAsync.response + } + + fun service(service: ProjectTagServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ProjectTagListPageAsync = + ProjectTagListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectTagListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "ProjectTagListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..c3107b65 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is ProjectTagListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..5ff04cc3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagListParams.kt @@ -0,0 +1,434 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +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 + */ +class ProjectTagListParams +private constructor( + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val projectId: String?, + private val projectName: String?, + private val projectTagName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** Name of the project to search for */ + fun projectName(): Optional = Optional.ofNullable(projectName) + + /** Name of the project_tag to search for */ + fun projectTagName(): Optional = Optional.ofNullable(projectTagName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectTagListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectTagListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var projectId: String? = null + private var projectName: String? = null + private var projectTagName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(projectTagListParams: ProjectTagListParams) = apply { + endingBefore = projectTagListParams.endingBefore + ids = projectTagListParams.ids + limit = projectTagListParams.limit + orgName = projectTagListParams.orgName + projectId = projectTagListParams.projectId + projectName = projectTagListParams.projectName + projectTagName = projectTagListParams.projectTagName + startingAfter = projectTagListParams.startingAfter + additionalHeaders = projectTagListParams.additionalHeaders.toBuilder() + additionalQueryParams = projectTagListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) + + /** Name of the project to search for */ + fun projectName(projectName: String?) = apply { this.projectName = projectName } + + /** Alias for calling [Builder.projectName] with `projectName.orElse(null)`. */ + fun projectName(projectName: Optional) = projectName(projectName.getOrNull()) + + /** Name of the project_tag to search for */ + fun projectTagName(projectTagName: String?) = apply { this.projectTagName = projectTagName } + + /** Alias for calling [Builder.projectTagName] with `projectTagName.orElse(null)`. */ + fun projectTagName(projectTagName: Optional) = + projectTagName(projectTagName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ProjectTagListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectTagListParams = + ProjectTagListParams( + endingBefore, + ids, + limit, + orgName, + projectId, + projectName, + projectTagName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectTagListParams && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + projectId == other.projectId && + projectName == other.projectName && + projectTagName == other.projectTagName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + ids, + limit, + orgName, + projectId, + projectName, + projectTagName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ProjectTagListParams{endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, projectId=$projectId, projectName=$projectName, projectTagName=$projectTagName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..f3a0b0d2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParams.kt @@ -0,0 +1,640 @@ +// 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.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.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 + +/** + * Create or replace project_tag. If there is an existing project_tag in the project with the same + * name as the one specified in the request, will replace the existing project_tag with the provided + * fields + */ +class ProjectTagReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the project tag + * + * @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 = body.name() + + /** + * Unique identifier for the project that the project tag 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 = body.projectId() + + /** + * 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 = body.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 = body.description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [color]. + * + * Unlike [color], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _color(): JsonField = body._color() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 project tag 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") + + /** + * 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") + + /** + * 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 [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 + + @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() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var color: 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 + color = body.color + description = body.description + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the project tag */ + 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 tag 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 } + + /** 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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), + color, + description, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + color() + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + projectId == other.projectId && + color == other.color && + description == other.description && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, projectId, color, description, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, color=$color, description=$description, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ProjectTagReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectTagReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..474a8d22 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParams.kt @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a project_tag object by its id */ +class ProjectTagRetrieveParams +private constructor( + private val projectTagId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** ProjectTag id */ + fun projectTagId(): Optional = Optional.ofNullable(projectTagId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectTagRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectTagRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagRetrieveParams]. */ + class Builder internal constructor() { + + private var projectTagId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(projectTagRetrieveParams: ProjectTagRetrieveParams) = apply { + projectTagId = projectTagRetrieveParams.projectTagId + additionalHeaders = projectTagRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = projectTagRetrieveParams.additionalQueryParams.toBuilder() + } + + /** ProjectTag id */ + fun projectTagId(projectTagId: String?) = apply { this.projectTagId = projectTagId } + + /** Alias for calling [Builder.projectTagId] with `projectTagId.orElse(null)`. */ + fun projectTagId(projectTagId: Optional) = projectTagId(projectTagId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [ProjectTagRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectTagRetrieveParams = + ProjectTagRetrieveParams( + projectTagId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is ProjectTagRetrieveParams && + projectTagId == other.projectTagId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(projectTagId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectTagRetrieveParams{projectTagId=$projectTagId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..d767ab90 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParams.kt @@ -0,0 +1,565 @@ +// 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.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +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 + +/** + * Partially update a project_tag object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ +class ProjectTagUpdateParams +private constructor( + private val projectTagId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** ProjectTag id */ + fun projectTagId(): Optional = Optional.ofNullable(projectTagId) + + /** + * 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 = body.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 = body.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 = body.name() + + /** + * Returns the raw JSON value of [color]. + * + * Unlike [color], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _color(): JsonField = body._color() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): ProjectTagUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [ProjectTagUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ProjectTagUpdateParams]. */ + class Builder internal constructor() { + + private var projectTagId: 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(projectTagUpdateParams: ProjectTagUpdateParams) = apply { + projectTagId = projectTagUpdateParams.projectTagId + body = projectTagUpdateParams.body.toBuilder() + additionalHeaders = projectTagUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = projectTagUpdateParams.additionalQueryParams.toBuilder() + } + + /** ProjectTag id */ + fun projectTagId(projectTagId: String?) = apply { this.projectTagId = projectTagId } + + /** Alias for calling [Builder.projectTagId] with `projectTagId.orElse(null)`. */ + fun projectTagId(projectTagId: Optional) = projectTagId(projectTagId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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) } + + /** 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) } + + /** Name of the project tag */ + 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) } + + 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 [ProjectTagUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectTagUpdateParams = + ProjectTagUpdateParams( + projectTagId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 other is Body && + color == other.color && + description == other.description && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(color, description, name, additionalProperties) + } + + 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 + } + + return other is ProjectTagUpdateParams && + projectTagId == other.projectTagId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(projectTagId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectTagUpdateParams{projectTagId=$projectTagId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 old mode 100644 new mode 100755 index 5f762fcf..f9d70c38 --- 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 @@ -3,247 +3,500 @@ 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.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +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 com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Collections import java.util.Objects import java.util.Optional +import kotlin.jvm.optionals.getOrNull +/** + * Partially update a project object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ class ProjectUpdateParams -constructor( - private val projectId: String, - private val name: String?, - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, - private val additionalBodyProperties: Map, -) { +private constructor( + private val projectId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** + * 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 = body.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 = body.settings() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [settings]. + * + * Unlike [settings], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _settings(): JsonField = body._settings() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun projectId(): String = projectId + fun toBuilder() = Builder().from(this) + + companion object { - fun name(): Optional = Optional.ofNullable(name) + @JvmStatic fun none(): ProjectUpdateParams = builder().build() - @JvmSynthetic - internal fun getBody(): ProjectUpdateBody { - return ProjectUpdateBody(name, additionalBodyProperties) + /** Returns a mutable builder for constructing an instance of [ProjectUpdateParams]. */ + @JvmStatic fun builder() = Builder() } - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** A builder for [ProjectUpdateParams]. */ + class Builder internal constructor() { - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + 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 getPathParam(index: Int): String { - return when (index) { - 0 -> projectId - else -> "" + @JvmSynthetic + internal fun from(projectUpdateParams: ProjectUpdateParams) = apply { + projectId = projectUpdateParams.projectId + body = projectUpdateParams.body.toBuilder() + additionalHeaders = projectUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = projectUpdateParams.additionalQueryParams.toBuilder() } - } - @JsonDeserialize(builder = ProjectUpdateBody.Builder::class) - @NoAutoDetect - class ProjectUpdateBody - internal constructor( - private val name: String?, - private val additionalProperties: Map, - ) { + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) - private var hashCode: Int = 0 + /** + * 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 */ - @JsonProperty("name") fun name(): String? = name + 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) } + + /** + * Project settings. Patch operations replace all settings, so make sure you include all + * settings you want to keep. + */ + fun settings(settings: ProjectSettings?) = apply { body.settings(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 { body.settings(settings) } - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + body.additionalProperties(additionalBodyProperties) + } - fun toBuilder() = Builder().from(this) + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + body.putAdditionalProperty(key, value) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + body.putAllAdditionalProperties(additionalBodyProperties) } - return other is ProjectUpdateBody && - this.name == other.name && - this.additionalProperties == other.additionalProperties + fun removeAdditionalBodyProperty(key: String) = apply { body.removeAdditionalProperty(key) } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + body.removeAllAdditionalProperties(keys) } - override fun hashCode(): Int { - if (hashCode == 0) { - hashCode = Objects.hash(name, additionalProperties) - } - return hashCode + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) } - override fun toString() = - "ProjectUpdateBody{name=$name, additionalProperties=$additionalProperties}" + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - companion object { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - @JvmStatic fun builder() = Builder() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) } - class Builder { + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - private var name: String? = null - private var additionalProperties: MutableMap = mutableMapOf() + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } - @JvmSynthetic - internal fun from(projectUpdateBody: ProjectUpdateBody) = apply { - this.name = projectUpdateBody.name - additionalProperties(projectUpdateBody.additionalProperties) - } + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } - /** Name of the project */ - @JsonProperty("name") fun name(name: String) = apply { this.name = name } + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.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 build(): ProjectUpdateBody = - ProjectUpdateBody(name, additionalProperties.toUnmodifiable()) + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - } - - fun _additionalQueryParams(): Map> = additionalQueryParams - fun _additionalHeaders(): Map> = additionalHeaders + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - fun _additionalBodyProperties(): Map = additionalBodyProperties + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } - override fun equals(other: Any?): Boolean { - if (this === other) { - return true + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - return other is ProjectUpdateParams && - this.projectId == other.projectId && - this.name == other.name && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders && - this.additionalBodyProperties == other.additionalBodyProperties - } + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } - override fun hashCode(): Int { - return Objects.hash( - projectId, - name, - additionalQueryParams, - additionalHeaders, - additionalBodyProperties, - ) - } + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - override fun toString() = - "ProjectUpdateParams{projectId=$projectId, name=$name, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } - fun toBuilder() = Builder().from(this) + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } - companion object { + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } - @JvmStatic fun builder() = Builder() - } + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - @NoAutoDetect - class Builder { + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } - private var projectId: String? = null - private var name: String? = null - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() - private var additionalBodyProperties: MutableMap = mutableMapOf() + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } - @JvmSynthetic - internal fun from(projectUpdateParams: ProjectUpdateParams) = apply { - this.projectId = projectUpdateParams.projectId - this.name = projectUpdateParams.name - additionalQueryParams(projectUpdateParams.additionalQueryParams) - additionalHeaders(projectUpdateParams.additionalHeaders) - additionalBodyProperties(projectUpdateParams.additionalBodyProperties) + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) } - /** Project id */ - fun projectId(projectId: String) = apply { this.projectId = projectId } + /** + * Returns an immutable instance of [ProjectUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ProjectUpdateParams = + ProjectUpdateParams( + projectId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } - /** Name of the project */ - fun name(name: String) = apply { this.name = name } + fun _body(): Body = body - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun _pathParam(index: Int): String = + when (index) { + 0 -> projectId ?: "" + else -> "" } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) - } + override fun _headers(): Headers = additionalHeaders - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) - } + override fun _queryParams(): QueryParams = additionalQueryParams - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) - } + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val name: JsonField, + private val settings: JsonField, + private val additionalProperties: MutableMap, + ) { - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) - } + @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 - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) - } + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) - } + fun toBuilder() = Builder().from(this) + + companion object { - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + /** Returns a mutable builder for constructing an instance of [Body]. */ + @JvmStatic fun builder() = Builder() } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + /** A builder for [Body]. */ + class Builder internal constructor() { - fun additionalBodyProperties(additionalBodyProperties: Map) = apply { - this.additionalBodyProperties.clear() - this.additionalBodyProperties.putAll(additionalBodyProperties) + 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()) } - fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { - this.additionalBodyProperties.put(key, value) + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + settings().ifPresent { it.validate() } + validated = true } - fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = - apply { - this.additionalBodyProperties.putAll(additionalBodyProperties) + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false } - fun build(): ProjectUpdateParams = - ProjectUpdateParams( - checkNotNull(projectId) { "`projectId` is required but was not set" }, - name, - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalBodyProperties.toUnmodifiable(), - ) + /** + * Returns a 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 other is Body && + name == other.name && + settings == other.settings && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, settings, additionalProperties) } + + 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 + } + + return other is ProjectUpdateParams && + projectId == other.projectId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = + Objects.hash(projectId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ProjectUpdateParams{projectId=$projectId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 new file mode 100755 index 00000000..f39b3655 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Prompt.kt @@ -0,0 +1,1052 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class Prompt +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * The transaction id of an event is unique to the network operation that processed the event + * insertion. Transaction ids are monotonically increasing over time and can be used to retrieve + * a versioned snapshot of the prompt (see the `version` parameter) + * + * @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 _xactId(): String = _xactId.getRequired("_xact_id") + + /** + * A literal 'p' which identifies the object as a project 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 logId(): LogId = logId.getRequired("log_id") + + /** + * Name of 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 name(): String = name.getRequired("name") + + /** + * Unique identifier for the organization + * + * @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 orgId(): String = orgId.getRequired("org_id") + + /** + * 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") + + /** + * 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") + + /** + * Date of prompt creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * 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") + + /** + * @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") + + /** + * User-controlled metadata about the prompt + * + * @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") + + /** + * 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") + + /** + * 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 [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [_xactId]. + * + * Unlike [_xactId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("_xact_id") @ExcludeMissing fun __xactId(): JsonField = _xactId + + /** + * Returns the raw JSON value of [logId]. + * + * Unlike [logId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("log_id") @ExcludeMissing fun _logId(): JsonField = logId + + /** + * 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 [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [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 [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 [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [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 [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("function_type") + @ExcludeMissing + fun _functionType(): JsonField = functionType + + /** + * 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 [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 [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 [Prompt]. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .logId() + * .name() + * .orgId() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Prompt]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var _xactId: JsonField? = null + private var logId: JsonField? = null + private var name: JsonField? = null + private var orgId: JsonField? = null + private var projectId: JsonField? = null + private var slug: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var functionType: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var promptData: JsonField = JsonMissing.of() + private var tags: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(prompt: Prompt) = apply { + id = prompt.id + _xactId = prompt._xactId + logId = prompt.logId + name = prompt.name + orgId = prompt.orgId + projectId = prompt.projectId + slug = prompt.slug + created = prompt.created + description = prompt.description + functionType = prompt.functionType + metadata = prompt.metadata + promptData = prompt.promptData + tags = prompt.tags.map { it.toMutableList() } + additionalProperties = prompt.additionalProperties.toMutableMap() + } + + /** Unique identifier for the prompt */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** + * The transaction id of an event is unique to the network operation that processed the + * event insertion. Transaction ids are monotonically increasing over time and can be used + * to retrieve a versioned snapshot of the prompt (see the `version` parameter) + */ + fun _xactId(_xactId: String) = _xactId(JsonField.of(_xactId)) + + /** + * Sets [Builder._xactId] to an arbitrary JSON value. + * + * You should usually call [Builder._xactId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun _xactId(_xactId: JsonField) = apply { this._xactId = _xactId } + + /** A literal 'p' which identifies the object as a project prompt */ + fun logId(logId: LogId) = logId(JsonField.of(logId)) + + /** + * Sets [Builder.logId] to an arbitrary JSON value. + * + * You should usually call [Builder.logId] with a well-typed [LogId] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun logId(logId: JsonField) = apply { this.logId = logId } + + /** 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 organization */ + fun orgId(orgId: String) = orgId(JsonField.of(orgId)) + + /** + * 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 } + + /** 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 } + + /** Date of prompt creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** 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 + } + + /** User-controlled metadata about the prompt */ + 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 } + + /** 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 } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Prompt]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ._xactId() + * .logId() + * .name() + * .orgId() + * .projectId() + * .slug() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Prompt = + Prompt( + checkRequired("id", id), + checkRequired("_xactId", _xactId), + checkRequired("logId", logId), + checkRequired("name", name), + checkRequired("orgId", orgId), + checkRequired("projectId", projectId), + checkRequired("slug", slug), + created, + description, + functionType, + metadata, + promptData, + (tags ?: JsonMissing.of()).map { it.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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val P = of("p") + + @JvmStatic fun of(value: String) = LogId(JsonField.of(value)) + } + + /** An enum containing [LogId]'s known values. */ + enum class Known { + P + } + + /** + * An enum containing [LogId]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [LogId] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + P, + /** An enum member indicating that [LogId] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + P -> Value.P + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + P -> Known.P + else -> throw BraintrustInvalidDataException("Unknown LogId: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is LogId && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class FunctionType @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM = of("llm") + + @JvmField val SCORER = of("scorer") + + @JvmField val TASK = of("task") + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = FunctionType(JsonField.of(value)) + } + + /** An enum containing [FunctionType]'s known values. */ + enum class Known { + LLM, + SCORER, + TASK, + TOOL, + } + + /** + * An enum containing [FunctionType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [FunctionType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM, + SCORER, + TASK, + TOOL, + /** + * An enum member indicating that [FunctionType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM -> Value.LLM + SCORER -> Value.SCORER + TASK -> Value.TASK + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LLM -> Known.LLM + SCORER -> Known.SCORER + TASK -> Known.TASK + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown FunctionType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is FunctionType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + /** User-controlled metadata about the prompt */ + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Prompt && + id == other.id && + _xactId == other._xactId && + logId == other.logId && + name == other.name && + orgId == other.orgId && + projectId == other.projectId && + slug == other.slug && + created == other.created && + description == other.description && + functionType == other.functionType && + metadata == other.metadata && + promptData == other.promptData && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + _xactId, + logId, + name, + orgId, + projectId, + slug, + created, + description, + functionType, + metadata, + promptData, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Prompt{id=$id, _xactId=$_xactId, logId=$logId, name=$name, orgId=$orgId, projectId=$projectId, slug=$slug, created=$created, description=$description, functionType=$functionType, metadata=$metadata, promptData=$promptData, tags=$tags, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..cd63f886 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptCreateParams.kt @@ -0,0 +1,1028 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.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.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 + +/** + * Create a new prompt. If there is an existing prompt in the project with the same slug as the one + * specified in the request, will return the existing prompt unmodified + */ +class PromptCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of 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 name(): String = body.name() + + /** + * 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 = body.projectId() + + /** + * 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 = body.slug() + + /** + * 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 = body.description() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionType(): Optional = body.functionType() + + /** + * 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 = body.promptData() + + /** + * 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> = body.tags() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [slug]. + * + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _slug(): JsonField = body._slug() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionType(): JsonField = body._functionType() + + /** + * Returns the raw JSON value of [promptData]. + * + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _promptData(): JsonField = body._promptData() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PromptCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptCreateParams]. */ + 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(promptCreateParams: PromptCreateParams) = apply { + body = promptCreateParams.body.toBuilder() + additionalHeaders = promptCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = promptCreateParams.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] + * - [slug] + * - [description] + * - [functionType] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the prompt */ + 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 prompt 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) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(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 { 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()) + + /** + * 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 functionType(functionType: FunctionType?) = apply { body.functionType(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 { + 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()) + + /** + * 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 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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()) + + /** + * Name of 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 name(): String = name.getRequired("name") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * @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") + + /** + * 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") + + /** + * 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 [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 [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 [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 [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_type") + @ExcludeMissing + fun _functionType(): JsonField = functionType + + /** + * 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 [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]. + * + * 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 } + + /** 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 + } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + slug() + description() + functionType().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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + projectId, + slug, + description, + functionType, + promptData, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + 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) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM = of("llm") + + @JvmField val SCORER = of("scorer") + + @JvmField val TASK = of("task") + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = FunctionType(JsonField.of(value)) + } + + /** An enum containing [FunctionType]'s known values. */ + enum class Known { + LLM, + SCORER, + TASK, + TOOL, + } + + /** + * An enum containing [FunctionType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [FunctionType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM, + SCORER, + TASK, + TOOL, + /** + * An enum member indicating that [FunctionType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM -> Value.LLM + SCORER -> Value.SCORER + TASK -> Value.TASK + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LLM -> Known.LLM + SCORER -> Known.SCORER + TASK -> Known.TASK + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown FunctionType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is FunctionType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "PromptCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..0d628a7e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptData.kt @@ -0,0 +1,5957 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.allMaxBy +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.getOrThrow +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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** The prompt, model, and its parameters */ +class PromptData +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 = 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 = 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 = 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 = 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> = toolFunctions.getOptional("tool_functions") + + /** + * 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 + + /** + * 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 + + /** + * Returns the raw JSON value of [parser]. + * + * Unlike [parser], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("parser") @ExcludeMissing fun _parser(): JsonField = parser + + /** + * Returns the raw JSON value of [prompt]. + * + * Unlike [prompt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompt") @ExcludeMissing fun _prompt(): JsonField = prompt + + /** + * Returns the raw JSON value of [toolFunctions]. + * + * Unlike [toolFunctions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tool_functions") + @ExcludeMissing + fun _toolFunctions(): JsonField> = toolFunctions + + @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 [PromptData]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptData]. */ + class Builder internal constructor() { + + private var options: JsonField = JsonMissing.of() + private var origin: JsonField = JsonMissing.of() + private var parser: JsonField = JsonMissing.of() + private var prompt: JsonField = JsonMissing.of() + private var toolFunctions: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(promptData: PromptData) = apply { + options = promptData.options + origin = promptData.origin + parser = promptData.parser + prompt = promptData.prompt + toolFunctions = promptData.toolFunctions.map { it.toMutableList() } + additionalProperties = promptData.additionalProperties.toMutableMap() + } + + fun options(options: PromptOptions?) = options(JsonField.ofNullable(options)) + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) + + /** + * Sets [Builder.options] to an arbitrary JSON value. + * + * You should usually call [Builder.options] with a well-typed [PromptOptions] 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 origin(origin: Origin?) = origin(JsonField.ofNullable(origin)) + + /** Alias for calling [Builder.origin] with `origin.orElse(null)`. */ + fun origin(origin: Optional) = origin(origin.getOrNull()) + + /** + * 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 parser(parser: Parser?) = parser(JsonField.ofNullable(parser)) + + /** Alias for calling [Builder.parser] with `parser.orElse(null)`. */ + fun parser(parser: Optional) = parser(parser.getOrNull()) + + /** + * Sets [Builder.parser] to an arbitrary JSON value. + * + * You should usually call [Builder.parser] with a well-typed [Parser] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun parser(parser: JsonField) = apply { this.parser = parser } + + fun prompt(prompt: Prompt?) = prompt(JsonField.ofNullable(prompt)) + + /** Alias for calling [Builder.prompt] with `prompt.orElse(null)`. */ + fun prompt(prompt: Optional) = prompt(prompt.getOrNull()) + + /** + * Sets [Builder.prompt] to an arbitrary JSON value. + * + * You should usually call [Builder.prompt] with a well-typed [Prompt] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun prompt(prompt: JsonField) = apply { this.prompt = prompt } + + /** Alias for calling [prompt] with `Prompt.ofCompletion(completion)`. */ + fun prompt(completion: Prompt.Completion) = prompt(Prompt.ofCompletion(completion)) + + /** Alias for calling [prompt] with `Prompt.ofChat(chat)`. */ + fun prompt(chat: Prompt.Chat) = prompt(Prompt.ofChat(chat)) + + fun toolFunctions(toolFunctions: List?) = + toolFunctions(JsonField.ofNullable(toolFunctions)) + + /** Alias for calling [Builder.toolFunctions] with `toolFunctions.orElse(null)`. */ + fun toolFunctions(toolFunctions: Optional>) = + toolFunctions(toolFunctions.getOrNull()) + + /** + * Sets [Builder.toolFunctions] to an arbitrary JSON value. + * + * You should usually call [Builder.toolFunctions] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolFunctions(toolFunctions: JsonField>) = apply { + this.toolFunctions = toolFunctions.map { it.toMutableList() } + } + + /** + * Adds a single [ToolFunction] to [toolFunctions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addToolFunction(toolFunction: ToolFunction) = apply { + toolFunctions = + (toolFunctions ?: JsonField.of(mutableListOf())).also { + checkKnown("toolFunctions", it).add(toolFunction) + } + } + + /** Alias for calling [addToolFunction] with `ToolFunction.ofFunction(function)`. */ + fun addToolFunction(function: ToolFunction.Function) = + addToolFunction(ToolFunction.ofFunction(function)) + + /** Alias for calling [addToolFunction] with `ToolFunction.ofGlobal(global)`. */ + fun addToolFunction(global: ToolFunction.Global) = + addToolFunction(ToolFunction.ofGlobal(global)) + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [PromptData]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PromptData = + PromptData( + options, + origin, + parser, + prompt, + (toolFunctions ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = 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 = 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 = promptVersion.getOptional("prompt_version") + + /** + * 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 [promptId]. + * + * Unlike [promptId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("prompt_id") @ExcludeMissing fun _promptId(): JsonField = promptId + + /** + * Returns the raw JSON value of [promptVersion]. + * + * Unlike [promptVersion], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("prompt_version") + @ExcludeMissing + fun _promptVersion(): JsonField = promptVersion + + @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 [Origin]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Origin]. */ + class Builder internal constructor() { + + private var projectId: JsonField = JsonMissing.of() + private var promptId: JsonField = JsonMissing.of() + private var promptVersion: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(origin: Origin) = apply { + projectId = origin.projectId + promptId = origin.promptId + promptVersion = origin.promptVersion + additionalProperties = origin.additionalProperties.toMutableMap() + } + + 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 } + + fun promptId(promptId: String) = promptId(JsonField.of(promptId)) + + /** + * Sets [Builder.promptId] to an arbitrary JSON value. + * + * You should usually call [Builder.promptId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptId(promptId: JsonField) = apply { this.promptId = promptId } + + fun promptVersion(promptVersion: String) = promptVersion(JsonField.of(promptVersion)) + + /** + * Sets [Builder.promptVersion] to an arbitrary JSON value. + * + * You should usually call [Builder.promptVersion] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun promptVersion(promptVersion: JsonField) = apply { + this.promptVersion = promptVersion + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Origin]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Origin = + 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 + } + + return other is Origin && + projectId == other.projectId && + promptId == other.promptId && + promptVersion == other.promptVersion && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(projectId, promptId, promptVersion, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Origin{projectId=$projectId, promptId=$promptId, promptVersion=$promptVersion, additionalProperties=$additionalProperties}" + } + + class Parser + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun choiceScores(): ChoiceScores = choiceScores.getRequired("choice_scores") + + /** + * @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") + + /** + * @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 useCot(): Boolean = useCot.getRequired("use_cot") + + /** + * Returns the raw JSON value of [choiceScores]. + * + * Unlike [choiceScores], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("choice_scores") + @ExcludeMissing + fun _choiceScores(): JsonField = choiceScores + + /** + * 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 + + /** + * Returns the raw JSON value of [useCot]. + * + * Unlike [useCot], this method doesn't throw if the JSON field has an unexpected type. + */ + @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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Parser]. + * + * The following fields are required: + * ```java + * .choiceScores() + * .type() + * .useCot() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Parser]. */ + class Builder internal constructor() { + + private var choiceScores: JsonField? = null + private var type: JsonField? = null + private var useCot: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(parser: Parser) = apply { + choiceScores = parser.choiceScores + type = parser.type + useCot = parser.useCot + additionalProperties = parser.additionalProperties.toMutableMap() + } + + fun choiceScores(choiceScores: ChoiceScores) = choiceScores(JsonField.of(choiceScores)) + + /** + * Sets [Builder.choiceScores] to an arbitrary JSON value. + * + * You should usually call [Builder.choiceScores] with a well-typed [ChoiceScores] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun choiceScores(choiceScores: JsonField) = apply { + this.choiceScores = choiceScores + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun useCot(useCot: Boolean) = useCot(JsonField.of(useCot)) + + /** + * Sets [Builder.useCot] to an arbitrary JSON value. + * + * You should usually call [Builder.useCot] with a well-typed [Boolean] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun useCot(useCot: JsonField) = apply { this.useCot = useCot } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Parser]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .choiceScores() + * .type() + * .useCot() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Parser = + Parser( + checkRequired("choiceScores", choiceScores), + checkRequired("type", type), + checkRequired("useCot", useCot), + additionalProperties.toMutableMap(), + ) + } + + 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( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ChoiceScores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ChoiceScores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(choiceScores: ChoiceScores) = apply { + additionalProperties = choiceScores.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 [ChoiceScores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is ChoiceScores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ChoiceScores{additionalProperties=$additionalProperties}" + } + + class Type @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is + * on an older version than the API, then the API may respond with new members that the + * SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM_CLASSIFIER = of("llm_classifier") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + LLM_CLASSIFIER + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM_CLASSIFIER, + /** An enum member indicating that [Type] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you + * want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM_CLASSIFIER -> Value.LLM_CLASSIFIER + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + LLM_CLASSIFIER -> Known.LLM_CLASSIFIER + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have + * the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Parser && + choiceScores == other.choiceScores && + type == other.type && + useCot == other.useCot && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(choiceScores, type, useCot, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Parser{choiceScores=$choiceScores, type=$type, useCot=$useCot, additionalProperties=$additionalProperties}" + } + + @JsonDeserialize(using = Prompt.Deserializer::class) + @JsonSerialize(using = Prompt.Serializer::class) + class Prompt + private constructor( + private val completion: Completion? = null, + private val chat: Chat? = null, + private val _json: JsonValue? = null, + ) { + + fun completion(): Optional = Optional.ofNullable(completion) + + fun chat(): Optional = Optional.ofNullable(chat) + + fun isCompletion(): Boolean = completion != null + + fun isChat(): Boolean = chat != null + + fun asCompletion(): Completion = completion.getOrThrow("completion") + + fun asChat(): Chat = chat.getOrThrow("chat") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Prompt = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitCompletion(completion: Completion) { + completion.validate() + } + + override fun visitChat(chat: Chat) { + chat.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 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 + } + + return other is Prompt && completion == other.completion && chat == other.chat + } + + override fun hashCode(): Int = Objects.hash(completion, chat) + + override fun toString(): String = + when { + completion != null -> "Prompt{completion=$completion}" + chat != null -> "Prompt{chat=$chat}" + _json != null -> "Prompt{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Prompt") + } + + companion object { + + @JvmStatic fun ofCompletion(completion: Completion) = Prompt(completion = completion) + + @JvmStatic fun ofChat(chat: Chat) = Prompt(chat = chat) + } + + /** An interface that defines how to map each variant of [Prompt] to a value of type [T]. */ + interface Visitor { + + fun visitCompletion(completion: Completion): T + + fun visitChat(chat: Chat): T + + /** + * Maps an unknown variant of [Prompt] to a value of type [T]. + * + * An instance of [Prompt] 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 Prompt: $json") + } + } + + internal class Deserializer : BaseDeserializer(Prompt::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Prompt { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Prompt::class) { + + override fun serialize( + value: Prompt, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.completion != null -> generator.writeObject(value.completion) + value.chat != null -> generator.writeObject(value.chat) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Prompt") + } + } + } + + class Completion + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun content(): String = content.getRequired("content") + + /** + * @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") + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("content") @ExcludeMissing fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Completion]. + * + * The following fields are required: + * ```java + * .content() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Completion]. */ + class Builder internal constructor() { + + private var content: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(completion: Completion) = apply { + content = completion.content + type = completion.type + additionalProperties = completion.additionalProperties.toMutableMap() + } + + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Completion]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .content() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Completion = + Completion( + checkRequired("content", content), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val COMPLETION = of("completion") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + COMPLETION + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + COMPLETION, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + COMPLETION -> Value.COMPLETION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + COMPLETION -> Known.COMPLETION + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Completion && + content == other.content && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(content, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Completion{content=$content, type=$type, additionalProperties=$additionalProperties}" + } + + class Chat + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun messages(): List = messages.getRequired("messages") + + /** + * @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") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun tools(): Optional = tools.getOptional("tools") + + /** + * Returns the raw JSON value of [messages]. + * + * Unlike [messages], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("messages") + @ExcludeMissing + fun _messages(): JsonField> = messages + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + /** + * Returns the raw JSON value of [tools]. + * + * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField = tools + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Chat]. + * + * The following fields are required: + * ```java + * .messages() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Chat]. */ + class Builder internal constructor() { + + private var messages: JsonField>? = null + private var type: JsonField? = null + private var tools: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(chat: Chat) = apply { + messages = chat.messages.map { it.toMutableList() } + type = chat.type + tools = chat.tools + additionalProperties = chat.additionalProperties.toMutableMap() + } + + fun messages(messages: List) = messages(JsonField.of(messages)) + + /** + * Sets [Builder.messages] to an arbitrary JSON value. + * + * You should usually call [Builder.messages] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun messages(messages: JsonField>) = apply { + this.messages = messages.map { it.toMutableList() } + } + + /** + * Adds a single [Message] to [messages]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMessage(message: Message) = apply { + messages = + (messages ?: JsonField.of(mutableListOf())).also { + checkKnown("messages", it).add(message) + } + } + + /** Alias for calling [addMessage] with `Message.ofSystem(system)`. */ + fun addMessage(system: Message.System) = addMessage(Message.ofSystem(system)) + + /** Alias for calling [addMessage] with `Message.ofUser(user)`. */ + fun addMessage(user: Message.User) = addMessage(Message.ofUser(user)) + + /** Alias for calling [addMessage] with `Message.ofAssistant(assistant)`. */ + fun addMessage(assistant: Message.Assistant) = + addMessage(Message.ofAssistant(assistant)) + + /** Alias for calling [addMessage] with `Message.ofTool(tool)`. */ + fun addMessage(tool: Message.Tool) = addMessage(Message.ofTool(tool)) + + /** Alias for calling [addMessage] with `Message.ofFunction(function)`. */ + fun addMessage(function: Message.Function) = + addMessage(Message.ofFunction(function)) + + /** Alias for calling [addMessage] with `Message.ofFallback(fallback)`. */ + fun addMessage(fallback: Message.Fallback) = + addMessage(Message.ofFallback(fallback)) + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun tools(tools: String) = tools(JsonField.of(tools)) + + /** + * Sets [Builder.tools] to an arbitrary JSON value. + * + * You should usually call [Builder.tools] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun tools(tools: JsonField) = apply { this.tools = tools } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Chat]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .messages() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Chat = + Chat( + checkRequired("messages", messages).map { it.toImmutable() }, + checkRequired("type", type), + tools, + 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 + private constructor( + private val system: System? = null, + private val user: User? = null, + private val assistant: Assistant? = null, + private val tool: Tool? = null, + private val function: Function? = null, + private val fallback: Fallback? = null, + private val _json: JsonValue? = null, + ) { + + fun system(): Optional = Optional.ofNullable(system) + + fun user(): Optional = Optional.ofNullable(user) + + fun assistant(): Optional = Optional.ofNullable(assistant) + + fun tool(): Optional = Optional.ofNullable(tool) + + fun function(): Optional = Optional.ofNullable(function) + + fun fallback(): Optional = Optional.ofNullable(fallback) + + fun isSystem(): Boolean = system != null + + fun isUser(): Boolean = user != null + + fun isAssistant(): Boolean = assistant != null + + fun isTool(): Boolean = tool != null + + fun isFunction(): Boolean = function != null + + fun isFallback(): Boolean = fallback != null + + fun asSystem(): System = system.getOrThrow("system") + + fun asUser(): User = user.getOrThrow("user") + + fun asAssistant(): Assistant = assistant.getOrThrow("assistant") + + fun asTool(): Tool = tool.getOrThrow("tool") + + fun asFunction(): Function = function.getOrThrow("function") + + fun asFallback(): Fallback = fallback.getOrThrow("fallback") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + system != null -> visitor.visitSystem(system) + user != null -> visitor.visitUser(user) + assistant != null -> visitor.visitAssistant(assistant) + tool != null -> visitor.visitTool(tool) + function != null -> visitor.visitFunction(function) + fallback != null -> visitor.visitFallback(fallback) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Message = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitSystem(system: System) { + system.validate() + } + + override fun visitUser(user: User) { + user.validate() + } + + override fun visitAssistant(assistant: Assistant) { + assistant.validate() + } + + override fun visitTool(tool: Tool) { + tool.validate() + } + + override fun visitFunction(function: Function) { + function.validate() + } + + override fun visitFallback(fallback: Fallback) { + fallback.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 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 + } + + return other is Message && + system == other.system && + user == other.user && + assistant == other.assistant && + tool == other.tool && + function == other.function && + fallback == other.fallback + } + + override fun hashCode(): Int = + Objects.hash(system, user, assistant, tool, function, fallback) + + override fun toString(): String = + when { + system != null -> "Message{system=$system}" + user != null -> "Message{user=$user}" + assistant != null -> "Message{assistant=$assistant}" + tool != null -> "Message{tool=$tool}" + function != null -> "Message{function=$function}" + fallback != null -> "Message{fallback=$fallback}" + _json != null -> "Message{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Message") + } + + companion object { + + @JvmStatic fun ofSystem(system: System) = Message(system = system) + + @JvmStatic fun ofUser(user: User) = Message(user = user) + + @JvmStatic + fun ofAssistant(assistant: Assistant) = Message(assistant = assistant) + + @JvmStatic fun ofTool(tool: Tool) = Message(tool = tool) + + @JvmStatic fun ofFunction(function: Function) = Message(function = function) + + @JvmStatic fun ofFallback(fallback: Fallback) = Message(fallback = fallback) + } + + /** + * An interface that defines how to map each variant of [Message] to a value of type + * [T]. + */ + interface Visitor { + + fun visitSystem(system: System): T + + fun visitUser(user: User): T + + fun visitAssistant(assistant: Assistant): T + + fun visitTool(tool: Tool): T + + fun visitFunction(function: Function): T + + fun visitFallback(fallback: Fallback): T + + /** + * Maps an unknown variant of [Message] to a value of type [T]. + * + * An instance of [Message] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws BraintrustInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw BraintrustInvalidDataException("Unknown Message: $json") + } + } + + internal class Deserializer : BaseDeserializer(Message::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Message { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Message(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() + } + } + } + + internal class Serializer : BaseSerializer(Message::class) { + + override fun serialize( + value: Message, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.system != null -> generator.writeObject(value.system) + value.user != null -> generator.writeObject(value.user) + value.assistant != null -> generator.writeObject(value.assistant) + value.tool != null -> generator.writeObject(value.tool) + value.function != null -> generator.writeObject(value.function) + value.fallback != null -> generator.writeObject(value.fallback) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Message") + } + } + } + + class System + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws 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 [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("content") + @ExcludeMissing + fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @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 [System]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [System]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(system: System) = apply { + role = system.role + content = system.content + name = system.name + additionalProperties = system.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [System]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): System = + System( + checkRequired("role", role), + content, + name, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val SYSTEM = of("system") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + SYSTEM + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + SYSTEM, + /** + * An enum member indicating that [Role] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + SYSTEM -> Value.SYSTEM + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + SYSTEM -> Known.SYSTEM + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is System && + role == other.role && + content == other.content && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "System{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" + } + + class User + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws 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 [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("content") + @ExcludeMissing + fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @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 [User]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [User]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(user: User) = apply { + role = user.role + content = user.content + name = user.name + additionalProperties = user.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: Content) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [Content] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + /** Alias for calling [content] with `Content.ofText(text)`. */ + fun content(text: String) = content(Content.ofText(text)) + + /** Alias for calling [content] with `Content.ofArray(array)`. */ + fun contentOfArray(array: List) = + content(Content.ofArray(array)) + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [User]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): User = + User( + checkRequired("role", role), + content, + name, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val USER = of("user") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + USER + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + USER, + /** + * An enum member indicating that [Role] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + USER -> Value.USER + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + USER -> Known.USER + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + @JsonDeserialize(using = Content.Deserializer::class) + @JsonSerialize(using = Content.Serializer::class) + class Content + private constructor( + private val text: String? = null, + private val array: List? = null, + private val _json: JsonValue? = null, + ) { + + fun text(): Optional = Optional.ofNullable(text) + + fun array(): Optional> = + Optional.ofNullable(array) + + fun isText(): Boolean = text != null + + fun isArray(): Boolean = array != null + + fun asText(): String = text.getOrThrow("text") + + fun asArray(): List = array.getOrThrow("array") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Content = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitText(text: String) {} + + override fun visitArray( + array: List + ) { + array.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 = + 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 + } + + return other is Content && text == other.text && array == other.array + } + + override fun hashCode(): Int = Objects.hash(text, array) + + override fun toString(): String = + when { + text != null -> "Content{text=$text}" + array != null -> "Content{array=$array}" + _json != null -> "Content{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Content") + } + + companion object { + + @JvmStatic fun ofText(text: String) = Content(text = text) + + @JvmStatic + fun ofArray(array: List) = + Content(array = array.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [Content] to a value + * of type [T]. + */ + interface Visitor { + + fun visitText(text: String): T + + fun visitArray(array: List): T + + /** + * Maps an unknown variant of [Content] to a value of type [T]. + * + * An instance of [Content] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new variants that the SDK is unaware of. + * + * @throws BraintrustInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw BraintrustInvalidDataException("Unknown Content: $json") + } + } + + internal class Deserializer : BaseDeserializer(Content::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Content { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + Content(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() + } + } + } + + internal class Serializer : BaseSerializer(Content::class) { + + override fun serialize( + value: Content, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.text != null -> generator.writeObject(value.text) + value.array != null -> generator.writeObject(value.array) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Content") + } + } + } + + @JsonDeserialize(using = ChatCompletionContentPart.Deserializer::class) + @JsonSerialize(using = ChatCompletionContentPart.Serializer::class) + class ChatCompletionContentPart + private constructor( + private val text: ChatCompletionContentPartText? = null, + private val image: ChatCompletionContentPartImage? = null, + private val _json: JsonValue? = null, + ) { + + fun text(): Optional = + Optional.ofNullable(text) + + fun image(): Optional = + Optional.ofNullable(image) + + fun isText(): Boolean = text != null + + fun isImage(): Boolean = image != null + + fun asText(): ChatCompletionContentPartText = text.getOrThrow("text") + + fun asImage(): ChatCompletionContentPartImage = + image.getOrThrow("image") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + text != null -> visitor.visitText(text) + image != null -> visitor.visitImage(image) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): ChatCompletionContentPart = apply { + if (validated) { + return@apply + } + + accept( + 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.validity() + + override fun unknown(json: JsonValue?) = 0 + } + ) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ChatCompletionContentPart && + text == other.text && + image == other.image + } + + override fun hashCode(): Int = Objects.hash(text, image) + + override fun toString(): String = + when { + text != null -> "ChatCompletionContentPart{text=$text}" + image != null -> "ChatCompletionContentPart{image=$image}" + _json != null -> "ChatCompletionContentPart{_unknown=$_json}" + else -> + throw IllegalStateException( + "Invalid ChatCompletionContentPart" + ) + } + + companion object { + + @JvmStatic + fun ofText(text: ChatCompletionContentPartText) = + ChatCompletionContentPart(text = text) + + @JvmStatic + fun ofImage(image: ChatCompletionContentPartImage) = + ChatCompletionContentPart(image = image) + } + + /** + * An interface that defines how to map each variant of + * [ChatCompletionContentPart] to a value of type [T]. + */ + interface Visitor { + + fun visitText(text: ChatCompletionContentPartText): T + + fun visitImage(image: ChatCompletionContentPartImage): T + + /** + * Maps an unknown variant of [ChatCompletionContentPart] to a value + * of type [T]. + * + * An instance of [ChatCompletionContentPart] 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 ChatCompletionContentPart: $json" + ) + } + } + + internal class Deserializer : + BaseDeserializer( + ChatCompletionContentPart::class + ) { + + override fun ObjectCodec.deserialize( + node: JsonNode + ): ChatCompletionContentPart { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionContentPartText + >(), + ) + ?.let { + ChatCompletionContentPart( + text = it, + _json = json, + ) + }, + tryDeserialize( + node, + jacksonTypeRef< + ChatCompletionContentPartImage + >(), + ) + ?.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() + } + } + } + + internal class Serializer : + BaseSerializer( + ChatCompletionContentPart::class + ) { + + override fun serialize( + value: ChatCompletionContentPart, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.text != null -> generator.writeObject(value.text) + value.image != null -> generator.writeObject(value.image) + value._json != null -> generator.writeObject(value._json) + else -> + throw IllegalStateException( + "Invalid ChatCompletionContentPart" + ) + } + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is User && + role == other.role && + content == other.content && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "User{role=$role, content=$content, name=$name, additionalProperties=$additionalProperties}" + } + + class Assistant + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun functionCall(): Optional = + functionCall.getOptional("function_call") + + /** + * @throws 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 toolCalls(): Optional> = + toolCalls.getOptional("tool_calls") + + /** + * Returns the raw JSON value of [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("content") + @ExcludeMissing + fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("function_call") + @ExcludeMissing + fun _functionCall(): JsonField = functionCall + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [toolCalls]. + * + * Unlike [toolCalls], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("tool_calls") + @ExcludeMissing + fun _toolCalls(): JsonField> = toolCalls + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Assistant]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Assistant]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var functionCall: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var toolCalls: + JsonField>? = + null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(assistant: Assistant) = apply { + role = assistant.role + content = assistant.content + functionCall = assistant.functionCall + name = assistant.name + toolCalls = assistant.toolCalls.map { it.toMutableList() } + additionalProperties = assistant.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun functionCall(functionCall: FunctionCall?) = + functionCall(JsonField.ofNullable(functionCall)) + + /** + * Alias for calling [Builder.functionCall] with + * `functionCall.orElse(null)`. + */ + fun functionCall(functionCall: Optional) = + functionCall(functionCall.getOrNull()) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed + * [FunctionCall] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + this.functionCall = functionCall + } + + fun name(name: String?) = name(JsonField.ofNullable(name)) + + /** Alias for calling [Builder.name] with `name.orElse(null)`. */ + fun name(name: Optional) = name(name.getOrNull()) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun toolCalls(toolCalls: List?) = + toolCalls(JsonField.ofNullable(toolCalls)) + + /** Alias for calling [Builder.toolCalls] with `toolCalls.orElse(null)`. */ + fun toolCalls(toolCalls: Optional>) = + toolCalls(toolCalls.getOrNull()) + + /** + * Sets [Builder.toolCalls] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCalls] with a well-typed + * `List` value instead. This method is + * primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun toolCalls(toolCalls: JsonField>) = + apply { + this.toolCalls = toolCalls.map { it.toMutableList() } + } + + /** + * Adds a single [ChatCompletionMessageToolCall] to [toolCalls]. + * + * @throws IllegalStateException if the field was previously set to a + * non-list. + */ + fun addToolCall(toolCall: ChatCompletionMessageToolCall) = apply { + toolCalls = + (toolCalls ?: JsonField.of(mutableListOf())).also { + checkKnown("toolCalls", it).add(toolCall) + } + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Assistant]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Assistant = + Assistant( + checkRequired("role", role), + content, + functionCall, + name, + (toolCalls ?: JsonMissing.of()).map { it.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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val ASSISTANT = of("assistant") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + ASSISTANT + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + ASSISTANT, + /** + * An enum member indicating that [Role] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + ASSISTANT -> Value.ASSISTANT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + ASSISTANT -> Known.ASSISTANT + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class FunctionCall + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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). + */ + fun arguments(): String = arguments.getRequired("arguments") + + /** + * @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") + + /** + * Returns the raw JSON value of [arguments]. + * + * Unlike [arguments], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("arguments") + @ExcludeMissing + fun _arguments(): JsonField = arguments + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [FunctionCall]. + * + * The following fields are required: + * ```java + * .arguments() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [FunctionCall]. */ + class Builder internal constructor() { + + private var arguments: JsonField? = null + private var name: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(functionCall: FunctionCall) = apply { + arguments = functionCall.arguments + name = functionCall.name + additionalProperties = + functionCall.additionalProperties.toMutableMap() + } + + fun arguments(arguments: String) = arguments(JsonField.of(arguments)) + + /** + * Sets [Builder.arguments] to an arbitrary JSON value. + * + * You should usually call [Builder.arguments] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun arguments(arguments: JsonField) = apply { + this.arguments = arguments + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [FunctionCall]. + * + * Further updates to this [Builder] will not mutate the returned + * instance. + * + * The following fields are required: + * ```java + * .arguments() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): FunctionCall = + FunctionCall( + checkRequired("arguments", arguments), + checkRequired("name", name), + 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 + } + + return other is FunctionCall && + arguments == other.arguments && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(arguments, name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "FunctionCall{arguments=$arguments, name=$name, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Assistant && + role == other.role && + content == other.content && + functionCall == other.functionCall && + name == other.name && + toolCalls == other.toolCalls && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + role, + content, + functionCall, + name, + toolCalls, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Assistant{role=$role, content=$content, functionCall=$functionCall, name=$name, toolCalls=$toolCalls, additionalProperties=$additionalProperties}" + } + + class Tool + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun toolCallId(): Optional = toolCallId.getOptional("tool_call_id") + + /** + * Returns the raw JSON value of [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("content") + @ExcludeMissing + fun _content(): JsonField = content + + /** + * Returns the raw JSON value of [toolCallId]. + * + * Unlike [toolCallId], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("tool_call_id") + @ExcludeMissing + fun _toolCallId(): JsonField = toolCallId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Tool]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Tool]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var toolCallId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(tool: Tool) = apply { + role = tool.role + content = tool.content + toolCallId = tool.toolCallId + additionalProperties = tool.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun toolCallId(toolCallId: String) = toolCallId(JsonField.of(toolCallId)) + + /** + * Sets [Builder.toolCallId] to an arbitrary JSON value. + * + * You should usually call [Builder.toolCallId] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun toolCallId(toolCallId: JsonField) = apply { + this.toolCallId = toolCallId + } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Tool]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Tool = + Tool( + checkRequired("role", role), + content, + toolCallId, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + TOOL + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TOOL, + /** + * An enum member indicating that [Role] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Tool && + role == other.role && + content == other.content && + toolCallId == other.toolCallId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, toolCallId, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Tool{role=$role, content=$content, toolCallId=$toolCallId, additionalProperties=$additionalProperties}" + } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 + * an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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 role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * Returns the raw JSON value of [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 [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("content") + @ExcludeMissing + fun _content(): JsonField = content + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .name() + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + name = function.name + role = function.role + content = function.content + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String) = content(JsonField.of(content)) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("name", name), + checkRequired("role", role), + content, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FUNCTION, + /** + * An enum member indicating that [Role] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + name == other.name && + role == other.role && + content == other.content && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, role, content, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{name=$name, role=$role, content=$content, additionalProperties=$additionalProperties}" + } + + class Fallback + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 value). + */ + fun role(): Role = role.getRequired("role") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected + * type (e.g. if the server responded with an unexpected value). + */ + fun content(): Optional = content.getOptional("content") + + /** + * Returns the raw JSON value of [role]. + * + * Unlike [role], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("role") @ExcludeMissing fun _role(): JsonField = role + + /** + * Returns the raw JSON value of [content]. + * + * Unlike [content], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("content") + @ExcludeMissing + fun _content(): JsonField = content + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Fallback]. + * + * The following fields are required: + * ```java + * .role() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Fallback]. */ + class Builder internal constructor() { + + private var role: JsonField? = null + private var content: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(fallback: Fallback) = apply { + role = fallback.role + content = fallback.content + additionalProperties = fallback.additionalProperties.toMutableMap() + } + + fun role(role: Role) = role(JsonField.of(role)) + + /** + * Sets [Builder.role] to an arbitrary JSON value. + * + * You should usually call [Builder.role] with a well-typed [Role] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun role(role: JsonField) = apply { this.role = role } + + fun content(content: String?) = content(JsonField.ofNullable(content)) + + /** Alias for calling [Builder.content] with `content.orElse(null)`. */ + fun content(content: Optional) = content(content.getOrNull()) + + /** + * Sets [Builder.content] to an arbitrary JSON value. + * + * You should usually call [Builder.content] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun content(content: JsonField) = apply { this.content = content } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Fallback]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .role() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Fallback = + Fallback( + checkRequired("role", role), + content, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val MODEL = of("model") + + @JvmStatic fun of(value: String) = Role(JsonField.of(value)) + } + + /** An enum containing [Role]'s known values. */ + enum class Known { + MODEL + } + + /** + * An enum containing [Role]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Role] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + MODEL, + /** + * An enum member indicating that [Role] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + MODEL -> Value.MODEL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + MODEL -> Known.MODEL + else -> throw BraintrustInvalidDataException("Unknown Role: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Role && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Fallback && + role == other.role && + content == other.content && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(role, content, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Fallback{role=$role, content=$content, additionalProperties=$additionalProperties}" + } + } + + class Type @JsonCreator private constructor(private val value: JsonField) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CHAT = of("chat") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + CHAT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + CHAT, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + CHAT -> Value.CHAT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + CHAT -> Known.CHAT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Chat && + messages == other.messages && + type == other.type && + tools == other.tools && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(messages, type, tools, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Chat{messages=$messages, type=$type, tools=$tools, additionalProperties=$additionalProperties}" + } + } + + @JsonDeserialize(using = ToolFunction.Deserializer::class) + @JsonSerialize(using = ToolFunction.Serializer::class) + class ToolFunction + private constructor( + private val function: Function? = null, + private val global: Global? = null, + private val _json: JsonValue? = null, + ) { + + fun function(): Optional = Optional.ofNullable(function) + + fun global(): Optional = Optional.ofNullable(global) + + fun isFunction(): Boolean = function != null + + fun isGlobal(): Boolean = global != null + + fun asFunction(): Function = function.getOrThrow("function") + + fun asGlobal(): Global = global.getOrThrow("global") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): ToolFunction = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitFunction(function: Function) { + function.validate() + } + + override fun visitGlobal(global: Global) { + global.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 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 + } + + return other is ToolFunction && function == other.function && global == other.global + } + + override fun hashCode(): Int = Objects.hash(function, global) + + override fun toString(): String = + when { + function != null -> "ToolFunction{function=$function}" + global != null -> "ToolFunction{global=$global}" + _json != null -> "ToolFunction{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ToolFunction") + } + + companion object { + + @JvmStatic fun ofFunction(function: Function) = ToolFunction(function = function) + + @JvmStatic fun ofGlobal(global: Global) = ToolFunction(global = global) + } + + /** + * An interface that defines how to map each variant of [ToolFunction] to a value of type + * [T]. + */ + interface Visitor { + + fun visitFunction(function: Function): T + + fun visitGlobal(global: Global): T + + /** + * Maps an unknown variant of [ToolFunction] to a value of type [T]. + * + * An instance of [ToolFunction] 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 ToolFunction: $json") + } + } + + internal class Deserializer : BaseDeserializer(ToolFunction::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ToolFunction { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(ToolFunction::class) { + + override fun serialize( + value: ToolFunction, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.function != null -> generator.writeObject(value.function) + value.global != null -> generator.writeObject(value.global) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ToolFunction") + } + } + } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun id(): String = id.getRequired("id") + + /** + * @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") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .id() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + id = function.id + type = function.type + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("id", id), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FUNCTION, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + id == other.id && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(id, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{id=$id, type=$type, additionalProperties=$additionalProperties}" + } + + class Global + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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") + + /** + * 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 [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Global]. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Global]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(global: Global) = apply { + name = global.name + type = global.type + additionalProperties = global.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Global]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Global = + Global( + checkRequired("name", name), + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val GLOBAL = of("global") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + GLOBAL + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + GLOBAL, + /** + * An enum member indicating that [Type] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + GLOBAL -> Value.GLOBAL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + GLOBAL -> Known.GLOBAL + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Global && + name == other.name && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Global{name=$name, type=$type, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptData && + options == other.options && + origin == other.origin && + parser == other.parser && + prompt == other.prompt && + toolFunctions == other.toolFunctions && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(options, origin, parser, prompt, toolFunctions, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PromptData{options=$options, origin=$origin, parser=$parser, prompt=$prompt, toolFunctions=$toolFunctions, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..81450806 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete a prompt object by its id */ +class PromptDeleteParams +private constructor( + private val promptId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** Prompt id */ + fun promptId(): Optional = Optional.ofNullable(promptId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): PromptDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [PromptDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptDeleteParams]. */ + class Builder internal constructor() { + + private var promptId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(promptDeleteParams: PromptDeleteParams) = apply { + promptId = promptDeleteParams.promptId + additionalHeaders = promptDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = promptDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = promptDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** Prompt id */ + fun promptId(promptId: String?) = apply { this.promptId = promptId } + + /** Alias for calling [Builder.promptId] with `promptId.orElse(null)`. */ + fun promptId(promptId: Optional) = promptId(promptId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [PromptDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PromptDeleteParams = + PromptDeleteParams( + promptId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is PromptDeleteParams && + promptId == other.promptId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(promptId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "PromptDeleteParams{promptId=$promptId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100755 index 00000000..2999576f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPage.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.PromptService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see PromptService.list */ +class PromptListPage +private constructor( + private val service: PromptService, + private val params: PromptListParams, + private val response: PromptListPageResponse, +) : Page { + + /** + * Delegates to [PromptListPageResponse], but gracefully handles missing data. + * + * @see PromptListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): PromptListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): PromptListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): PromptListParams = params + + /** The response that this page was parsed from. */ + fun response(): PromptListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PromptListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptListPage]. */ + class Builder internal constructor() { + + private var service: PromptService? = null + private var params: PromptListParams? = null + private var response: PromptListPageResponse? = null + + @JvmSynthetic + internal fun from(promptListPage: PromptListPage) = apply { + service = promptListPage.service + params = promptListPage.params + response = promptListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..fca34922 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageAsync.kt @@ -0,0 +1,138 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.PromptServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see PromptServiceAsync.list */ +class PromptListPageAsync +private constructor( + private val service: PromptServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: PromptListParams, + private val response: PromptListPageResponse, +) : PageAsync { + + /** + * Delegates to [PromptListPageResponse], but gracefully handles missing data. + * + * @see PromptListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): PromptListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): PromptListParams = params + + /** The response that this page was parsed from. */ + fun response(): PromptListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PromptListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptListPageAsync]. */ + class Builder internal constructor() { + + private var service: PromptServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: PromptListParams? = null + private var response: PromptListPageResponse? = null + + @JvmSynthetic + internal fun from(promptListPageAsync: PromptListPageAsync) = apply { + service = promptListPageAsync.service + streamHandlerExecutor = promptListPageAsync.streamHandlerExecutor + params = promptListPageAsync.params + response = promptListPageAsync.response + } + + fun service(service: PromptServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): PromptListPageAsync = + PromptListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "PromptListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..86c17a00 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListPageResponse.kt @@ -0,0 +1,193 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is PromptListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..1f2ba2ba --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptListParams.kt @@ -0,0 +1,475 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all prompts. The prompts are sorted by creation date, with the most recently-created + * prompts coming first + */ +class PromptListParams +private constructor( + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val projectId: String?, + private val projectName: String?, + private val promptName: String?, + private val slug: String?, + private val startingAfter: String?, + private val version: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** Project id */ + fun projectId(): Optional = Optional.ofNullable(projectId) + + /** Name of the project to search for */ + fun projectName(): Optional = Optional.ofNullable(projectName) + + /** Name of the prompt to search for */ + fun promptName(): Optional = Optional.ofNullable(promptName) + + /** Retrieve prompt with a specific slug */ + fun slug(): Optional = Optional.ofNullable(slug) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** + * Retrieve prompt at a specific version. + * + * The version id can either be a transaction id (e.g. '1000192656880881099') or a version + * identifier (e.g. '81cd05ee665fdfb3'). + */ + fun version(): Optional = Optional.ofNullable(version) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): PromptListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [PromptListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var projectId: String? = null + private var projectName: String? = null + private var promptName: String? = null + private var slug: String? = null + private var startingAfter: String? = null + private var version: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(promptListParams: PromptListParams) = apply { + endingBefore = promptListParams.endingBefore + ids = promptListParams.ids + limit = promptListParams.limit + orgName = promptListParams.orgName + projectId = promptListParams.projectId + projectName = promptListParams.projectName + promptName = promptListParams.promptName + slug = promptListParams.slug + startingAfter = promptListParams.startingAfter + version = promptListParams.version + additionalHeaders = promptListParams.additionalHeaders.toBuilder() + additionalQueryParams = promptListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Project id */ + fun projectId(projectId: String?) = apply { this.projectId = projectId } + + /** Alias for calling [Builder.projectId] with `projectId.orElse(null)`. */ + fun projectId(projectId: Optional) = projectId(projectId.getOrNull()) + + /** Name of the project to search for */ + fun projectName(projectName: String?) = apply { this.projectName = projectName } + + /** Alias for calling [Builder.projectName] with `projectName.orElse(null)`. */ + fun projectName(projectName: Optional) = projectName(projectName.getOrNull()) + + /** Name of the prompt to search for */ + fun promptName(promptName: String?) = apply { this.promptName = promptName } + + /** Alias for calling [Builder.promptName] with `promptName.orElse(null)`. */ + fun promptName(promptName: Optional) = promptName(promptName.getOrNull()) + + /** Retrieve prompt with a specific slug */ + fun slug(slug: String?) = apply { this.slug = slug } + + /** Alias for calling [Builder.slug] with `slug.orElse(null)`. */ + fun slug(slug: Optional) = slug(slug.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + /** + * Retrieve prompt at a specific version. + * + * The version id can either be a transaction id (e.g. '1000192656880881099') or a version + * identifier (e.g. '81cd05ee665fdfb3'). + */ + fun version(version: String?) = apply { this.version = version } + + /** Alias for calling [Builder.version] with `version.orElse(null)`. */ + fun version(version: Optional) = version(version.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [PromptListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PromptListParams = + PromptListParams( + endingBefore, + ids, + limit, + orgName, + projectId, + projectName, + promptName, + slug, + startingAfter, + version, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptListParams && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + projectId == other.projectId && + projectName == other.projectName && + promptName == other.promptName && + slug == other.slug && + startingAfter == other.startingAfter && + version == other.version && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + ids, + limit, + orgName, + projectId, + projectName, + promptName, + slug, + startingAfter, + version, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "PromptListParams{endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, projectId=$projectId, projectName=$projectName, promptName=$promptName, slug=$slug, startingAfter=$startingAfter, version=$version, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..0034e601 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptOptions.kt @@ -0,0 +1,5519 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.BaseDeserializer +import com.braintrustdata.api.core.BaseSerializer +import com.braintrustdata.api.core.Enum +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.allMaxBy +import com.braintrustdata.api.core.checkKnown +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.getOrThrow +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 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.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +class PromptOptions +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 = 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 = 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 = position.getOptional("position") + + /** + * Returns the raw JSON value of [model]. + * + * Unlike [model], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("model") @ExcludeMissing fun _model(): JsonField = model + + /** + * Returns the raw JSON value of [params]. + * + * Unlike [params], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("params") @ExcludeMissing fun _params(): JsonField = params + + /** + * Returns the raw JSON value of [position]. + * + * Unlike [position], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("position") @ExcludeMissing fun _position(): JsonField = position + + @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 [PromptOptions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptOptions]. */ + class Builder internal constructor() { + + private var model: JsonField = JsonMissing.of() + private var params: JsonField = JsonMissing.of() + private var position: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(promptOptions: PromptOptions) = apply { + model = promptOptions.model + params = promptOptions.params + position = promptOptions.position + additionalProperties = promptOptions.additionalProperties.toMutableMap() + } + + fun model(model: String) = model(JsonField.of(model)) + + /** + * Sets [Builder.model] to an arbitrary JSON value. + * + * You should usually call [Builder.model] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun model(model: JsonField) = apply { this.model = model } + + fun params(params: Params) = params(JsonField.of(params)) + + /** + * Sets [Builder.params] to an arbitrary JSON value. + * + * You should usually call [Builder.params] with a well-typed [Params] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun params(params: JsonField) = apply { this.params = params } + + /** Alias for calling [params] with `Params.ofOpenAIModel(openaiModel)`. */ + fun params(openaiModel: Params.OpenAIModelParams) = + params(Params.ofOpenAIModel(openaiModel)) + + /** Alias for calling [params] with `Params.ofAnthropicModel(anthropicModel)`. */ + fun params(anthropicModel: Params.AnthropicModelParams) = + params(Params.ofAnthropicModel(anthropicModel)) + + /** Alias for calling [params] with `Params.ofGoogleModel(googleModel)`. */ + fun params(googleModel: Params.GoogleModelParams) = + params(Params.ofGoogleModel(googleModel)) + + /** Alias for calling [params] with `Params.ofWindowAiModel(windowAiModel)`. */ + fun params(windowAiModel: Params.WindowAiModelParams) = + params(Params.ofWindowAiModel(windowAiModel)) + + /** Alias for calling [params] with `Params.ofJsCompletion(jsCompletion)`. */ + fun params(jsCompletion: Params.JsCompletionParams) = + params(Params.ofJsCompletion(jsCompletion)) + + fun position(position: String) = position(JsonField.of(position)) + + /** + * Sets [Builder.position] to an arbitrary JSON value. + * + * You should usually call [Builder.position] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun position(position: JsonField) = apply { this.position = position } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [PromptOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PromptOptions = + 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 + private constructor( + private val openaiModel: OpenAIModelParams? = null, + private val anthropicModel: AnthropicModelParams? = null, + private val googleModel: GoogleModelParams? = null, + private val windowAiModel: WindowAiModelParams? = null, + private val jsCompletion: JsCompletionParams? = null, + private val _json: JsonValue? = null, + ) { + + fun openaiModel(): Optional = Optional.ofNullable(openaiModel) + + fun anthropicModel(): Optional = Optional.ofNullable(anthropicModel) + + fun googleModel(): Optional = Optional.ofNullable(googleModel) + + fun windowAiModel(): Optional = Optional.ofNullable(windowAiModel) + + fun jsCompletion(): Optional = Optional.ofNullable(jsCompletion) + + fun isOpenAIModel(): Boolean = openaiModel != null + + fun isAnthropicModel(): Boolean = anthropicModel != null + + fun isGoogleModel(): Boolean = googleModel != null + + fun isWindowAiModel(): Boolean = windowAiModel != null + + fun isJsCompletion(): Boolean = jsCompletion != null + + fun asOpenAIModel(): OpenAIModelParams = openaiModel.getOrThrow("openaiModel") + + fun asAnthropicModel(): AnthropicModelParams = anthropicModel.getOrThrow("anthropicModel") + + fun asGoogleModel(): GoogleModelParams = googleModel.getOrThrow("googleModel") + + fun asWindowAiModel(): WindowAiModelParams = windowAiModel.getOrThrow("windowAiModel") + + fun asJsCompletion(): JsCompletionParams = jsCompletion.getOrThrow("jsCompletion") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T = + when { + openaiModel != null -> visitor.visitOpenAIModel(openaiModel) + anthropicModel != null -> visitor.visitAnthropicModel(anthropicModel) + googleModel != null -> visitor.visitGoogleModel(googleModel) + windowAiModel != null -> visitor.visitWindowAiModel(windowAiModel) + jsCompletion != null -> visitor.visitJsCompletion(jsCompletion) + else -> visitor.unknown(_json) + } + + private var validated: Boolean = false + + fun validate(): Params = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitOpenAIModel(openaiModel: OpenAIModelParams) { + openaiModel.validate() + } + + override fun visitAnthropicModel(anthropicModel: AnthropicModelParams) { + anthropicModel.validate() + } + + override fun visitGoogleModel(googleModel: GoogleModelParams) { + googleModel.validate() + } + + override fun visitWindowAiModel(windowAiModel: WindowAiModelParams) { + windowAiModel.validate() + } + + override fun visitJsCompletion(jsCompletion: JsCompletionParams) { + jsCompletion.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 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 + } + + return other is Params && + openaiModel == other.openaiModel && + anthropicModel == other.anthropicModel && + googleModel == other.googleModel && + windowAiModel == other.windowAiModel && + jsCompletion == other.jsCompletion + } + + override fun hashCode(): Int = + Objects.hash(openaiModel, anthropicModel, googleModel, windowAiModel, jsCompletion) + + override fun toString(): String = + when { + openaiModel != null -> "Params{openaiModel=$openaiModel}" + anthropicModel != null -> "Params{anthropicModel=$anthropicModel}" + googleModel != null -> "Params{googleModel=$googleModel}" + windowAiModel != null -> "Params{windowAiModel=$windowAiModel}" + jsCompletion != null -> "Params{jsCompletion=$jsCompletion}" + _json != null -> "Params{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Params") + } + + companion object { + + @JvmStatic + fun ofOpenAIModel(openaiModel: OpenAIModelParams) = Params(openaiModel = openaiModel) + + @JvmStatic + fun ofAnthropicModel(anthropicModel: AnthropicModelParams) = + Params(anthropicModel = anthropicModel) + + @JvmStatic + fun ofGoogleModel(googleModel: GoogleModelParams) = Params(googleModel = googleModel) + + @JvmStatic + fun ofWindowAiModel(windowAiModel: WindowAiModelParams) = + Params(windowAiModel = windowAiModel) + + @JvmStatic + fun ofJsCompletion(jsCompletion: JsCompletionParams) = + Params(jsCompletion = jsCompletion) + } + + /** An interface that defines how to map each variant of [Params] to a value of type [T]. */ + interface Visitor { + + fun visitOpenAIModel(openaiModel: OpenAIModelParams): T + + fun visitAnthropicModel(anthropicModel: AnthropicModelParams): T + + fun visitGoogleModel(googleModel: GoogleModelParams): T + + fun visitWindowAiModel(windowAiModel: WindowAiModelParams): T + + fun visitJsCompletion(jsCompletion: JsCompletionParams): T + + /** + * Maps an unknown variant of [Params] to a value of type [T]. + * + * An instance of [Params] 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 Params: $json") + } + } + + internal class Deserializer : BaseDeserializer(Params::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Params { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Params::class) { + + override fun serialize( + value: Params, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.openaiModel != null -> generator.writeObject(value.openaiModel) + value.anthropicModel != null -> generator.writeObject(value.anthropicModel) + value.googleModel != null -> generator.writeObject(value.googleModel) + value.windowAiModel != null -> generator.writeObject(value.windowAiModel) + value.jsCompletion != null -> generator.writeObject(value.jsCompletion) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Params") + } + } + } + + class OpenAIModelParams + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = + 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 = functionCall.getOptional("function_call") + + /** + * The successor to max_tokens + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun maxCompletionTokens(): Optional = + 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 = 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 = 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 = + 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 = + 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 = + 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> = 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 = 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 = 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 = 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 = useCache.getOptional("use_cache") + + /** + * Returns the raw JSON value of [frequencyPenalty]. + * + * Unlike [frequencyPenalty], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("frequency_penalty") + @ExcludeMissing + fun _frequencyPenalty(): JsonField = frequencyPenalty + + /** + * Returns the raw JSON value of [functionCall]. + * + * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_call") + @ExcludeMissing + fun _functionCall(): JsonField = functionCall + + /** + * Returns the raw JSON value of [maxCompletionTokens]. + * + * Unlike [maxCompletionTokens], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("max_completion_tokens") + @ExcludeMissing + fun _maxCompletionTokens(): JsonField = maxCompletionTokens + + /** + * Returns the raw JSON value of [maxTokens]. + * + * Unlike [maxTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_tokens") + @ExcludeMissing + fun _maxTokens(): JsonField = maxTokens + + /** + * Returns the raw JSON value of [n]. + * + * Unlike [n], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("n") @ExcludeMissing fun _n(): JsonField = n + + /** + * Returns the raw JSON value of [presencePenalty]. + * + * Unlike [presencePenalty], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("presence_penalty") + @ExcludeMissing + fun _presencePenalty(): JsonField = presencePenalty + + /** + * Returns the raw JSON value of [reasoningEffort]. + * + * Unlike [reasoningEffort], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("reasoning_effort") + @ExcludeMissing + fun _reasoningEffort(): JsonField = reasoningEffort + + /** + * Returns the raw JSON value of [responseFormat]. + * + * Unlike [responseFormat], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("response_format") + @ExcludeMissing + fun _responseFormat(): JsonField = responseFormat + + /** + * Returns the raw JSON value of [stop]. + * + * Unlike [stop], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("stop") @ExcludeMissing fun _stop(): JsonField> = stop + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("temperature") + @ExcludeMissing + fun _temperature(): JsonField = temperature + + /** + * Returns the raw JSON value of [toolChoice]. + * + * Unlike [toolChoice], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("tool_choice") + @ExcludeMissing + fun _toolChoice(): JsonField = toolChoice + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_p") @ExcludeMissing fun _topP(): JsonField = topP + + /** + * Returns the raw JSON value of [useCache]. + * + * Unlike [useCache], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("use_cache") + @ExcludeMissing + fun _useCache(): JsonField = useCache + + @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 [OpenAIModelParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [OpenAIModelParams]. */ + class Builder internal constructor() { + + private var frequencyPenalty: JsonField = JsonMissing.of() + private var functionCall: JsonField = JsonMissing.of() + private var maxCompletionTokens: JsonField = JsonMissing.of() + private var maxTokens: JsonField = JsonMissing.of() + private var n: JsonField = JsonMissing.of() + private var presencePenalty: JsonField = JsonMissing.of() + private var reasoningEffort: JsonField = JsonMissing.of() + private var responseFormat: JsonField = JsonMissing.of() + private var stop: JsonField>? = null + private var temperature: JsonField = JsonMissing.of() + private var toolChoice: JsonField = JsonMissing.of() + private var topP: JsonField = JsonMissing.of() + private var useCache: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(openaiModelParams: OpenAIModelParams) = apply { + frequencyPenalty = openaiModelParams.frequencyPenalty + functionCall = openaiModelParams.functionCall + maxCompletionTokens = openaiModelParams.maxCompletionTokens + maxTokens = openaiModelParams.maxTokens + n = openaiModelParams.n + presencePenalty = openaiModelParams.presencePenalty + reasoningEffort = openaiModelParams.reasoningEffort + responseFormat = openaiModelParams.responseFormat + stop = openaiModelParams.stop.map { it.toMutableList() } + temperature = openaiModelParams.temperature + toolChoice = openaiModelParams.toolChoice + topP = openaiModelParams.topP + useCache = openaiModelParams.useCache + additionalProperties = openaiModelParams.additionalProperties.toMutableMap() + } + + fun frequencyPenalty(frequencyPenalty: Double) = + frequencyPenalty(JsonField.of(frequencyPenalty)) + + /** + * Sets [Builder.frequencyPenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.frequencyPenalty] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun frequencyPenalty(frequencyPenalty: JsonField) = apply { + this.frequencyPenalty = frequencyPenalty + } + + fun functionCall(functionCall: FunctionCall) = + functionCall(JsonField.of(functionCall)) + + /** + * Sets [Builder.functionCall] to an arbitrary JSON value. + * + * You should usually call [Builder.functionCall] with a well-typed [FunctionCall] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun functionCall(functionCall: JsonField) = apply { + this.functionCall = functionCall + } + + /** + * Alias for calling [functionCall] with + * `FunctionCall.ofUnionMember0(unionMember0)`. + */ + fun functionCall(unionMember0: FunctionCall.UnionMember0) = + functionCall(FunctionCall.ofUnionMember0(unionMember0)) + + /** Alias for calling [functionCall] with `FunctionCall.ofFunction(function)`. */ + fun functionCall(function: FunctionCall.Function) = + functionCall(FunctionCall.ofFunction(function)) + + /** The successor to max_tokens */ + fun maxCompletionTokens(maxCompletionTokens: Double) = + maxCompletionTokens(JsonField.of(maxCompletionTokens)) + + /** + * Sets [Builder.maxCompletionTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxCompletionTokens] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun maxCompletionTokens(maxCompletionTokens: JsonField) = apply { + this.maxCompletionTokens = maxCompletionTokens + } + + fun maxTokens(maxTokens: Double) = maxTokens(JsonField.of(maxTokens)) + + /** + * Sets [Builder.maxTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokens] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun maxTokens(maxTokens: JsonField) = apply { this.maxTokens = maxTokens } + + fun n(n: Double) = n(JsonField.of(n)) + + /** + * Sets [Builder.n] to an arbitrary JSON value. + * + * You should usually call [Builder.n] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun n(n: JsonField) = apply { this.n = n } + + fun presencePenalty(presencePenalty: Double) = + presencePenalty(JsonField.of(presencePenalty)) + + /** + * Sets [Builder.presencePenalty] to an arbitrary JSON value. + * + * You should usually call [Builder.presencePenalty] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun presencePenalty(presencePenalty: JsonField) = apply { + this.presencePenalty = presencePenalty + } + + fun reasoningEffort(reasoningEffort: ReasoningEffort) = + reasoningEffort(JsonField.of(reasoningEffort)) + + /** + * Sets [Builder.reasoningEffort] to an arbitrary JSON value. + * + * You should usually call [Builder.reasoningEffort] with a well-typed + * [ReasoningEffort] value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun reasoningEffort(reasoningEffort: JsonField) = apply { + this.reasoningEffort = reasoningEffort + } + + fun responseFormat(responseFormat: ResponseFormat?) = + responseFormat(JsonField.ofNullable(responseFormat)) + + /** + * Alias for calling [Builder.responseFormat] with `responseFormat.orElse(null)`. + */ + fun responseFormat(responseFormat: Optional) = + responseFormat(responseFormat.getOrNull()) + + /** + * Sets [Builder.responseFormat] to an arbitrary JSON value. + * + * You should usually call [Builder.responseFormat] with a well-typed + * [ResponseFormat] value instead. This method is primarily for setting the field to + * an undocumented or not yet supported value. + */ + fun responseFormat(responseFormat: JsonField) = apply { + this.responseFormat = responseFormat + } + + /** + * Alias for calling [responseFormat] with + * `ResponseFormat.ofJsonObject(jsonObject)`. + */ + fun responseFormat(jsonObject: ResponseFormat.JsonObject) = + responseFormat(ResponseFormat.ofJsonObject(jsonObject)) + + /** + * Alias for calling [responseFormat] with + * `ResponseFormat.ofJsonSchema(jsonSchema)`. + */ + fun responseFormat(jsonSchema: ResponseFormat.JsonSchema) = + responseFormat(ResponseFormat.ofJsonSchema(jsonSchema)) + + /** Alias for calling [responseFormat] with `ResponseFormat.ofText(text)`. */ + fun responseFormat(text: ResponseFormat.Text) = + responseFormat(ResponseFormat.ofText(text)) + + fun stop(stop: List) = stop(JsonField.of(stop)) + + /** + * Sets [Builder.stop] to an arbitrary JSON value. + * + * You should usually call [Builder.stop] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun stop(stop: JsonField>) = apply { + this.stop = stop.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.stop]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addStop(stop: String) = apply { + this.stop = + (this.stop ?: JsonField.of(mutableListOf())).also { + checkKnown("stop", it).add(stop) + } + } + + fun temperature(temperature: Double) = temperature(JsonField.of(temperature)) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun temperature(temperature: JsonField) = apply { + this.temperature = temperature + } + + fun toolChoice(toolChoice: ToolChoice) = toolChoice(JsonField.of(toolChoice)) + + /** + * Sets [Builder.toolChoice] to an arbitrary JSON value. + * + * You should usually call [Builder.toolChoice] with a well-typed [ToolChoice] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun toolChoice(toolChoice: JsonField) = apply { + this.toolChoice = toolChoice + } + + /** + * Alias for calling [toolChoice] with `ToolChoice.ofUnionMember0(unionMember0)`. + */ + fun toolChoice(unionMember0: ToolChoice.UnionMember0) = + toolChoice(ToolChoice.ofUnionMember0(unionMember0)) + + /** Alias for calling [toolChoice] with `ToolChoice.ofFunction(function)`. */ + fun toolChoice(function: ToolChoice.Function) = + toolChoice(ToolChoice.ofFunction(function)) + + fun topP(topP: Double) = topP(JsonField.of(topP)) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topP(topP: JsonField) = apply { this.topP = topP } + + fun useCache(useCache: Boolean) = useCache(JsonField.of(useCache)) + + /** + * Sets [Builder.useCache] to an arbitrary JSON value. + * + * You should usually call [Builder.useCache] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun useCache(useCache: JsonField) = apply { this.useCache = useCache } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [OpenAIModelParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): OpenAIModelParams = + OpenAIModelParams( + frequencyPenalty, + functionCall, + maxCompletionTokens, + maxTokens, + n, + presencePenalty, + reasoningEffort, + responseFormat, + (stop ?: JsonMissing.of()).map { it.toImmutable() }, + temperature, + toolChoice, + topP, + useCache, + 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 + private constructor( + private val unionMember0: UnionMember0? = null, + private val function: Function? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = Optional.ofNullable(unionMember0) + + fun function(): Optional = Optional.ofNullable(function) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isFunction(): Boolean = function != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asFunction(): Function = function.getOrThrow("function") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): FunctionCall = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitFunction(function: Function) { + function.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 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 + } + + return other is FunctionCall && + unionMember0 == other.unionMember0 && + function == other.function + } + + override fun hashCode(): Int = Objects.hash(unionMember0, function) + + override fun toString(): String = + when { + unionMember0 != null -> "FunctionCall{unionMember0=$unionMember0}" + function != null -> "FunctionCall{function=$function}" + _json != null -> "FunctionCall{_unknown=$_json}" + else -> throw IllegalStateException("Invalid FunctionCall") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + FunctionCall(unionMember0 = unionMember0) + + @JvmStatic + fun ofFunction(function: Function) = FunctionCall(function = function) + } + + /** + * An interface that defines how to map each variant of [FunctionCall] to a value of + * type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitFunction(function: Function): T + + /** + * Maps an unknown variant of [FunctionCall] to a value of type [T]. + * + * An instance of [FunctionCall] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws BraintrustInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw BraintrustInvalidDataException("Unknown FunctionCall: $json") + } + } + + internal class Deserializer : BaseDeserializer(FunctionCall::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): FunctionCall { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + FunctionCall(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() + } + } + } + + internal class Serializer : BaseSerializer(FunctionCall::class) { + + override fun serialize( + value: FunctionCall, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> generator.writeObject(value.unionMember0) + value.function != null -> generator.writeObject(value.function) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid FunctionCall") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val NONE = of("none") + + @JvmStatic fun of(value: String) = UnionMember0(JsonField.of(value)) + } + + /** An enum containing [UnionMember0]'s known values. */ + enum class Known { + AUTO, + NONE, + } + + /** + * An enum containing [UnionMember0]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [UnionMember0] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + NONE, + /** + * An enum member indicating that [UnionMember0] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + NONE -> Value.NONE + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a + * not a known member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + NONE -> Known.NONE + else -> + throw BraintrustInvalidDataException("Unknown UnionMember0: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does + * not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is UnionMember0 && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun name(): String = name.getRequired("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 + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + name = function.name + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("name", name), + 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 + } + + return other is Function && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{name=$name, additionalProperties=$additionalProperties}" + } + } + + class ReasoningEffort + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, if + * the SDK is on an older version than the API, then the API may respond with new + * members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LOW = of("low") + + @JvmField val MEDIUM = of("medium") + + @JvmField val HIGH = of("high") + + @JvmStatic fun of(value: String) = ReasoningEffort(JsonField.of(value)) + } + + /** An enum containing [ReasoningEffort]'s known values. */ + enum class Known { + LOW, + MEDIUM, + HIGH, + } + + /** + * An enum containing [ReasoningEffort]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [ReasoningEffort] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LOW, + MEDIUM, + HIGH, + /** + * An enum member indicating that [ReasoningEffort] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if + * you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LOW -> Value.LOW + MEDIUM -> Value.MEDIUM + HIGH -> Value.HIGH + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and + * don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a + * known member. + */ + fun known(): Known = + when (this) { + LOW -> Known.LOW + MEDIUM -> Known.MEDIUM + HIGH -> Known.HIGH + else -> + throw BraintrustInvalidDataException("Unknown ReasoningEffort: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not + * have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ReasoningEffort && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + @JsonDeserialize(using = ResponseFormat.Deserializer::class) + @JsonSerialize(using = ResponseFormat.Serializer::class) + class ResponseFormat + private constructor( + private val jsonObject: JsonObject? = null, + private val jsonSchema: JsonSchema? = null, + private val text: Text? = null, + private val _json: JsonValue? = null, + ) { + + fun jsonObject(): Optional = Optional.ofNullable(jsonObject) + + fun jsonSchema(): Optional = Optional.ofNullable(jsonSchema) + + fun text(): Optional = Optional.ofNullable(text) + + fun isJsonObject(): Boolean = jsonObject != null + + fun isJsonSchema(): Boolean = jsonSchema != null + + fun isText(): Boolean = text != null + + fun asJsonObject(): JsonObject = jsonObject.getOrThrow("jsonObject") + + fun asJsonSchema(): JsonSchema = jsonSchema.getOrThrow("jsonSchema") + + fun asText(): Text = text.getOrThrow("text") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): ResponseFormat = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitJsonObject(jsonObject: JsonObject) { + jsonObject.validate() + } + + override fun visitJsonSchema(jsonSchema: JsonSchema) { + jsonSchema.validate() + } + + override fun visitText(text: Text) { + text.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 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 + } + + return other is ResponseFormat && + jsonObject == other.jsonObject && + jsonSchema == other.jsonSchema && + text == other.text + } + + override fun hashCode(): Int = Objects.hash(jsonObject, jsonSchema, text) + + override fun toString(): String = + when { + jsonObject != null -> "ResponseFormat{jsonObject=$jsonObject}" + jsonSchema != null -> "ResponseFormat{jsonSchema=$jsonSchema}" + text != null -> "ResponseFormat{text=$text}" + _json != null -> "ResponseFormat{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ResponseFormat") + } + + companion object { + + @JvmStatic + fun ofJsonObject(jsonObject: JsonObject) = + ResponseFormat(jsonObject = jsonObject) + + @JvmStatic + fun ofJsonSchema(jsonSchema: JsonSchema) = + ResponseFormat(jsonSchema = jsonSchema) + + @JvmStatic fun ofText(text: Text) = ResponseFormat(text = text) + } + + /** + * An interface that defines how to map each variant of [ResponseFormat] to a value + * of type [T]. + */ + interface Visitor { + + fun visitJsonObject(jsonObject: JsonObject): T + + fun visitJsonSchema(jsonSchema: JsonSchema): T + + fun visitText(text: Text): T + + /** + * Maps an unknown variant of [ResponseFormat] to a value of type [T]. + * + * An instance of [ResponseFormat] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws BraintrustInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw BraintrustInvalidDataException("Unknown ResponseFormat: $json") + } + } + + internal class Deserializer : + BaseDeserializer(ResponseFormat::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ResponseFormat { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + ResponseFormat(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() + } + } + } + + internal class Serializer : BaseSerializer(ResponseFormat::class) { + + override fun serialize( + value: ResponseFormat, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.jsonObject != null -> generator.writeObject(value.jsonObject) + value.jsonSchema != null -> generator.writeObject(value.jsonSchema) + value.text != null -> generator.writeObject(value.text) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ResponseFormat") + } + } + } + + class JsonObject + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [JsonObject]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [JsonObject]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(jsonObject: JsonObject) = apply { + type = jsonObject.type + additionalProperties = jsonObject.additionalProperties.toMutableMap() + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [JsonObject]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): JsonObject = + JsonObject( + checkRequired("type", type), + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val JSON_OBJECT = of("json_object") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + JSON_OBJECT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + JSON_OBJECT, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + JSON_OBJECT -> Value.JSON_OBJECT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + JSON_OBJECT -> Known.JSON_OBJECT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JsonObject && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "JsonObject{type=$type, additionalProperties=$additionalProperties}" + } + + class JsonSchema + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun jsonSchema(): InnerJsonSchema = jsonSchema.getRequired("json_schema") + + /** + * @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") + + /** + * Returns the raw JSON value of [jsonSchema]. + * + * Unlike [jsonSchema], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("json_schema") + @ExcludeMissing + fun _jsonSchema(): JsonField = jsonSchema + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [JsonSchema]. + * + * The following fields are required: + * ```java + * .jsonSchema() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [JsonSchema]. */ + class Builder internal constructor() { + + private var jsonSchema: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(jsonSchema: JsonSchema) = apply { + this.jsonSchema = jsonSchema.jsonSchema + type = jsonSchema.type + additionalProperties = jsonSchema.additionalProperties.toMutableMap() + } + + fun jsonSchema(jsonSchema: InnerJsonSchema) = + jsonSchema(JsonField.of(jsonSchema)) + + /** + * Sets [Builder.jsonSchema] to an arbitrary JSON value. + * + * You should usually call [Builder.jsonSchema] with a well-typed + * [InnerJsonSchema] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun jsonSchema(jsonSchema: JsonField) = apply { + this.jsonSchema = jsonSchema + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [JsonSchema]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .jsonSchema() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): JsonSchema = + JsonSchema( + checkRequired("jsonSchema", jsonSchema), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @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") + + /** + * @throws BraintrustInvalidDataException if the JSON field has an + * unexpected type (e.g. if the server responded with an unexpected + * value). + */ + 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 = strict.getOptional("strict") + + /** + * 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 [schema]. + * + * Unlike [schema], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("schema") + @ExcludeMissing + fun _schema(): JsonField = schema + + /** + * Returns the raw JSON value of [strict]. + * + * Unlike [strict], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("strict") + @ExcludeMissing + fun _strict(): JsonField = strict + + @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 + * [InnerJsonSchema]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InnerJsonSchema]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var schema: JsonField = JsonMissing.of() + private var strict: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(innerJsonSchema: InnerJsonSchema) = apply { + name = innerJsonSchema.name + description = innerJsonSchema.description + schema = innerJsonSchema.schema + strict = innerJsonSchema.strict + additionalProperties = + innerJsonSchema.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun description(description: String) = + description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed + * [String] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + + fun schema(schema: Schema) = schema(JsonField.of(schema)) + + /** + * Sets [Builder.schema] to an arbitrary JSON value. + * + * You should usually call [Builder.schema] with a well-typed [Schema] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun schema(schema: JsonField) = apply { this.schema = schema } + + /** Alias for calling [schema] with `Schema.ofObject(object_)`. */ + fun schema(object_: Schema.Object) = schema(Schema.ofObject(object_)) + + /** Alias for calling [schema] with `Schema.ofString(string)`. */ + fun schema(string: String) = schema(Schema.ofString(string)) + + fun strict(strict: Boolean?) = strict(JsonField.ofNullable(strict)) + + /** + * Alias for [Builder.strict]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun strict(strict: Boolean) = strict(strict as Boolean?) + + /** Alias for calling [Builder.strict] with `strict.orElse(null)`. */ + fun strict(strict: Optional) = strict(strict.getOrNull()) + + /** + * Sets [Builder.strict] to an arbitrary JSON value. + * + * You should usually call [Builder.strict] with a well-typed [Boolean] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun strict(strict: JsonField) = apply { this.strict = strict } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InnerJsonSchema]. + * + * 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(): InnerJsonSchema = + InnerJsonSchema( + checkRequired("name", name), + description, + schema, + strict, + 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 + private constructor( + private val object_: Object? = null, + private val string: String? = null, + private val _json: JsonValue? = null, + ) { + + fun object_(): Optional = Optional.ofNullable(object_) + + fun string(): Optional = Optional.ofNullable(string) + + fun isObject(): Boolean = object_ != null + + fun isString(): Boolean = string != null + + fun asObject(): Object = object_.getOrThrow("object_") + + fun asString(): String = string.getOrThrow("string") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): Schema = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitObject(object_: Object) { + object_.validate() + } + + override fun visitString(string: String) {} + } + ) + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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 + } + + return other is Schema && + object_ == other.object_ && + string == other.string + } + + override fun hashCode(): Int = Objects.hash(object_, string) + + override fun toString(): String = + when { + object_ != null -> "Schema{object_=$object_}" + string != null -> "Schema{string=$string}" + _json != null -> "Schema{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Schema") + } + + companion object { + + @JvmStatic fun ofObject(object_: Object) = Schema(object_ = object_) + + @JvmStatic fun ofString(string: String) = Schema(string = string) + } + + /** + * An interface that defines how to map each variant of [Schema] to a + * value of type [T]. + */ + interface Visitor { + + fun visitObject(object_: Object): T + + fun visitString(string: String): T + + /** + * Maps an unknown variant of [Schema] to a value of type [T]. + * + * An instance of [Schema] 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 Schema: $json") + } + } + + internal class Deserializer : BaseDeserializer(Schema::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Schema { + val json = JsonValue.fromJsonNode(node) + + 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() + } + } + } + + internal class Serializer : BaseSerializer(Schema::class) { + + override fun serialize( + value: Schema, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.object_ != null -> + generator.writeObject(value.object_) + value.string != null -> generator.writeObject(value.string) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Schema") + } + } + } + + class Object + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of + * [Object]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Object]. */ + class Builder internal constructor() { + + private var additionalProperties: + MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(object_: Object) = apply { + additionalProperties = + object_.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 [Object]. + * + * Further updates to this [Builder] will not mutate the + * returned instance. + */ + 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 + } + + return other is Object && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Object{additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InnerJsonSchema && + name == other.name && + description == other.description && + schema == other.schema && + strict == other.strict && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, description, schema, strict, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InnerJsonSchema{name=$name, description=$description, schema=$schema, strict=$strict, additionalProperties=$additionalProperties}" + } + + class Type + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val JSON_SCHEMA = of("json_schema") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + JSON_SCHEMA + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + JSON_SCHEMA, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + JSON_SCHEMA -> Value.JSON_SCHEMA + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + JSON_SCHEMA -> Known.JSON_SCHEMA + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is JsonSchema && + jsonSchema == other.jsonSchema && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(jsonSchema, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "JsonSchema{jsonSchema=$jsonSchema, type=$type, additionalProperties=$additionalProperties}" + } + + class Text + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 value). + */ + fun type(): Type = type.getRequired("type") + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Text]. + * + * The following fields are required: + * ```java + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Text]. */ + class Builder internal constructor() { + + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(text: Text) = apply { + type = text.type + additionalProperties = text.additionalProperties.toMutableMap() + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Text]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Text = + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val TEXT = of("text") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + TEXT + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + TEXT, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + TEXT -> Value.TEXT + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + TEXT -> Known.TEXT + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Text && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Text{type=$type, additionalProperties=$additionalProperties}" + } + } + + @JsonDeserialize(using = ToolChoice.Deserializer::class) + @JsonSerialize(using = ToolChoice.Serializer::class) + class ToolChoice + private constructor( + private val unionMember0: UnionMember0? = null, + private val function: Function? = null, + private val _json: JsonValue? = null, + ) { + + fun unionMember0(): Optional = Optional.ofNullable(unionMember0) + + fun function(): Optional = Optional.ofNullable(function) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isFunction(): Boolean = function != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asFunction(): Function = function.getOrThrow("function") + + fun _json(): Optional = Optional.ofNullable(_json) + + 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 + + fun validate(): ToolChoice = apply { + if (validated) { + return@apply + } + + accept( + object : Visitor { + override fun visitUnionMember0(unionMember0: UnionMember0) { + unionMember0.validate() + } + + override fun visitFunction(function: Function) { + function.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 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 + } + + return other is ToolChoice && + unionMember0 == other.unionMember0 && + function == other.function + } + + override fun hashCode(): Int = Objects.hash(unionMember0, function) + + override fun toString(): String = + when { + unionMember0 != null -> "ToolChoice{unionMember0=$unionMember0}" + function != null -> "ToolChoice{function=$function}" + _json != null -> "ToolChoice{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ToolChoice") + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + ToolChoice(unionMember0 = unionMember0) + + @JvmStatic fun ofFunction(function: Function) = ToolChoice(function = function) + } + + /** + * An interface that defines how to map each variant of [ToolChoice] to a value of + * type [T]. + */ + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitFunction(function: Function): T + + /** + * Maps an unknown variant of [ToolChoice] to a value of type [T]. + * + * An instance of [ToolChoice] can contain an unknown variant if it was + * deserialized from data that doesn't match any known variant. For example, if + * the SDK is on an older version than the API, then the API may respond with + * new variants that the SDK is unaware of. + * + * @throws BraintrustInvalidDataException in the default implementation. + */ + fun unknown(json: JsonValue?): T { + throw BraintrustInvalidDataException("Unknown ToolChoice: $json") + } + } + + internal class Deserializer : BaseDeserializer(ToolChoice::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ToolChoice { + val json = JsonValue.fromJsonNode(node) + + val bestMatches = + sequenceOf( + tryDeserialize(node, jacksonTypeRef())?.let { + ToolChoice(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() + } + } + } + + internal class Serializer : BaseSerializer(ToolChoice::class) { + + override fun serialize( + value: ToolChoice, + generator: JsonGenerator, + provider: SerializerProvider, + ) { + when { + value.unionMember0 != null -> generator.writeObject(value.unionMember0) + value.function != null -> generator.writeObject(value.function) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ToolChoice") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that + * doesn't match any known member, and you want to know that value. For example, + * if the SDK is on an older version than the API, then the API may respond with + * new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val AUTO = of("auto") + + @JvmField val NONE = of("none") + + @JvmField val REQUIRED = of("required") + + @JvmStatic fun of(value: String) = UnionMember0(JsonField.of(value)) + } + + /** An enum containing [UnionMember0]'s known values. */ + enum class Known { + AUTO, + NONE, + REQUIRED, + } + + /** + * An enum containing [UnionMember0]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [UnionMember0] can contain an unknown value in a couple of + * cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + AUTO, + NONE, + REQUIRED, + /** + * An enum member indicating that [UnionMember0] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or + * if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + NONE -> Value.NONE + REQUIRED -> Value.REQUIRED + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known + * and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a + * not a known member. + */ + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + NONE -> Known.NONE + REQUIRED -> Known.REQUIRED + else -> + throw BraintrustInvalidDataException("Unknown UnionMember0: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for + * debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does + * not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is UnionMember0 && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Function + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * an unexpected value). + */ + fun function(): InnerFunction = function.getRequired("function") + + /** + * @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") + + /** + * Returns the raw JSON value of [function]. + * + * Unlike [function], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("function") + @ExcludeMissing + fun _function(): JsonField = function + + /** + * Returns the raw JSON value of [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Function]. + * + * The following fields are required: + * ```java + * .function() + * .type() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Function]. */ + class Builder internal constructor() { + + private var function: JsonField? = null + private var type: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(function: Function) = apply { + this.function = function.function + type = function.type + additionalProperties = function.additionalProperties.toMutableMap() + } + + fun function(function: InnerFunction) = function(JsonField.of(function)) + + /** + * Sets [Builder.function] to an arbitrary JSON value. + * + * You should usually call [Builder.function] with a well-typed + * [InnerFunction] value instead. This method is primarily for setting the + * field to an undocumented or not yet supported value. + */ + fun function(function: JsonField) = apply { + this.function = function + } + + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Sets [Builder.type] to an arbitrary JSON value. + * + * You should usually call [Builder.type] with a well-typed [Type] value + * instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Function]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .function() + * .type() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Function = + Function( + checkRequired("function", function), + checkRequired("type", type), + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 an unexpected value). + */ + fun name(): String = name.getRequired("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 + + @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 + * [InnerFunction]. + * + * The following fields are required: + * ```java + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InnerFunction]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var additionalProperties: MutableMap = + mutableMapOf() + + @JvmSynthetic + internal fun from(innerFunction: InnerFunction) = apply { + name = innerFunction.name + additionalProperties = + innerFunction.additionalProperties.toMutableMap() + } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] + * value instead. This method is primarily for setting the field to an + * undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun additionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties( + additionalProperties: Map + ) = apply { this.additionalProperties.putAll(additionalProperties) } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InnerFunction]. + * + * 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(): InnerFunction = + InnerFunction( + checkRequired("name", name), + 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 + } + + return other is InnerFunction && + name == other.name && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InnerFunction{name=$name, additionalProperties=$additionalProperties}" + } + + class Type + @JsonCreator + private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data + * that doesn't match any known member, and you want to know that value. For + * example, if the SDK is on an older version than the API, then the API may + * respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue + fun _value(): JsonField = value + + companion object { + + @JvmField val FUNCTION = of("function") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + /** An enum containing [Type]'s known values. */ + enum class Known { + FUNCTION + } + + /** + * An enum containing [Type]'s known values, as well as an [_UNKNOWN] + * member. + * + * An instance of [Type] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For + * example, if the SDK is on an older version than the API, then the API + * may respond with new members that the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + FUNCTION, + /** + * An enum member indicating that [Type] was instantiated with an + * unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or + * [Value._UNKNOWN] if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always + * known or if you want to throw for the unknown case. + */ + fun value(): Value = + when (this) { + FUNCTION -> Value.FUNCTION + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always + * known and don't want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is + * a not a known member. + */ + fun known(): Known = + when (this) { + FUNCTION -> Known.FUNCTION + else -> throw BraintrustInvalidDataException("Unknown Type: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily + * for debugging and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value + * does not have the expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is Type && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Function && + function == other.function && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(function, type, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Function{function=$function, type=$type, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is OpenAIModelParams && + frequencyPenalty == other.frequencyPenalty && + functionCall == other.functionCall && + maxCompletionTokens == other.maxCompletionTokens && + maxTokens == other.maxTokens && + n == other.n && + presencePenalty == other.presencePenalty && + reasoningEffort == other.reasoningEffort && + responseFormat == other.responseFormat && + stop == other.stop && + temperature == other.temperature && + toolChoice == other.toolChoice && + topP == other.topP && + useCache == other.useCache && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + frequencyPenalty, + functionCall, + maxCompletionTokens, + maxTokens, + n, + presencePenalty, + reasoningEffort, + responseFormat, + stop, + temperature, + toolChoice, + topP, + useCache, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "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}" + } + + class AnthropicModelParams + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * value). + */ + fun maxTokens(): Double = maxTokens.getRequired("max_tokens") + + /** + * @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 temperature(): Double = temperature.getRequired("temperature") + + /** + * This is a legacy parameter that should not be used. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. + * if the server responded with an unexpected value). + */ + fun maxTokensToSample(): Optional = + 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> = + 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 = 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 = 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 = useCache.getOptional("use_cache") + + /** + * Returns the raw JSON value of [maxTokens]. + * + * Unlike [maxTokens], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("max_tokens") + @ExcludeMissing + fun _maxTokens(): JsonField = maxTokens + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("temperature") + @ExcludeMissing + fun _temperature(): JsonField = temperature + + /** + * Returns the raw JSON value of [maxTokensToSample]. + * + * Unlike [maxTokensToSample], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("max_tokens_to_sample") + @ExcludeMissing + fun _maxTokensToSample(): JsonField = maxTokensToSample + + /** + * Returns the raw JSON value of [stopSequences]. + * + * Unlike [stopSequences], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("stop_sequences") + @ExcludeMissing + fun _stopSequences(): JsonField> = stopSequences + + /** + * Returns the raw JSON value of [topK]. + * + * Unlike [topK], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_k") @ExcludeMissing fun _topK(): JsonField = topK + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("top_p") @ExcludeMissing fun _topP(): JsonField = topP + + /** + * Returns the raw JSON value of [useCache]. + * + * Unlike [useCache], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("use_cache") + @ExcludeMissing + fun _useCache(): JsonField = useCache + + @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 [AnthropicModelParams]. + * + * The following fields are required: + * ```java + * .maxTokens() + * .temperature() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AnthropicModelParams]. */ + class Builder internal constructor() { + + private var maxTokens: JsonField? = null + private var temperature: JsonField? = null + private var maxTokensToSample: JsonField = JsonMissing.of() + private var stopSequences: JsonField>? = null + private var topK: JsonField = JsonMissing.of() + private var topP: JsonField = JsonMissing.of() + private var useCache: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(anthropicModelParams: AnthropicModelParams) = apply { + maxTokens = anthropicModelParams.maxTokens + temperature = anthropicModelParams.temperature + maxTokensToSample = anthropicModelParams.maxTokensToSample + stopSequences = anthropicModelParams.stopSequences.map { it.toMutableList() } + topK = anthropicModelParams.topK + topP = anthropicModelParams.topP + useCache = anthropicModelParams.useCache + additionalProperties = anthropicModelParams.additionalProperties.toMutableMap() + } + + fun maxTokens(maxTokens: Double) = maxTokens(JsonField.of(maxTokens)) + + /** + * Sets [Builder.maxTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokens] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun maxTokens(maxTokens: JsonField) = apply { this.maxTokens = maxTokens } + + fun temperature(temperature: Double) = temperature(JsonField.of(temperature)) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun temperature(temperature: JsonField) = apply { + this.temperature = temperature + } + + /** This is a legacy parameter that should not be used. */ + fun maxTokensToSample(maxTokensToSample: Double) = + maxTokensToSample(JsonField.of(maxTokensToSample)) + + /** + * Sets [Builder.maxTokensToSample] to an arbitrary JSON value. + * + * You should usually call [Builder.maxTokensToSample] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun maxTokensToSample(maxTokensToSample: JsonField) = apply { + this.maxTokensToSample = maxTokensToSample + } + + fun stopSequences(stopSequences: List) = + stopSequences(JsonField.of(stopSequences)) + + /** + * Sets [Builder.stopSequences] to an arbitrary JSON value. + * + * You should usually call [Builder.stopSequences] with a well-typed `List` + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun stopSequences(stopSequences: JsonField>) = apply { + this.stopSequences = stopSequences.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [stopSequences]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addStopSequence(stopSequence: String) = apply { + stopSequences = + (stopSequences ?: JsonField.of(mutableListOf())).also { + checkKnown("stopSequences", it).add(stopSequence) + } + } + + fun topK(topK: Double) = topK(JsonField.of(topK)) + + /** + * Sets [Builder.topK] to an arbitrary JSON value. + * + * You should usually call [Builder.topK] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topK(topK: JsonField) = apply { this.topK = topK } + + fun topP(topP: Double) = topP(JsonField.of(topP)) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topP(topP: JsonField) = apply { this.topP = topP } + + fun useCache(useCache: Boolean) = useCache(JsonField.of(useCache)) + + /** + * Sets [Builder.useCache] to an arbitrary JSON value. + * + * You should usually call [Builder.useCache] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun useCache(useCache: JsonField) = apply { this.useCache = useCache } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AnthropicModelParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .maxTokens() + * .temperature() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AnthropicModelParams = + AnthropicModelParams( + checkRequired("maxTokens", maxTokens), + checkRequired("temperature", temperature), + maxTokensToSample, + (stopSequences ?: JsonMissing.of()).map { it.toImmutable() }, + topK, + topP, + useCache, + 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 + } + + return other is AnthropicModelParams && + maxTokens == other.maxTokens && + temperature == other.temperature && + maxTokensToSample == other.maxTokensToSample && + stopSequences == other.stopSequences && + topK == other.topK && + topP == other.topP && + useCache == other.useCache && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + maxTokens, + temperature, + maxTokensToSample, + stopSequences, + topK, + topP, + useCache, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AnthropicModelParams{maxTokens=$maxTokens, temperature=$temperature, maxTokensToSample=$maxTokensToSample, stopSequences=$stopSequences, topK=$topK, topP=$topP, useCache=$useCache, additionalProperties=$additionalProperties}" + } + + class GoogleModelParams + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = 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 = 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 = 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 = 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 = useCache.getOptional("use_cache") + + /** + * Returns the raw JSON value of [maxOutputTokens]. + * + * Unlike [maxOutputTokens], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("maxOutputTokens") + @ExcludeMissing + fun _maxOutputTokens(): JsonField = maxOutputTokens + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("temperature") + @ExcludeMissing + fun _temperature(): JsonField = temperature + + /** + * Returns the raw JSON value of [topK]. + * + * Unlike [topK], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("topK") @ExcludeMissing fun _topK(): JsonField = topK + + /** + * Returns the raw JSON value of [topP]. + * + * Unlike [topP], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("topP") @ExcludeMissing fun _topP(): JsonField = topP + + /** + * Returns the raw JSON value of [useCache]. + * + * Unlike [useCache], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("use_cache") + @ExcludeMissing + fun _useCache(): JsonField = useCache + + @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 [GoogleModelParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [GoogleModelParams]. */ + class Builder internal constructor() { + + private var maxOutputTokens: JsonField = JsonMissing.of() + private var temperature: JsonField = JsonMissing.of() + private var topK: JsonField = JsonMissing.of() + private var topP: JsonField = JsonMissing.of() + private var useCache: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(googleModelParams: GoogleModelParams) = apply { + maxOutputTokens = googleModelParams.maxOutputTokens + temperature = googleModelParams.temperature + topK = googleModelParams.topK + topP = googleModelParams.topP + useCache = googleModelParams.useCache + additionalProperties = googleModelParams.additionalProperties.toMutableMap() + } + + fun maxOutputTokens(maxOutputTokens: Double) = + maxOutputTokens(JsonField.of(maxOutputTokens)) + + /** + * Sets [Builder.maxOutputTokens] to an arbitrary JSON value. + * + * You should usually call [Builder.maxOutputTokens] with a well-typed [Double] + * value instead. This method is primarily for setting the field to an undocumented + * or not yet supported value. + */ + fun maxOutputTokens(maxOutputTokens: JsonField) = apply { + this.maxOutputTokens = maxOutputTokens + } + + fun temperature(temperature: Double) = temperature(JsonField.of(temperature)) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun temperature(temperature: JsonField) = apply { + this.temperature = temperature + } + + fun topK(topK: Double) = topK(JsonField.of(topK)) + + /** + * Sets [Builder.topK] to an arbitrary JSON value. + * + * You should usually call [Builder.topK] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topK(topK: JsonField) = apply { this.topK = topK } + + fun topP(topP: Double) = topP(JsonField.of(topP)) + + /** + * Sets [Builder.topP] to an arbitrary JSON value. + * + * You should usually call [Builder.topP] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topP(topP: JsonField) = apply { this.topP = topP } + + fun useCache(useCache: Boolean) = useCache(JsonField.of(useCache)) + + /** + * Sets [Builder.useCache] to an arbitrary JSON value. + * + * You should usually call [Builder.useCache] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun useCache(useCache: JsonField) = apply { this.useCache = useCache } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [GoogleModelParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): GoogleModelParams = + GoogleModelParams( + maxOutputTokens, + temperature, + topK, + topP, + useCache, + 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 + } + + return other is GoogleModelParams && + maxOutputTokens == other.maxOutputTokens && + temperature == other.temperature && + topK == other.topK && + topP == other.topP && + useCache == other.useCache && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + maxOutputTokens, + temperature, + topK, + topP, + useCache, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GoogleModelParams{maxOutputTokens=$maxOutputTokens, temperature=$temperature, topK=$topK, topP=$topP, useCache=$useCache, additionalProperties=$additionalProperties}" + } + + class WindowAiModelParams + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = 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 = 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 = useCache.getOptional("use_cache") + + /** + * Returns the raw JSON value of [temperature]. + * + * Unlike [temperature], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("temperature") + @ExcludeMissing + fun _temperature(): JsonField = temperature + + /** + * Returns the raw JSON value of [topK]. + * + * Unlike [topK], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("topK") @ExcludeMissing fun _topK(): JsonField = topK + + /** + * Returns the raw JSON value of [useCache]. + * + * Unlike [useCache], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("use_cache") + @ExcludeMissing + fun _useCache(): JsonField = useCache + + @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 [WindowAiModelParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [WindowAiModelParams]. */ + class Builder internal constructor() { + + private var temperature: JsonField = JsonMissing.of() + private var topK: JsonField = JsonMissing.of() + private var useCache: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(windowAiModelParams: WindowAiModelParams) = apply { + temperature = windowAiModelParams.temperature + topK = windowAiModelParams.topK + useCache = windowAiModelParams.useCache + additionalProperties = windowAiModelParams.additionalProperties.toMutableMap() + } + + fun temperature(temperature: Double) = temperature(JsonField.of(temperature)) + + /** + * Sets [Builder.temperature] to an arbitrary JSON value. + * + * You should usually call [Builder.temperature] with a well-typed [Double] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun temperature(temperature: JsonField) = apply { + this.temperature = temperature + } + + fun topK(topK: Double) = topK(JsonField.of(topK)) + + /** + * Sets [Builder.topK] to an arbitrary JSON value. + * + * You should usually call [Builder.topK] with a well-typed [Double] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun topK(topK: JsonField) = apply { this.topK = topK } + + fun useCache(useCache: Boolean) = useCache(JsonField.of(useCache)) + + /** + * Sets [Builder.useCache] to an arbitrary JSON value. + * + * You should usually call [Builder.useCache] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun useCache(useCache: JsonField) = apply { this.useCache = useCache } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [WindowAiModelParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): WindowAiModelParams = + WindowAiModelParams( + temperature, + topK, + useCache, + 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 + } + + return other is WindowAiModelParams && + temperature == other.temperature && + topK == other.topK && + useCache == other.useCache && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(temperature, topK, useCache, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "WindowAiModelParams{temperature=$temperature, topK=$topK, useCache=$useCache, additionalProperties=$additionalProperties}" + } + + class JsCompletionParams + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 = useCache.getOptional("use_cache") + + /** + * Returns the raw JSON value of [useCache]. + * + * Unlike [useCache], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("use_cache") + @ExcludeMissing + fun _useCache(): JsonField = useCache + + @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 [JsCompletionParams]. + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [JsCompletionParams]. */ + class Builder internal constructor() { + + private var useCache: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(jsCompletionParams: JsCompletionParams) = apply { + useCache = jsCompletionParams.useCache + additionalProperties = jsCompletionParams.additionalProperties.toMutableMap() + } + + fun useCache(useCache: Boolean) = useCache(JsonField.of(useCache)) + + /** + * Sets [Builder.useCache] to an arbitrary JSON value. + * + * You should usually call [Builder.useCache] with a well-typed [Boolean] value + * instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun useCache(useCache: JsonField) = apply { this.useCache = useCache } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { + additionalProperties.remove(key) + } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [JsCompletionParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): JsCompletionParams = + 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 + } + + return other is JsCompletionParams && + useCache == other.useCache && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(useCache, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "JsCompletionParams{useCache=$useCache, additionalProperties=$additionalProperties}" + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptOptions && + model == other.model && + params == other.params && + position == other.position && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(model, params, position, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PromptOptions{model=$model, params=$params, position=$position, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..97a12f57 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptReplaceParams.kt @@ -0,0 +1,1028 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.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.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 + +/** + * Create or replace prompt. If there is an existing prompt in the project with the same slug as the + * one specified in the request, will replace the existing prompt with the provided fields + */ +class PromptReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of 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 name(): String = body.name() + + /** + * 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 = body.projectId() + + /** + * 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 = body.slug() + + /** + * 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 = body.description() + + /** + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun functionType(): Optional = body.functionType() + + /** + * 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 = body.promptData() + + /** + * 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> = body.tags() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [slug]. + * + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _slug(): JsonField = body._slug() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _functionType(): JsonField = body._functionType() + + /** + * Returns the raw JSON value of [promptData]. + * + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _promptData(): JsonField = body._promptData() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [PromptReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * .projectId() + * .slug() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptReplaceParams]. */ + 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(promptReplaceParams: PromptReplaceParams) = apply { + body = promptReplaceParams.body.toBuilder() + additionalHeaders = promptReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = promptReplaceParams.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] + * - [slug] + * - [description] + * - [functionType] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the prompt */ + 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 prompt 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) } + + /** Unique identifier for the prompt */ + fun slug(slug: String) = apply { body.slug(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 { 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()) + + /** + * 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 functionType(functionType: FunctionType?) = apply { body.functionType(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 { + 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()) + + /** + * 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 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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()) + + /** + * Name of 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 name(): String = name.getRequired("name") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * @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") + + /** + * 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") + + /** + * 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 [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 [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 [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 [functionType]. + * + * Unlike [functionType], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("function_type") + @ExcludeMissing + fun _functionType(): JsonField = functionType + + /** + * 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 [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]. + * + * 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 } + + /** 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 + } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + slug() + description() + functionType().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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + projectId, + slug, + description, + functionType, + promptData, + tags, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + 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) : + Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM = of("llm") + + @JvmField val SCORER = of("scorer") + + @JvmField val TASK = of("task") + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = FunctionType(JsonField.of(value)) + } + + /** An enum containing [FunctionType]'s known values. */ + enum class Known { + LLM, + SCORER, + TASK, + TOOL, + } + + /** + * An enum containing [FunctionType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [FunctionType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM, + SCORER, + TASK, + TOOL, + /** + * An enum member indicating that [FunctionType] was instantiated with an unknown value. + */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM -> Value.LLM + SCORER -> Value.SCORER + TASK -> Value.TASK + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LLM -> Known.LLM + SCORER -> Known.SCORER + TASK -> Known.TASK + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown FunctionType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is FunctionType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "PromptReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..0dda7e97 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptRetrieveParams.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a prompt object by its id */ +class PromptRetrieveParams +private constructor( + private val promptId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Prompt id */ + fun promptId(): Optional = Optional.ofNullable(promptId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): PromptRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [PromptRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [PromptRetrieveParams]. */ + class Builder internal constructor() { + + private var promptId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(promptRetrieveParams: PromptRetrieveParams) = apply { + promptId = promptRetrieveParams.promptId + additionalHeaders = promptRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = promptRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Prompt id */ + fun promptId(promptId: String?) = apply { this.promptId = promptId } + + /** Alias for calling [Builder.promptId] with `promptId.orElse(null)`. */ + fun promptId(promptId: Optional) = promptId(promptId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [PromptRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PromptRetrieveParams = + PromptRetrieveParams(promptId, additionalHeaders.build(), additionalQueryParams.build()) + } + + 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 + } + + return other is PromptRetrieveParams && + promptId == other.promptId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(promptId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "PromptRetrieveParams{promptId=$promptId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..0cfcc0a0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/PromptUpdateParams.kt @@ -0,0 +1,737 @@ +// 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.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.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 + +/** + * Partially update a prompt object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ +class PromptUpdateParams +private constructor( + private val promptId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Prompt id */ + fun promptId(): Optional = Optional.ofNullable(promptId) + + /** + * 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 = body.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 = body.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 = body.promptData() + + /** + * 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 = body.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> = body.tags() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [promptData]. + * + * Unlike [promptData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _promptData(): JsonField = body._promptData() + + /** + * Returns the raw JSON value of [slug]. + * + * Unlike [slug], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _slug(): JsonField = body._slug() + + /** + * Returns the raw JSON value of [tags]. + * + * Unlike [tags], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _tags(): JsonField> = body._tags() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): PromptUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [PromptUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** Prompt id */ + fun promptId(promptId: String?) = apply { this.promptId = promptId } + + /** Alias for calling [Builder.promptId] with `promptId.orElse(null)`. */ + fun promptId(promptId: Optional) = promptId(promptId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [description] + * - [name] + * - [promptData] + * - [slug] + * - [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) } + + /** 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) } + + 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 [PromptUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): PromptUpdateParams = + PromptUpdateParams( + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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. + * + * 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 + } + + /** Unique identifier for the prompt */ + fun slug(slug: String?) = slug(JsonField.ofNullable(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 { this.slug = slug } + + /** A list of tags for the prompt */ + fun tags(tags: List?) = tags(JsonField.ofNullable(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 { + this.tags = tags.map { it.toMutableList() } + } + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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, + promptData, + slug, + (tags ?: JsonMissing.of()).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + description() + name() + promptData().ifPresent { it.validate() } + slug() + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + description == other.description && + name == other.name && + promptData == other.promptData && + slug == other.slug && + tags == other.tags && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(description, name, promptData, slug, tags, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{description=$description, name=$name, promptData=$promptData, slug=$slug, tags=$tags, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is PromptUpdateParams && + promptId == other.promptId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(promptId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "PromptUpdateParams{promptId=$promptId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..d81c3eef --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RepoInfo.kt @@ -0,0 +1,517 @@ +// 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.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 */ +class RepoInfo +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 = authorEmail.getOptional("author_email") + + /** + * Name 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 authorName(): Optional = authorName.getOptional("author_name") + + /** + * Name of the branch the most recent commit belongs to + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun branch(): Optional = branch.getOptional("branch") + + /** + * SHA of most recent commit + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun commit(): Optional = commit.getOptional("commit") + + /** + * Most recent commit message + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun commitMessage(): Optional = commitMessage.getOptional("commit_message") + + /** + * Time 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 commitTime(): Optional = commitTime.getOptional("commit_time") + + /** + * Whether or not the repo had uncommitted changes when snapshotted + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun dirty(): Optional = dirty.getOptional("dirty") + + /** + * If the repo was dirty when run, this includes the diff between the current state of the repo + * and 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 gitDiff(): Optional = gitDiff.getOptional("git_diff") + + /** + * Name of the tag on 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 tag(): Optional = tag.getOptional("tag") + + /** + * Returns the raw JSON value of [authorEmail]. + * + * Unlike [authorEmail], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("author_email") + @ExcludeMissing + fun _authorEmail(): JsonField = authorEmail + + /** + * Returns the raw JSON value of [authorName]. + * + * Unlike [authorName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("author_name") @ExcludeMissing fun _authorName(): JsonField = authorName + + /** + * Returns the raw JSON value of [branch]. + * + * Unlike [branch], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("branch") @ExcludeMissing fun _branch(): JsonField = branch + + /** + * Returns the raw JSON value of [commit]. + * + * Unlike [commit], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("commit") @ExcludeMissing fun _commit(): JsonField = commit + + /** + * Returns the raw JSON value of [commitMessage]. + * + * Unlike [commitMessage], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("commit_message") + @ExcludeMissing + fun _commitMessage(): JsonField = commitMessage + + /** + * Returns the raw JSON value of [commitTime]. + * + * Unlike [commitTime], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("commit_time") @ExcludeMissing fun _commitTime(): JsonField = commitTime + + /** + * Returns the raw JSON value of [dirty]. + * + * Unlike [dirty], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("dirty") @ExcludeMissing fun _dirty(): JsonField = dirty + + /** + * Returns the raw JSON value of [gitDiff]. + * + * Unlike [gitDiff], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("git_diff") @ExcludeMissing fun _gitDiff(): JsonField = gitDiff + + /** + * Returns the raw JSON value of [tag]. + * + * Unlike [tag], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tag") @ExcludeMissing fun _tag(): JsonField = tag + + @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 [RepoInfo]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RepoInfo]. */ + class Builder internal constructor() { + + private var authorEmail: JsonField = JsonMissing.of() + private var authorName: JsonField = JsonMissing.of() + private var branch: JsonField = JsonMissing.of() + private var commit: JsonField = JsonMissing.of() + private var commitMessage: JsonField = JsonMissing.of() + private var commitTime: JsonField = JsonMissing.of() + private var dirty: JsonField = JsonMissing.of() + private var gitDiff: JsonField = JsonMissing.of() + private var tag: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(repoInfo: RepoInfo) = apply { + authorEmail = repoInfo.authorEmail + authorName = repoInfo.authorName + branch = repoInfo.branch + commit = repoInfo.commit + commitMessage = repoInfo.commitMessage + commitTime = repoInfo.commitTime + dirty = repoInfo.dirty + gitDiff = repoInfo.gitDiff + tag = repoInfo.tag + additionalProperties = repoInfo.additionalProperties.toMutableMap() + } + + /** Email of the author of the most recent commit */ + fun authorEmail(authorEmail: String?) = authorEmail(JsonField.ofNullable(authorEmail)) + + /** Alias for calling [Builder.authorEmail] with `authorEmail.orElse(null)`. */ + fun authorEmail(authorEmail: Optional) = authorEmail(authorEmail.getOrNull()) + + /** + * Sets [Builder.authorEmail] to an arbitrary JSON value. + * + * You should usually call [Builder.authorEmail] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun authorEmail(authorEmail: JsonField) = apply { this.authorEmail = authorEmail } + + /** Name of the author of the most recent commit */ + fun authorName(authorName: String?) = authorName(JsonField.ofNullable(authorName)) + + /** Alias for calling [Builder.authorName] with `authorName.orElse(null)`. */ + fun authorName(authorName: Optional) = authorName(authorName.getOrNull()) + + /** + * Sets [Builder.authorName] to an arbitrary JSON value. + * + * You should usually call [Builder.authorName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun authorName(authorName: JsonField) = apply { this.authorName = authorName } + + /** Name of the branch the most recent commit belongs to */ + fun branch(branch: String?) = branch(JsonField.ofNullable(branch)) + + /** Alias for calling [Builder.branch] with `branch.orElse(null)`. */ + fun branch(branch: Optional) = branch(branch.getOrNull()) + + /** + * Sets [Builder.branch] to an arbitrary JSON value. + * + * You should usually call [Builder.branch] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun branch(branch: JsonField) = apply { this.branch = branch } + + /** SHA of most recent commit */ + fun commit(commit: String?) = commit(JsonField.ofNullable(commit)) + + /** Alias for calling [Builder.commit] with `commit.orElse(null)`. */ + fun commit(commit: Optional) = commit(commit.getOrNull()) + + /** + * Sets [Builder.commit] to an arbitrary JSON value. + * + * You should usually call [Builder.commit] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun commit(commit: JsonField) = apply { this.commit = commit } + + /** Most recent commit message */ + fun commitMessage(commitMessage: String?) = + commitMessage(JsonField.ofNullable(commitMessage)) + + /** Alias for calling [Builder.commitMessage] with `commitMessage.orElse(null)`. */ + fun commitMessage(commitMessage: Optional) = + commitMessage(commitMessage.getOrNull()) + + /** + * Sets [Builder.commitMessage] to an arbitrary JSON value. + * + * You should usually call [Builder.commitMessage] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun commitMessage(commitMessage: JsonField) = apply { + this.commitMessage = commitMessage + } + + /** Time of the most recent commit */ + fun commitTime(commitTime: String?) = commitTime(JsonField.ofNullable(commitTime)) + + /** Alias for calling [Builder.commitTime] with `commitTime.orElse(null)`. */ + fun commitTime(commitTime: Optional) = commitTime(commitTime.getOrNull()) + + /** + * Sets [Builder.commitTime] to an arbitrary JSON value. + * + * You should usually call [Builder.commitTime] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun commitTime(commitTime: JsonField) = apply { this.commitTime = commitTime } + + /** Whether or not the repo had uncommitted changes when snapshotted */ + fun dirty(dirty: Boolean?) = dirty(JsonField.ofNullable(dirty)) + + /** + * Alias for [Builder.dirty]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun dirty(dirty: Boolean) = dirty(dirty as Boolean?) + + /** Alias for calling [Builder.dirty] with `dirty.orElse(null)`. */ + fun dirty(dirty: Optional) = dirty(dirty.getOrNull()) + + /** + * Sets [Builder.dirty] to an arbitrary JSON value. + * + * You should usually call [Builder.dirty] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun dirty(dirty: JsonField) = apply { this.dirty = dirty } + + /** + * If the repo was dirty when run, this includes the diff between the current state of the + * repo and the most recent commit. + */ + fun gitDiff(gitDiff: String?) = gitDiff(JsonField.ofNullable(gitDiff)) + + /** Alias for calling [Builder.gitDiff] with `gitDiff.orElse(null)`. */ + fun gitDiff(gitDiff: Optional) = gitDiff(gitDiff.getOrNull()) + + /** + * Sets [Builder.gitDiff] to an arbitrary JSON value. + * + * You should usually call [Builder.gitDiff] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun gitDiff(gitDiff: JsonField) = apply { this.gitDiff = gitDiff } + + /** Name of the tag on the most recent commit */ + fun tag(tag: String?) = tag(JsonField.ofNullable(tag)) + + /** Alias for calling [Builder.tag] with `tag.orElse(null)`. */ + fun tag(tag: Optional) = tag(tag.getOrNull()) + + /** + * Sets [Builder.tag] to an arbitrary JSON value. + * + * You should usually call [Builder.tag] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun tag(tag: JsonField) = apply { this.tag = 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 [RepoInfo]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RepoInfo = + RepoInfo( + authorEmail, + authorName, + branch, + commit, + commitMessage, + commitTime, + dirty, + gitDiff, + tag, + 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 + } + + return other is RepoInfo && + authorEmail == other.authorEmail && + authorName == other.authorName && + branch == other.branch && + commit == other.commit && + commitMessage == other.commitMessage && + commitTime == other.commitTime && + dirty == other.dirty && + gitDiff == other.gitDiff && + tag == other.tag && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + authorEmail, + authorName, + branch, + commit, + commitMessage, + commitTime, + dirty, + gitDiff, + tag, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RepoInfo{authorEmail=$authorEmail, authorName=$authorName, branch=$branch, commit=$commit, commitMessage=$commitMessage, commitTime=$commitTime, dirty=$dirty, gitDiff=$gitDiff, tag=$tag, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..8863415e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/Role.kt @@ -0,0 +1,804 @@ +// 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.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * A role is a collection of permissions which can be granted as part of an ACL + * + * Roles can consist of individual permissions, as well as a set of roles they inherit from + */ +class Role +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * Name of the role + * + * @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") + + /** + * Date of role creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * 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") + + /** + * 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") + + /** + * (permission, restrict_object_type) tuples which belong to this role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + 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(): Optional> = memberRoles.getOptional("member_roles") + + /** + * Unique id for the organization that the role belongs under + * + * A null org_id indicates a system role, which may be assigned to anybody and inherited by any + * other role, but cannot be edited. + * + * It is forbidden to change the org after creating a role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun orgId(): Optional = orgId.getOptional("org_id") + + /** + * Identifies the user who created the role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [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 [memberPermissions]. + * + * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("member_permissions") + @ExcludeMissing + fun _memberPermissions(): JsonField> = memberPermissions + + /** + * 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 + + /** + * Returns the raw JSON value of [orgId]. + * + * Unlike [orgId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("org_id") @ExcludeMissing fun _orgId(): JsonField = orgId + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [Role]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Role]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var deletedAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var memberPermissions: JsonField>? = null + private var memberRoles: JsonField>? = null + private var orgId: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(role: Role) = apply { + id = role.id + name = role.name + created = role.created + deletedAt = role.deletedAt + description = role.description + memberPermissions = role.memberPermissions.map { it.toMutableList() } + memberRoles = role.memberRoles.map { it.toMutableList() } + orgId = role.orgId + userId = role.userId + additionalProperties = role.additionalProperties.toMutableMap() + } + + /** Unique identifier for the role */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** 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 } + + /** Date of role creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } + + /** 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() } + } + + /** + * 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) + } + } + + /** + * 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)) + + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = memberRoles(memberRoles.getOrNull()) + + /** + * 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() } + } + + /** + * 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) + } + } + + /** + * Unique id for the organization that the role belongs under + * + * A null org_id indicates a system role, which may be assigned to anybody and inherited by + * any other role, but cannot be edited. + * + * It is forbidden to change the org after creating a role + */ + 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 } + + /** Identifies the user who created the role */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Role]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Role = + Role( + checkRequired("id", id), + checkRequired("name", name), + created, + deletedAt, + description, + (memberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, + (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, + orgId, + userId, + additionalProperties.toMutableMap(), + ) + } + + 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(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * Permissions can be assigned to to objects on an individual basis, or grouped into roles + * + * @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 permission(): Permission = permission.getRequired("permission") + + /** + * The object type that the ACL applies to + * + * @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") + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + @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 [MemberPermission]. + * + * The following fields are required: + * ```java + * .permission() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [MemberPermission]. */ + class Builder internal constructor() { + + private var permission: JsonField? = null + private var restrictObjectType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(memberPermission: MemberPermission) = apply { + permission = memberPermission.permission + restrictObjectType = memberPermission.restrictObjectType + additionalProperties = memberPermission.additionalProperties.toMutableMap() + } + + /** + * Each permission permits a certain type of operation on an object in the system + * + * Permissions can be assigned to to objects on an individual basis, or grouped into + * roles + */ + fun permission(permission: Permission) = permission(JsonField.of(permission)) + + /** + * 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 + } + + /** The object type that the ACL applies to */ + 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [MemberPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .permission() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MemberPermission = + MemberPermission( + checkRequired("permission", permission), + restrictObjectType, + 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 + } + + return other is MemberPermission && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(permission, restrictObjectType, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MemberPermission{permission=$permission, restrictObjectType=$restrictObjectType, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Role && + id == other.id && + name == other.name && + created == other.created && + deletedAt == other.deletedAt && + description == other.description && + memberPermissions == other.memberPermissions && + memberRoles == other.memberRoles && + orgId == other.orgId && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + created, + deletedAt, + description, + memberPermissions, + memberRoles, + orgId, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Role{id=$id, name=$name, created=$created, deletedAt=$deletedAt, description=$description, memberPermissions=$memberPermissions, memberRoles=$memberRoles, orgId=$orgId, userId=$userId, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..9f3a93c7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleCreateParams.kt @@ -0,0 +1,1037 @@ +// 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.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.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 + +/** + * Create a new role. If there is an existing role with the same name as the one specified in the + * request, will return the existing role unmodified + */ +class RoleCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the role + * + * @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 = body.name() + + /** + * 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 = body.description() + + /** + * (permission, restrict_object_type) tuples which belong to this role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun memberPermissions(): Optional> = body.memberPermissions() + + /** + * 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(): Optional> = body.memberRoles() + + /** + * 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 = body.orgName() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [memberPermissions]. + * + * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _memberPermissions(): JsonField> = body._memberPermissions() + + /** + * Returns the raw JSON value of [memberRoles]. + * + * Unlike [memberRoles], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _memberRoles(): JsonField> = body._memberRoles() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoleCreateParams]. + * + * The following fields are required: + * ```java + * .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() + } + + /** + * 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] + * - [description] + * - [memberPermissions] + * - [memberRoles] + * - [orgName] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the role */ + 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 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) } + + /** (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()) + + /** + * 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 { + body.memberPermissions(memberPermissions) + } + + /** + * Adds a single [MemberPermission] to [memberPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberPermission(memberPermission: MemberPermission) = apply { + body.addMemberPermission(memberPermission) + } + + /** + * 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?) = apply { body.memberRoles(memberRoles) } + + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = memberRoles(memberRoles.getOrNull()) + + /** + * 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 { + body.memberRoles(memberRoles) + } + + /** + * Adds a single [String] to [memberRoles]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberRole(memberRole: String) = apply { body.addMemberRole(memberRole) } + + /** + * 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?) = 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) + } + + 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 [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()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val name: JsonField, + private val description: JsonField, + private val memberPermissions: JsonField>, + private val memberRoles: 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_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()) + + /** + * Name of the role + * + * @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 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") + + /** + * (permission, restrict_object_type) tuples which belong to this role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + 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(): Optional> = memberRoles.getOptional("member_roles") + + /** + * 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") + + /** + * 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 [memberPermissions]. + * + * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("member_permissions") + @ExcludeMissing + fun _memberPermissions(): JsonField> = memberPermissions + + /** + * 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 + + /** + * 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 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() } + } + + /** + * 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) + } + } + + /** + * 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)) + + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = + memberRoles(memberRoles.getOrNull()) + + /** + * 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() } + } + + /** + * 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) + } + } + + /** + * 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)) + + /** 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), + description, + (memberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, + (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, + orgName, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + description() + memberPermissions().ifPresent { it.forEach { it.validate() } } + memberRoles() + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + description == other.description && + memberPermissions == other.memberPermissions && + memberRoles == other.memberRoles && + orgName == other.orgName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + description, + memberPermissions, + memberRoles, + orgName, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, description=$description, memberPermissions=$memberPermissions, memberRoles=$memberRoles, orgName=$orgName, additionalProperties=$additionalProperties}" + } + + class MemberPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * Permissions can be assigned to to objects on an individual basis, or grouped into roles + * + * @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 permission(): Permission = permission.getRequired("permission") + + /** + * The object type that the ACL applies to + * + * @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") + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + @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 [MemberPermission]. + * + * The following fields are required: + * ```java + * .permission() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [MemberPermission]. */ + class Builder internal constructor() { + + private var permission: JsonField? = null + private var restrictObjectType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(memberPermission: MemberPermission) = apply { + permission = memberPermission.permission + restrictObjectType = memberPermission.restrictObjectType + additionalProperties = memberPermission.additionalProperties.toMutableMap() + } + + /** + * Each permission permits a certain type of operation on an object in the system + * + * Permissions can be assigned to to objects on an individual basis, or grouped into + * roles + */ + fun permission(permission: Permission) = permission(JsonField.of(permission)) + + /** + * 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 + } + + /** The object type that the ACL applies to */ + 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [MemberPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .permission() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MemberPermission = + MemberPermission( + checkRequired("permission", permission), + restrictObjectType, + 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 + } + + return other is MemberPermission && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(permission, restrictObjectType, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MemberPermission{permission=$permission, restrictObjectType=$restrictObjectType, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoleCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "RoleCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..046d491b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleDeleteParams.kt @@ -0,0 +1,231 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete a role object by its id */ +class RoleDeleteParams +private constructor( + private val roleId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** Role id */ + fun roleId(): Optional = Optional.ofNullable(roleId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): RoleDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [RoleDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleDeleteParams]. */ + class Builder internal constructor() { + + private var roleId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(roleDeleteParams: RoleDeleteParams) = apply { + roleId = roleDeleteParams.roleId + additionalHeaders = roleDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = roleDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = roleDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** Role id */ + fun roleId(roleId: String?) = apply { this.roleId = roleId } + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [RoleDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RoleDeleteParams = + RoleDeleteParams( + roleId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is RoleDeleteParams && + roleId == other.roleId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash(roleId, additionalHeaders, additionalQueryParams, additionalBodyProperties) + + override fun toString() = + "RoleDeleteParams{roleId=$roleId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100755 index 00000000..9982ae81 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPage.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.RoleService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see RoleService.list */ +class RoleListPage +private constructor( + private val service: RoleService, + private val params: RoleListParams, + private val response: RoleListPageResponse, +) : Page { + + /** + * Delegates to [RoleListPageResponse], but gracefully handles missing data. + * + * @see RoleListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): RoleListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): RoleListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): RoleListParams = params + + /** The response that this page was parsed from. */ + fun response(): RoleListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoleListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleListPage]. */ + class Builder internal constructor() { + + private var service: RoleService? = null + private var params: RoleListParams? = null + private var response: RoleListPageResponse? = null + + @JvmSynthetic + internal fun from(roleListPage: RoleListPage) = apply { + service = roleListPage.service + params = roleListPage.params + response = roleListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoleListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..bd22807d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageAsync.kt @@ -0,0 +1,138 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.RoleServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see RoleServiceAsync.list */ +class RoleListPageAsync +private constructor( + private val service: RoleServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: RoleListParams, + private val response: RoleListPageResponse, +) : PageAsync { + + /** + * Delegates to [RoleListPageResponse], but gracefully handles missing data. + * + * @see RoleListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): RoleListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): RoleListParams = params + + /** The response that this page was parsed from. */ + fun response(): RoleListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoleListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleListPageAsync]. */ + class Builder internal constructor() { + + private var service: RoleServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: RoleListParams? = null + private var response: RoleListPageResponse? = null + + @JvmSynthetic + internal fun from(roleListPageAsync: RoleListPageAsync) = apply { + service = roleListPageAsync.service + streamHandlerExecutor = roleListPageAsync.streamHandlerExecutor + params = roleListPageAsync.params + response = roleListPageAsync.response + } + + fun service(service: RoleServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RoleListPageAsync = + RoleListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoleListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "RoleListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..e02593db --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListPageResponse.kt @@ -0,0 +1,193 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is RoleListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..7ae51b50 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleListParams.kt @@ -0,0 +1,401 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all roles. The roles are sorted by creation date, with the most recently-created roles + * coming first + */ +class RoleListParams +private constructor( + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val roleName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** Name of the role to search for */ + fun roleName(): Optional = Optional.ofNullable(roleName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): RoleListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [RoleListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var roleName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(roleListParams: RoleListParams) = apply { + endingBefore = roleListParams.endingBefore + ids = roleListParams.ids + limit = roleListParams.limit + orgName = roleListParams.orgName + roleName = roleListParams.roleName + startingAfter = roleListParams.startingAfter + additionalHeaders = roleListParams.additionalHeaders.toBuilder() + additionalQueryParams = roleListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Name of the role to search for */ + fun roleName(roleName: String?) = apply { this.roleName = roleName } + + /** Alias for calling [Builder.roleName] with `roleName.orElse(null)`. */ + fun roleName(roleName: Optional) = roleName(roleName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [RoleListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RoleListParams = + RoleListParams( + endingBefore, + ids, + limit, + orgName, + roleName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoleListParams && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + roleName == other.roleName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + ids, + limit, + orgName, + roleName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "RoleListParams{endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, roleName=$roleName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..6f369bab --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleReplaceParams.kt @@ -0,0 +1,1041 @@ +// 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.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.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 + +/** + * Create or replace role. If there is an existing role with the same name as the one specified in + * the request, will replace the existing role with the provided fields + */ +class RoleReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the role + * + * @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 = body.name() + + /** + * 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 = body.description() + + /** + * (permission, restrict_object_type) tuples which belong to this role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun memberPermissions(): Optional> = body.memberPermissions() + + /** + * 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(): Optional> = body.memberRoles() + + /** + * 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 = body.orgName() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [memberPermissions]. + * + * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _memberPermissions(): JsonField> = body._memberPermissions() + + /** + * Returns the raw JSON value of [memberRoles]. + * + * Unlike [memberRoles], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _memberRoles(): JsonField> = body._memberRoles() + + /** + * Returns the raw JSON value of [orgName]. + * + * Unlike [orgName], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _orgName(): JsonField = body._orgName() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [RoleReplaceParams]. + * + * The following fields are required: + * ```java + * .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() + } + + /** + * 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] + * - [description] + * - [memberPermissions] + * - [memberRoles] + * - [orgName] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the role */ + 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 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) } + + /** (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()) + + /** + * 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 { + body.memberPermissions(memberPermissions) + } + + /** + * Adds a single [MemberPermission] to [memberPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberPermission(memberPermission: MemberPermission) = apply { + body.addMemberPermission(memberPermission) + } + + /** + * 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?) = apply { body.memberRoles(memberRoles) } + + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = memberRoles(memberRoles.getOrNull()) + + /** + * 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 { + body.memberRoles(memberRoles) + } + + /** + * Adds a single [String] to [memberRoles]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMemberRole(memberRole: String) = apply { body.addMemberRole(memberRole) } + + /** + * 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?) = 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) + } + + 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 [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(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val name: JsonField, + private val description: JsonField, + private val memberPermissions: JsonField>, + private val memberRoles: 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_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()) + + /** + * Name of the role + * + * @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 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") + + /** + * (permission, restrict_object_type) tuples which belong to this role + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + 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(): Optional> = memberRoles.getOptional("member_roles") + + /** + * 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") + + /** + * 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 [memberPermissions]. + * + * Unlike [memberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("member_permissions") + @ExcludeMissing + fun _memberPermissions(): JsonField> = memberPermissions + + /** + * 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 + + /** + * 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 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() } + } + + /** + * 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) + } + } + + /** + * 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)) + + /** Alias for calling [Builder.memberRoles] with `memberRoles.orElse(null)`. */ + fun memberRoles(memberRoles: Optional>) = + memberRoles(memberRoles.getOrNull()) + + /** + * 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() } + } + + /** + * 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) + } + } + + /** + * 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)) + + /** 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), + description, + (memberPermissions ?: JsonMissing.of()).map { it.toImmutable() }, + (memberRoles ?: JsonMissing.of()).map { it.toImmutable() }, + orgName, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + description() + memberPermissions().ifPresent { it.forEach { it.validate() } } + memberRoles() + 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 (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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + description == other.description && + memberPermissions == other.memberPermissions && + memberRoles == other.memberRoles && + orgName == other.orgName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + description, + memberPermissions, + memberRoles, + orgName, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, description=$description, memberPermissions=$memberPermissions, memberRoles=$memberRoles, orgName=$orgName, additionalProperties=$additionalProperties}" + } + + class MemberPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * Permissions can be assigned to to objects on an individual basis, or grouped into roles + * + * @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 permission(): Permission = permission.getRequired("permission") + + /** + * The object type that the ACL applies to + * + * @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") + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + @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 [MemberPermission]. + * + * The following fields are required: + * ```java + * .permission() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [MemberPermission]. */ + class Builder internal constructor() { + + private var permission: JsonField? = null + private var restrictObjectType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(memberPermission: MemberPermission) = apply { + permission = memberPermission.permission + restrictObjectType = memberPermission.restrictObjectType + additionalProperties = memberPermission.additionalProperties.toMutableMap() + } + + /** + * Each permission permits a certain type of operation on an object in the system + * + * Permissions can be assigned to to objects on an individual basis, or grouped into + * roles + */ + fun permission(permission: Permission) = permission(JsonField.of(permission)) + + /** + * 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 + } + + /** The object type that the ACL applies to */ + 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [MemberPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .permission() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): MemberPermission = + MemberPermission( + checkRequired("permission", permission), + restrictObjectType, + 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 + } + + return other is MemberPermission && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(permission, restrictObjectType, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MemberPermission{permission=$permission, restrictObjectType=$restrictObjectType, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoleReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "RoleReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..ab31b790 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleRetrieveParams.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a role object by its id */ +class RoleRetrieveParams +private constructor( + private val roleId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Role id */ + fun roleId(): Optional = Optional.ofNullable(roleId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): RoleRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [RoleRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RoleRetrieveParams]. */ + class Builder internal constructor() { + + private var roleId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(roleRetrieveParams: RoleRetrieveParams) = apply { + roleId = roleRetrieveParams.roleId + additionalHeaders = roleRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = roleRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Role id */ + fun roleId(roleId: String?) = apply { this.roleId = roleId } + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [RoleRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): RoleRetrieveParams = + RoleRetrieveParams(roleId, additionalHeaders.build(), additionalQueryParams.build()) + } + + 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 + } + + return other is RoleRetrieveParams && + roleId == other.roleId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(roleId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "RoleRetrieveParams{roleId=$roleId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..de9e7fb3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/RoleUpdateParams.kt @@ -0,0 +1,1423 @@ +// 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.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.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 + +/** + * Partially update a role object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ +class RoleUpdateParams +private constructor( + private val roleId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** Role id */ + fun roleId(): Optional = Optional.ofNullable(roleId) + + /** + * 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> = body.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). + */ + fun addMemberRoles(): Optional> = body.addMemberRoles() + + /** + * 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 = body.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 = body.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> = + body.removeMemberPermissions() + + /** + * 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> = body.removeMemberRoles() + + /** + * Returns the raw JSON value of [addMemberPermissions]. + * + * Unlike [addMemberPermissions], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _addMemberPermissions(): JsonField> = body._addMemberPermissions() + + /** + * Returns the raw JSON value of [addMemberRoles]. + * + * Unlike [addMemberRoles], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _addMemberRoles(): JsonField> = body._addMemberRoles() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [removeMemberPermissions]. + * + * Unlike [removeMemberPermissions], this method doesn't throw if the JSON field has an + * unexpected type. + */ + fun _removeMemberPermissions(): JsonField> = + body._removeMemberPermissions() + + /** + * Returns the raw JSON value of [removeMemberRoles]. + * + * Unlike [removeMemberRoles], this method doesn't throw if the JSON field has an unexpected + * type. + */ + fun _removeMemberRoles(): JsonField> = body._removeMemberRoles() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): RoleUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [RoleUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** Role id */ + fun roleId(roleId: String?) = apply { this.roleId = roleId } + + /** Alias for calling [Builder.roleId] with `roleId.orElse(null)`. */ + fun roleId(roleId: Optional) = roleId(roleId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [addMemberPermissions] + * - [addMemberRoles] + * - [description] + * - [name] + * - [removeMemberPermissions] + * - etc. + */ + 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) + } + + /** + * 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) + } + + 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. + */ + fun build(): RoleUpdateParams = + RoleUpdateParams( + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 + private var description: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var removeMemberPermissions: JsonField>? = + null + private var removeMemberRoles: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + addMemberPermissions = body.addMemberPermissions.map { it.toMutableList() } + addMemberRoles = body.addMemberRoles.map { it.toMutableList() } + description = body.description + name = body.name + removeMemberPermissions = body.removeMemberPermissions.map { it.toMutableList() } + removeMemberRoles = body.removeMemberRoles.map { it.toMutableList() } + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** A list of permissions to add to the role */ + fun addMemberPermissions(addMemberPermissions: List?) = + addMemberPermissions(JsonField.ofNullable(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 { + this.addMemberPermissions = addMemberPermissions.map { it.toMutableList() } + } + + /** + * Adds a single [AddMemberPermission] to [addMemberPermissions]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAddMemberPermission(addMemberPermission: AddMemberPermission) = apply { + addMemberPermissions = + (addMemberPermissions ?: JsonField.of(mutableListOf())).also { + checkKnown("addMemberPermissions", it).add(addMemberPermission) + } + } + + /** A list of role IDs to add to the role's inheriting-from set */ + fun addMemberRoles(addMemberRoles: List?) = + addMemberRoles(JsonField.ofNullable(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 { + this.addMemberRoles = addMemberRoles.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [addMemberRoles]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addAddMemberRole(addMemberRole: String) = apply { + addMemberRoles = + (addMemberRoles ?: JsonField.of(mutableListOf())).also { + checkKnown("addMemberRoles", it).add(addMemberRole) + } + } + + /** 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 + } + + /** Name of the role */ + 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 } + + /** A list of permissions to remove from the role */ + fun removeMemberPermissions(removeMemberPermissions: List?) = + removeMemberPermissions(JsonField.ofNullable(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 { + 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.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + addMemberPermissions().ifPresent { it.forEach { it.validate() } } + addMemberRoles() + description() + name() + removeMemberPermissions().ifPresent { it.forEach { it.validate() } } + removeMemberRoles() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns 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) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + addMemberPermissions == other.addMemberPermissions && + addMemberRoles == other.addMemberRoles && + description == other.description && + name == other.name && + removeMemberPermissions == other.removeMemberPermissions && + removeMemberRoles == other.removeMemberRoles && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + addMemberPermissions, + addMemberRoles, + description, + name, + removeMemberPermissions, + removeMemberRoles, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{addMemberPermissions=$addMemberPermissions, addMemberRoles=$addMemberRoles, description=$description, name=$name, removeMemberPermissions=$removeMemberPermissions, removeMemberRoles=$removeMemberRoles, additionalProperties=$additionalProperties}" + } + + class AddMemberPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * Permissions can be assigned to to objects on an individual basis, or grouped into roles + * + * @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 permission(): Permission = permission.getRequired("permission") + + /** + * The object type that the ACL applies to + * + * @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") + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + @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 [AddMemberPermission]. + * + * The following fields are required: + * ```java + * .permission() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [AddMemberPermission]. */ + class Builder internal constructor() { + + private var permission: JsonField? = null + private var restrictObjectType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(addMemberPermission: AddMemberPermission) = apply { + permission = addMemberPermission.permission + restrictObjectType = addMemberPermission.restrictObjectType + additionalProperties = addMemberPermission.additionalProperties.toMutableMap() + } + + /** + * Each permission permits a certain type of operation on an object in the system + * + * Permissions can be assigned to to objects on an individual basis, or grouped into + * roles + */ + fun permission(permission: Permission) = permission(JsonField.of(permission)) + + /** + * 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 + } + + /** The object type that the ACL applies to */ + 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [AddMemberPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .permission() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): AddMemberPermission = + AddMemberPermission( + checkRequired("permission", permission), + restrictObjectType, + 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 + } + + return other is AddMemberPermission && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(permission, restrictObjectType, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AddMemberPermission{permission=$permission, restrictObjectType=$restrictObjectType, additionalProperties=$additionalProperties}" + } + + class RemoveMemberPermission + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * Permissions can be assigned to to objects on an individual basis, or grouped into roles + * + * @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 permission(): Permission = permission.getRequired("permission") + + /** + * The object type that the ACL applies to + * + * @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") + + /** + * Returns the raw JSON value of [permission]. + * + * Unlike [permission], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("permission") + @ExcludeMissing + fun _permission(): JsonField = permission + + /** + * 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 + + @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 [RemoveMemberPermission]. + * + * The following fields are required: + * ```java + * .permission() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [RemoveMemberPermission]. */ + class Builder internal constructor() { + + private var permission: JsonField? = null + private var restrictObjectType: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(removeMemberPermission: RemoveMemberPermission) = apply { + permission = removeMemberPermission.permission + restrictObjectType = removeMemberPermission.restrictObjectType + additionalProperties = removeMemberPermission.additionalProperties.toMutableMap() + } + + /** + * Each permission permits a certain type of operation on an object in the system + * + * Permissions can be assigned to to objects on an individual basis, or grouped into + * roles + */ + fun permission(permission: Permission) = permission(JsonField.of(permission)) + + /** + * 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 + } + + /** The object type that the ACL applies to */ + 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [RemoveMemberPermission]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .permission() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): RemoveMemberPermission = + RemoveMemberPermission( + checkRequired("permission", permission), + restrictObjectType, + 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 + } + + return other is RemoveMemberPermission && + permission == other.permission && + restrictObjectType == other.restrictObjectType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(permission, restrictObjectType, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RemoveMemberPermission{permission=$permission, restrictObjectType=$restrictObjectType, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is RoleUpdateParams && + roleId == other.roleId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(roleId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "RoleUpdateParams{roleId=$roleId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..a960bd03 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ScoreSummary.kt @@ -0,0 +1,329 @@ +// 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.checkRequired +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 */ +class ScoreSummary +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 improvements(): Long = improvements.getRequired("improvements") + + /** + * Name of the 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 name(): String = name.getRequired("name") + + /** + * Number of regressions in the 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 regressions(): Long = regressions.getRequired("regressions") + + /** + * Average score across all examples + * + * @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 score(): Double = score.getRequired("score") + + /** + * Difference in score between the current and comparison experiment + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun diff(): Optional = diff.getOptional("diff") + + /** + * Returns the raw JSON value of [improvements]. + * + * Unlike [improvements], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("improvements") + @ExcludeMissing + fun _improvements(): JsonField = improvements + + /** + * 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 [regressions]. + * + * Unlike [regressions], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("regressions") @ExcludeMissing fun _regressions(): JsonField = regressions + + /** + * Returns the raw JSON value of [score]. + * + * Unlike [score], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("score") @ExcludeMissing fun _score(): JsonField = score + + /** + * Returns the raw JSON value of [diff]. + * + * Unlike [diff], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("diff") @ExcludeMissing fun _diff(): JsonField = diff + + @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 [ScoreSummary]. + * + * The following fields are required: + * ```java + * .improvements() + * .name() + * .regressions() + * .score() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ScoreSummary]. */ + class Builder internal constructor() { + + private var improvements: JsonField? = null + private var name: JsonField? = null + private var regressions: JsonField? = null + private var score: JsonField? = null + private var diff: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scoreSummary: ScoreSummary) = apply { + improvements = scoreSummary.improvements + name = scoreSummary.name + regressions = scoreSummary.regressions + score = scoreSummary.score + diff = scoreSummary.diff + additionalProperties = scoreSummary.additionalProperties.toMutableMap() + } + + /** Number of improvements in the score */ + fun improvements(improvements: Long) = improvements(JsonField.of(improvements)) + + /** + * Sets [Builder.improvements] to an arbitrary JSON value. + * + * You should usually call [Builder.improvements] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun improvements(improvements: JsonField) = apply { this.improvements = improvements } + + /** Name of the 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 } + + /** Number of regressions in the score */ + fun regressions(regressions: Long) = regressions(JsonField.of(regressions)) + + /** + * Sets [Builder.regressions] to an arbitrary JSON value. + * + * You should usually call [Builder.regressions] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun regressions(regressions: JsonField) = apply { this.regressions = regressions } + + /** Average score across all examples */ + fun score(score: Double) = score(JsonField.of(score)) + + /** + * Sets [Builder.score] to an arbitrary JSON value. + * + * You should usually call [Builder.score] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun score(score: JsonField) = apply { this.score = score } + + /** Difference in score between the current and comparison experiment */ + fun diff(diff: Double) = diff(JsonField.of(diff)) + + /** + * Sets [Builder.diff] to an arbitrary JSON value. + * + * You should usually call [Builder.diff] with a well-typed [Double] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun diff(diff: JsonField) = apply { this.diff = diff } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ScoreSummary]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .improvements() + * .name() + * .regressions() + * .score() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ScoreSummary = + ScoreSummary( + checkRequired("improvements", improvements), + checkRequired("name", name), + checkRequired("regressions", regressions), + checkRequired("score", score), + diff, + 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 + } + + return other is ScoreSummary && + improvements == other.improvements && + name == other.name && + regressions == other.regressions && + score == other.score && + diff == other.diff && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(improvements, name, regressions, score, diff, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ScoreSummary{improvements=$improvements, name=$name, regressions=$regressions, score=$score, diff=$diff, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..0c75a9a3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanAttributes.kt @@ -0,0 +1,198 @@ +// 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.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. */ +class SpanAttributes +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 = name.getOptional("name") + + /** + * Type 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 type(): Optional = type.getOptional("type") + + /** + * 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 [type]. + * + * Unlike [type], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("type") @ExcludeMissing fun _type(): JsonField = type + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [SpanAttributes]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanAttributes]. */ + class Builder internal constructor() { + + private var name: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(spanAttributes: SpanAttributes) = apply { + name = spanAttributes.name + type = spanAttributes.type + additionalProperties = spanAttributes.additionalProperties.toMutableMap() + } + + /** Name of the span, for display purposes only */ + 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 } + + /** Type of the span, for display purposes only */ + fun type(type: SpanType?) = 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 [SpanType] 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 [SpanAttributes]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is SpanAttributes && + name == other.name && + type == other.type && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(name, type, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SpanAttributes{name=$name, type=$type, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..672c8cfc --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIFrame.kt @@ -0,0 +1,523 @@ +// 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.checkRequired +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 + +class SpanIFrame +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * Name of the span iframe + * + * @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 span iframe 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") + + /** + * URL to embed the project viewer in an iframe + * + * @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 url(): String = url.getRequired("url") + + /** + * Date of span iframe creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * Date of span iframe deletion, or null if the span iframe 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") + + /** + * 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") + + /** + * 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") + + /** + * Identifies the user who created the span iframe + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [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 [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 [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("user_id") @ExcludeMissing fun _userId(): JsonField = userId + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SpanIFrame]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIFrame]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var projectId: JsonField? = null + private var url: JsonField? = null + private var created: JsonField = JsonMissing.of() + private var deletedAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() + private var postMessage: JsonField = JsonMissing.of() + private var userId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(spanIFrame: SpanIFrame) = apply { + id = spanIFrame.id + name = spanIFrame.name + projectId = spanIFrame.projectId + url = spanIFrame.url + created = spanIFrame.created + deletedAt = spanIFrame.deletedAt + description = spanIFrame.description + postMessage = spanIFrame.postMessage + userId = spanIFrame.userId + additionalProperties = spanIFrame.additionalProperties.toMutableMap() + } + + /** Unique identifier for the span iframe */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** Name of the span iframe */ + 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 span iframe 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 } + + /** URL to embed the project viewer in an iframe */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** Date of span iframe creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Date of span iframe deletion, or null if the span iframe is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } + + /** 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 } + + /** + * 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 } + + /** Identifies the user who created the span iframe */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SpanIFrame]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .projectId() + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanIFrame = + SpanIFrame( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("url", url), + created, + deletedAt, + description, + postMessage, + userId, + 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 + } + + return other is SpanIFrame && + id == other.id && + name == other.name && + projectId == other.projectId && + url == other.url && + created == other.created && + deletedAt == other.deletedAt && + description == other.description && + postMessage == other.postMessage && + userId == other.userId && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + projectId, + url, + created, + deletedAt, + description, + postMessage, + userId, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SpanIFrame{id=$id, name=$name, projectId=$projectId, url=$url, created=$created, deletedAt=$deletedAt, description=$description, postMessage=$postMessage, userId=$userId, additionalProperties=$additionalProperties}" +} 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 new file mode 100644 index 00000000..ff2b7316 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeCreateParams.kt @@ -0,0 +1,735 @@ +// 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.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.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 + +/** + * Create a new span_iframe. If there is an existing span_iframe with the same name as the one + * specified in the request, will return the existing span_iframe unmodified + */ +class SpanIframeCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the span iframe + * + * @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 = body.name() + + /** + * Unique identifier for the project that the span iframe 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 = body.projectId() + + /** + * URL to embed the project viewer in an iframe + * + * @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 url(): String = body.url() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun postMessage(): Optional = body.postMessage() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _url(): JsonField = body._url() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [postMessage]. + * + * Unlike [postMessage], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _postMessage(): JsonField = body._postMessage() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 span iframe 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") + + /** + * URL to embed the project viewer in an iframe + * + * @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 url(): String = url.getRequired("url") + + /** + * 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") + + /** + * 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") + + /** + * 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 [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [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 [postMessage]. + * + * Unlike [postMessage], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("post_message") + @ExcludeMissing + fun _postMessage(): JsonField = postMessage + + @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() + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var url: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var postMessage: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + projectId = body.projectId + url = body.url + description = body.description + postMessage = body.postMessage + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the span iframe */ + 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 span iframe 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 } + + /** URL to embed the project viewer in an iframe */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** 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 + } + + /** + * 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("url", url), + description, + postMessage, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + url() + description() + postMessage() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a 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 (url.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (postMessage.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + projectId == other.projectId && + url == other.url && + description == other.description && + postMessage == other.postMessage && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, projectId, url, description, postMessage, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, url=$url, description=$description, postMessage=$postMessage, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanIframeCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "SpanIframeCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..78f3a416 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParams.kt @@ -0,0 +1,237 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import com.braintrustdata.api.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Delete a span_iframe object by its id */ +class SpanIframeDeleteParams +private constructor( + private val spanIframeId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) : Params { + + /** SpanIframe id */ + fun spanIframeId(): Optional = Optional.ofNullable(spanIframeId) + + /** Additional body properties to send with the request. */ + fun _additionalBodyProperties(): Map = additionalBodyProperties + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): SpanIframeDeleteParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [SpanIframeDeleteParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeDeleteParams]. */ + class Builder internal constructor() { + + private var spanIframeId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(spanIframeDeleteParams: SpanIframeDeleteParams) = apply { + spanIframeId = spanIframeDeleteParams.spanIframeId + additionalHeaders = spanIframeDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = spanIframeDeleteParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + spanIframeDeleteParams.additionalBodyProperties.toMutableMap() + } + + /** SpanIframe id */ + fun spanIframeId(spanIframeId: String?) = apply { this.spanIframeId = spanIframeId } + + /** Alias for calling [Builder.spanIframeId] with `spanIframeId.orElse(null)`. */ + fun spanIframeId(spanIframeId: Optional) = spanIframeId(spanIframeId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + /** + * Returns an immutable instance of [SpanIframeDeleteParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SpanIframeDeleteParams = + SpanIframeDeleteParams( + spanIframeId, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + 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 + } + + return other is SpanIframeDeleteParams && + spanIframeId == other.spanIframeId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams && + additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int = + Objects.hash( + spanIframeId, + additionalHeaders, + additionalQueryParams, + additionalBodyProperties, + ) + + override fun toString() = + "SpanIframeDeleteParams{spanIframeId=$spanIframeId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} 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 new file mode 100644 index 00000000..6fcfd056 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPage.kt @@ -0,0 +1,125 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.SpanIframeService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see SpanIframeService.list */ +class SpanIframeListPage +private constructor( + private val service: SpanIframeService, + private val params: SpanIframeListParams, + private val response: SpanIframeListPageResponse, +) : Page { + + /** + * Delegates to [SpanIframeListPageResponse], but gracefully handles missing data. + * + * @see SpanIframeListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): SpanIframeListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): SpanIframeListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): SpanIframeListParams = params + + /** The response that this page was parsed from. */ + fun response(): SpanIframeListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SpanIframeListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeListPage]. */ + class Builder internal constructor() { + + private var service: SpanIframeService? = null + private var params: SpanIframeListParams? = null + private var response: SpanIframeListPageResponse? = null + + @JvmSynthetic + internal fun from(spanIframeListPage: SpanIframeListPage) = apply { + service = spanIframeListPage.service + params = spanIframeListPage.params + response = spanIframeListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanIframeListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100644 index 00000000..c7541bca --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageAsync.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.SpanIframeServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see SpanIframeServiceAsync.list */ +class SpanIframeListPageAsync +private constructor( + private val service: SpanIframeServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: SpanIframeListParams, + private val response: SpanIframeListPageResponse, +) : PageAsync { + + /** + * Delegates to [SpanIframeListPageResponse], but gracefully handles missing data. + * + * @see SpanIframeListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): SpanIframeListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): SpanIframeListParams = params + + /** The response that this page was parsed from. */ + fun response(): SpanIframeListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [SpanIframeListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeListPageAsync]. */ + class Builder internal constructor() { + + private var service: SpanIframeServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: SpanIframeListParams? = null + private var response: SpanIframeListPageResponse? = null + + @JvmSynthetic + internal fun from(spanIframeListPageAsync: SpanIframeListPageAsync) = apply { + service = spanIframeListPageAsync.service + streamHandlerExecutor = spanIframeListPageAsync.streamHandlerExecutor + params = spanIframeListPageAsync.params + response = spanIframeListPageAsync.response + } + + fun service(service: SpanIframeServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SpanIframeListPageAsync = + SpanIframeListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanIframeListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "SpanIframeListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..a5b8da6f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListPageResponse.kt @@ -0,0 +1,195 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is SpanIframeListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100644 index 00000000..c2b00d9b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeListParams.kt @@ -0,0 +1,402 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +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 + */ +class SpanIframeListParams +private constructor( + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val spanIframeName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** Name of the span_iframe to search for */ + fun spanIframeName(): Optional = Optional.ofNullable(spanIframeName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): SpanIframeListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [SpanIframeListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeListParams]. */ + class Builder internal constructor() { + + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var spanIframeName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(spanIframeListParams: SpanIframeListParams) = apply { + endingBefore = spanIframeListParams.endingBefore + ids = spanIframeListParams.ids + limit = spanIframeListParams.limit + orgName = spanIframeListParams.orgName + spanIframeName = spanIframeListParams.spanIframeName + startingAfter = spanIframeListParams.startingAfter + additionalHeaders = spanIframeListParams.additionalHeaders.toBuilder() + additionalQueryParams = spanIframeListParams.additionalQueryParams.toBuilder() + } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** Name of the span_iframe to search for */ + fun spanIframeName(spanIframeName: String?) = apply { this.spanIframeName = spanIframeName } + + /** Alias for calling [Builder.spanIframeName] with `spanIframeName.orElse(null)`. */ + fun spanIframeName(spanIframeName: Optional) = + spanIframeName(spanIframeName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [SpanIframeListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SpanIframeListParams = + SpanIframeListParams( + endingBefore, + ids, + limit, + orgName, + spanIframeName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanIframeListParams && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + spanIframeName == other.spanIframeName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + endingBefore, + ids, + limit, + orgName, + spanIframeName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "SpanIframeListParams{endingBefore=$endingBefore, ids=$ids, limit=$limit, orgName=$orgName, spanIframeName=$spanIframeName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..66e52233 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParams.kt @@ -0,0 +1,735 @@ +// 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.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.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 + +/** + * Create or replace span_iframe. If there is an existing span_iframe with the same name as the one + * specified in the request, will replace the existing span_iframe with the provided fields + */ +class SpanIframeReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the span iframe + * + * @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 = body.name() + + /** + * Unique identifier for the project that the span iframe 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 = body.projectId() + + /** + * URL to embed the project viewer in an iframe + * + * @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 url(): String = body.url() + + /** + * 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 = body.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. + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun postMessage(): Optional = body.postMessage() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [projectId]. + * + * Unlike [projectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _projectId(): JsonField = body._projectId() + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _url(): JsonField = body._url() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [postMessage]. + * + * Unlike [postMessage], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _postMessage(): JsonField = body._postMessage() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * 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 + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + 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 + * + * @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 span iframe 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") + + /** + * URL to embed the project viewer in an iframe + * + * @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 url(): String = url.getRequired("url") + + /** + * 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") + + /** + * 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") + + /** + * 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 [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("url") @ExcludeMissing fun _url(): JsonField = url + + /** + * Returns the raw JSON value of [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 [postMessage]. + * + * Unlike [postMessage], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("post_message") + @ExcludeMissing + fun _postMessage(): JsonField = postMessage + + @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() + * .url() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Body]. */ + class Builder internal constructor() { + + private var name: JsonField? = null + private var projectId: JsonField? = null + private var url: JsonField? = null + private var description: JsonField = JsonMissing.of() + private var postMessage: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(body: Body) = apply { + name = body.name + projectId = body.projectId + url = body.url + description = body.description + postMessage = body.postMessage + additionalProperties = body.additionalProperties.toMutableMap() + } + + /** Name of the span iframe */ + 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 span iframe 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 } + + /** URL to embed the project viewer in an iframe */ + fun url(url: String) = url(JsonField.of(url)) + + /** + * Sets [Builder.url] to an arbitrary JSON value. + * + * You should usually call [Builder.url] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun url(url: JsonField) = apply { this.url = url } + + /** 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 + } + + /** + * 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 + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .url() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): Body = + Body( + checkRequired("name", name), + checkRequired("projectId", projectId), + checkRequired("url", url), + description, + postMessage, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + name() + projectId() + url() + description() + postMessage() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: BraintrustInvalidDataException) { + false + } + + /** + * Returns a 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 (url.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + + (if (postMessage.asKnown().isPresent) 1 else 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Body && + name == other.name && + projectId == other.projectId && + url == other.url && + description == other.description && + postMessage == other.postMessage && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(name, projectId, url, description, postMessage, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Body{name=$name, projectId=$projectId, url=$url, description=$description, postMessage=$postMessage, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SpanIframeReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "SpanIframeReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..b5d6c6e0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParams.kt @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a span_iframe object by its id */ +class SpanIframeRetrieveParams +private constructor( + private val spanIframeId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** SpanIframe id */ + fun spanIframeId(): Optional = Optional.ofNullable(spanIframeId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): SpanIframeRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [SpanIframeRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeRetrieveParams]. */ + class Builder internal constructor() { + + private var spanIframeId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(spanIframeRetrieveParams: SpanIframeRetrieveParams) = apply { + spanIframeId = spanIframeRetrieveParams.spanIframeId + additionalHeaders = spanIframeRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = spanIframeRetrieveParams.additionalQueryParams.toBuilder() + } + + /** SpanIframe id */ + fun spanIframeId(spanIframeId: String?) = apply { this.spanIframeId = spanIframeId } + + /** Alias for calling [Builder.spanIframeId] with `spanIframeId.orElse(null)`. */ + fun spanIframeId(spanIframeId: Optional) = spanIframeId(spanIframeId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [SpanIframeRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SpanIframeRetrieveParams = + SpanIframeRetrieveParams( + spanIframeId, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is SpanIframeRetrieveParams && + spanIframeId == other.spanIframeId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(spanIframeId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "SpanIframeRetrieveParams{spanIframeId=$spanIframeId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..0dd41fd8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParams.kt @@ -0,0 +1,662 @@ +// 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.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +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 + +/** + * Partially update a span_iframe object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ +class SpanIframeUpdateParams +private constructor( + private val spanIframeId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** SpanIframe id */ + fun spanIframeId(): Optional = Optional.ofNullable(spanIframeId) + + /** + * 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 = body.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 = body.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 = body.postMessage() + + /** + * 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 = body.url() + + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [postMessage]. + * + * Unlike [postMessage], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _postMessage(): JsonField = body._postMessage() + + /** + * Returns the raw JSON value of [url]. + * + * Unlike [url], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _url(): JsonField = body._url() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): SpanIframeUpdateParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [SpanIframeUpdateParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SpanIframeUpdateParams]. */ + class Builder internal constructor() { + + private var spanIframeId: 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(spanIframeUpdateParams: SpanIframeUpdateParams) = apply { + spanIframeId = spanIframeUpdateParams.spanIframeId + body = spanIframeUpdateParams.body.toBuilder() + additionalHeaders = spanIframeUpdateParams.additionalHeaders.toBuilder() + additionalQueryParams = spanIframeUpdateParams.additionalQueryParams.toBuilder() + } + + /** SpanIframe id */ + fun spanIframeId(spanIframeId: String?) = apply { this.spanIframeId = spanIframeId } + + /** Alias for calling [Builder.spanIframeId] with `spanIframeId.orElse(null)`. */ + fun spanIframeId(spanIframeId: Optional) = spanIframeId(spanIframeId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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) } + + /** 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 span iframe */ + 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 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) } + + /** URL to embed the project viewer in an iframe */ + fun url(url: String?) = apply { body.url(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 { body.url(url) } + + 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 [SpanIframeUpdateParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): SpanIframeUpdateParams = + SpanIframeUpdateParams( + spanIframeId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 other is Body && + description == other.description && + name == other.name && + postMessage == other.postMessage && + url == other.url && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(description, name, postMessage, url, additionalProperties) + } + + 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 + } + + return other is SpanIframeUpdateParams && + spanIframeId == other.spanIframeId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(spanIframeId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "SpanIframeUpdateParams{spanIframeId=$spanIframeId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..ec98994e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SpanType.kt @@ -0,0 +1,156 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.errors.BraintrustInvalidDataException +import com.fasterxml.jackson.annotation.JsonCreator + +/** Type of the span, for display purposes only */ +class SpanType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val LLM = of("llm") + + @JvmField val SCORE = of("score") + + @JvmField val FUNCTION = of("function") + + @JvmField val EVAL = of("eval") + + @JvmField val TASK = of("task") + + @JvmField val TOOL = of("tool") + + @JvmStatic fun of(value: String) = SpanType(JsonField.of(value)) + } + + /** An enum containing [SpanType]'s known values. */ + enum class Known { + LLM, + SCORE, + FUNCTION, + EVAL, + TASK, + TOOL, + } + + /** + * An enum containing [SpanType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [SpanType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + LLM, + SCORE, + FUNCTION, + EVAL, + TASK, + TOOL, + /** An enum member indicating that [SpanType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + LLM -> Value.LLM + SCORE -> Value.SCORE + FUNCTION -> Value.FUNCTION + EVAL -> Value.EVAL + TASK -> Value.TASK + TOOL -> Value.TOOL + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + LLM -> Known.LLM + SCORE -> Known.SCORE + FUNCTION -> Known.FUNCTION + EVAL -> Known.EVAL + TASK -> Known.TASK + TOOL -> Known.TOOL + else -> throw BraintrustInvalidDataException("Unknown SpanType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { BraintrustInvalidDataException("Value is not a String") } + + private var validated: Boolean = false + + fun validate(): SpanType = 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 + } + + return other is SpanType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponse.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponse.kt new file mode 100755 index 00000000..7e04b7d1 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponse.kt @@ -0,0 +1,355 @@ +// 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.checkRequired +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 a dataset */ +class SummarizeDatasetResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 datasetName(): String = datasetName.getRequired("dataset_name") + + /** + * URL to the dataset's page in the Braintrust app + * + * @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 datasetUrl(): String = datasetUrl.getRequired("dataset_url") + + /** + * Name of the project that the dataset belongs 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 projectName(): String = projectName.getRequired("project_name") + + /** + * URL to the project's page in the Braintrust app + * + * @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 projectUrl(): String = projectUrl.getRequired("project_url") + + /** + * Summary of a dataset's data + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun dataSummary(): Optional = dataSummary.getOptional("data_summary") + + /** + * Returns the raw JSON value of [datasetName]. + * + * Unlike [datasetName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("dataset_name") + @ExcludeMissing + fun _datasetName(): JsonField = datasetName + + /** + * Returns the raw JSON value of [datasetUrl]. + * + * Unlike [datasetUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("dataset_url") @ExcludeMissing fun _datasetUrl(): JsonField = datasetUrl + + /** + * Returns the raw JSON value of [projectName]. + * + * Unlike [projectName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_name") + @ExcludeMissing + fun _projectName(): JsonField = projectName + + /** + * Returns the raw JSON value of [projectUrl]. + * + * Unlike [projectUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_url") @ExcludeMissing fun _projectUrl(): JsonField = projectUrl + + /** + * Returns the raw JSON value of [dataSummary]. + * + * Unlike [dataSummary], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("data_summary") + @ExcludeMissing + fun _dataSummary(): JsonField = dataSummary + + @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 [SummarizeDatasetResponse]. + * + * The following fields are required: + * ```java + * .datasetName() + * .datasetUrl() + * .projectName() + * .projectUrl() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SummarizeDatasetResponse]. */ + class Builder internal constructor() { + + private var datasetName: JsonField? = null + private var datasetUrl: JsonField? = null + private var projectName: JsonField? = null + private var projectUrl: JsonField? = null + private var dataSummary: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(summarizeDatasetResponse: SummarizeDatasetResponse) = apply { + datasetName = summarizeDatasetResponse.datasetName + datasetUrl = summarizeDatasetResponse.datasetUrl + projectName = summarizeDatasetResponse.projectName + projectUrl = summarizeDatasetResponse.projectUrl + dataSummary = summarizeDatasetResponse.dataSummary + additionalProperties = summarizeDatasetResponse.additionalProperties.toMutableMap() + } + + /** Name of the dataset */ + fun datasetName(datasetName: String) = datasetName(JsonField.of(datasetName)) + + /** + * Sets [Builder.datasetName] to an arbitrary JSON value. + * + * You should usually call [Builder.datasetName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun datasetName(datasetName: JsonField) = apply { this.datasetName = datasetName } + + /** URL to the dataset's page in the Braintrust app */ + fun datasetUrl(datasetUrl: String) = datasetUrl(JsonField.of(datasetUrl)) + + /** + * Sets [Builder.datasetUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.datasetUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun datasetUrl(datasetUrl: JsonField) = apply { this.datasetUrl = datasetUrl } + + /** Name of the project that the dataset belongs to */ + fun projectName(projectName: String) = projectName(JsonField.of(projectName)) + + /** + * Sets [Builder.projectName] to an arbitrary JSON value. + * + * You should usually call [Builder.projectName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectName(projectName: JsonField) = apply { this.projectName = projectName } + + /** URL to the project's page in the Braintrust app */ + fun projectUrl(projectUrl: String) = projectUrl(JsonField.of(projectUrl)) + + /** + * Sets [Builder.projectUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.projectUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectUrl(projectUrl: JsonField) = apply { this.projectUrl = projectUrl } + + /** Summary of a dataset's data */ + fun dataSummary(dataSummary: DataSummary?) = dataSummary(JsonField.ofNullable(dataSummary)) + + /** Alias for calling [Builder.dataSummary] with `dataSummary.orElse(null)`. */ + fun dataSummary(dataSummary: Optional) = dataSummary(dataSummary.getOrNull()) + + /** + * Sets [Builder.dataSummary] to an arbitrary JSON value. + * + * You should usually call [Builder.dataSummary] with a well-typed [DataSummary] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun dataSummary(dataSummary: JsonField) = apply { + this.dataSummary = dataSummary + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SummarizeDatasetResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .datasetName() + * .datasetUrl() + * .projectName() + * .projectUrl() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SummarizeDatasetResponse = + SummarizeDatasetResponse( + checkRequired("datasetName", datasetName), + checkRequired("datasetUrl", datasetUrl), + checkRequired("projectName", projectName), + checkRequired("projectUrl", projectUrl), + dataSummary, + 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 + } + + return other is SummarizeDatasetResponse && + datasetName == other.datasetName && + datasetUrl == other.datasetUrl && + projectName == other.projectName && + projectUrl == other.projectUrl && + dataSummary == other.dataSummary && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + datasetName, + datasetUrl, + projectName, + projectUrl, + dataSummary, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SummarizeDatasetResponse{datasetName=$datasetName, datasetUrl=$datasetUrl, projectName=$projectName, projectUrl=$projectUrl, dataSummary=$dataSummary, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..b2acbaa8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponse.kt @@ -0,0 +1,654 @@ +// 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.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 java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Summary of an experiment */ +class SummarizeExperimentResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 experimentName(): String = experimentName.getRequired("experiment_name") + + /** + * URL to the experiment's page in the Braintrust app + * + * @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 experimentUrl(): String = experimentUrl.getRequired("experiment_url") + + /** + * Name of the project that the experiment belongs 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 projectName(): String = projectName.getRequired("project_name") + + /** + * URL to the project's page in the Braintrust app + * + * @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 projectUrl(): String = projectUrl.getRequired("project_url") + + /** + * The experiment which scores are baselined against + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun comparisonExperimentName(): Optional = + comparisonExperimentName.getOptional("comparison_experiment_name") + + /** + * Summary of the experiment's metrics + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metrics(): Optional = metrics.getOptional("metrics") + + /** + * Summary of the experiment's scores + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun scores(): Optional = scores.getOptional("scores") + + /** + * 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 the raw JSON value of [experimentUrl]. + * + * Unlike [experimentUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("experiment_url") + @ExcludeMissing + fun _experimentUrl(): JsonField = experimentUrl + + /** + * Returns the raw JSON value of [projectName]. + * + * Unlike [projectName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_name") + @ExcludeMissing + fun _projectName(): JsonField = projectName + + /** + * Returns the raw JSON value of [projectUrl]. + * + * Unlike [projectUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("project_url") @ExcludeMissing fun _projectUrl(): JsonField = projectUrl + + /** + * Returns the raw JSON value of [comparisonExperimentName]. + * + * Unlike [comparisonExperimentName], this method doesn't throw if the JSON field has an + * unexpected type. + */ + @JsonProperty("comparison_experiment_name") + @ExcludeMissing + fun _comparisonExperimentName(): JsonField = comparisonExperimentName + + /** + * Returns the raw JSON value of [metrics]. + * + * Unlike [metrics], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metrics") @ExcludeMissing fun _metrics(): JsonField = metrics + + /** + * 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 + + @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 [SummarizeExperimentResponse]. + * + * The following fields are required: + * ```java + * .experimentName() + * .experimentUrl() + * .projectName() + * .projectUrl() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [SummarizeExperimentResponse]. */ + class Builder internal constructor() { + + private var experimentName: JsonField? = null + private var experimentUrl: JsonField? = null + private var projectName: JsonField? = null + private var projectUrl: JsonField? = null + private var comparisonExperimentName: JsonField = JsonMissing.of() + private var metrics: JsonField = JsonMissing.of() + private var scores: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(summarizeExperimentResponse: SummarizeExperimentResponse) = apply { + experimentName = summarizeExperimentResponse.experimentName + experimentUrl = summarizeExperimentResponse.experimentUrl + projectName = summarizeExperimentResponse.projectName + projectUrl = summarizeExperimentResponse.projectUrl + comparisonExperimentName = summarizeExperimentResponse.comparisonExperimentName + metrics = summarizeExperimentResponse.metrics + scores = summarizeExperimentResponse.scores + additionalProperties = summarizeExperimentResponse.additionalProperties.toMutableMap() + } + + /** Name of the experiment */ + 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 + } + + /** URL to the experiment's page in the Braintrust app */ + fun experimentUrl(experimentUrl: String) = experimentUrl(JsonField.of(experimentUrl)) + + /** + * Sets [Builder.experimentUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.experimentUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun experimentUrl(experimentUrl: JsonField) = apply { + this.experimentUrl = experimentUrl + } + + /** Name of the project that the experiment belongs to */ + fun projectName(projectName: String) = projectName(JsonField.of(projectName)) + + /** + * Sets [Builder.projectName] to an arbitrary JSON value. + * + * You should usually call [Builder.projectName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectName(projectName: JsonField) = apply { this.projectName = projectName } + + /** URL to the project's page in the Braintrust app */ + fun projectUrl(projectUrl: String) = projectUrl(JsonField.of(projectUrl)) + + /** + * Sets [Builder.projectUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.projectUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun projectUrl(projectUrl: JsonField) = apply { this.projectUrl = projectUrl } + + /** The experiment which scores are baselined against */ + fun comparisonExperimentName(comparisonExperimentName: String?) = + comparisonExperimentName(JsonField.ofNullable(comparisonExperimentName)) + + /** + * Alias for calling [Builder.comparisonExperimentName] with + * `comparisonExperimentName.orElse(null)`. + */ + fun comparisonExperimentName(comparisonExperimentName: Optional) = + comparisonExperimentName(comparisonExperimentName.getOrNull()) + + /** + * Sets [Builder.comparisonExperimentName] to an arbitrary JSON value. + * + * You should usually call [Builder.comparisonExperimentName] with a well-typed [String] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun comparisonExperimentName(comparisonExperimentName: JsonField) = apply { + this.comparisonExperimentName = comparisonExperimentName + } + + /** Summary of the experiment's metrics */ + fun metrics(metrics: Metrics?) = metrics(JsonField.ofNullable(metrics)) + + /** Alias for calling [Builder.metrics] with `metrics.orElse(null)`. */ + fun metrics(metrics: Optional) = metrics(metrics.getOrNull()) + + /** + * Sets [Builder.metrics] to an arbitrary JSON value. + * + * You should usually call [Builder.metrics] with a well-typed [Metrics] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun metrics(metrics: JsonField) = apply { this.metrics = metrics } + + /** Summary of the experiment's scores */ + fun scores(scores: Scores?) = scores(JsonField.ofNullable(scores)) + + /** Alias for calling [Builder.scores] with `scores.orElse(null)`. */ + fun scores(scores: Optional) = scores(scores.getOrNull()) + + /** + * Sets [Builder.scores] to an arbitrary JSON value. + * + * You should usually call [Builder.scores] with a well-typed [Scores] 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 } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [SummarizeExperimentResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .experimentName() + * .experimentUrl() + * .projectName() + * .projectUrl() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): SummarizeExperimentResponse = + SummarizeExperimentResponse( + checkRequired("experimentName", experimentName), + checkRequired("experimentUrl", experimentUrl), + checkRequired("projectName", projectName), + checkRequired("projectUrl", projectUrl), + comparisonExperimentName, + metrics, + scores, + 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 */ + class Metrics + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metrics]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metrics]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metrics: Metrics) = apply { + additionalProperties = metrics.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 [Metrics]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Metrics && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metrics{additionalProperties=$additionalProperties}" + } + + /** Summary of the experiment's scores */ + class Scores + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Scores]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Scores]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(scores: Scores) = apply { + additionalProperties = scores.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 [Scores]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is Scores && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Scores{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is SummarizeExperimentResponse && + experimentName == other.experimentName && + experimentUrl == other.experimentUrl && + projectName == other.projectName && + projectUrl == other.projectUrl && + comparisonExperimentName == other.comparisonExperimentName && + metrics == other.metrics && + scores == other.scores && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + experimentName, + experimentUrl, + projectName, + projectUrl, + comparisonExperimentName, + metrics, + scores, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "SummarizeExperimentResponse{experimentName=$experimentName, experimentUrl=$experimentUrl, projectName=$projectName, projectUrl=$projectUrl, comparisonExperimentName=$comparisonExperimentName, metrics=$metrics, scores=$scores, additionalProperties=$additionalProperties}" +} 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 old mode 100644 new mode 100755 index 9575b9fa..da51fccf --- 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,105 +2,169 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.NoAutoDetect -import com.braintrustdata.api.core.toUnmodifiable -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams import java.util.Objects +/** Default endpoint. Simply replies with 'Hello, World!'. Authorization is not required */ class TopLevelHelloWorldParams -constructor( - private val additionalQueryParams: Map>, - private val additionalHeaders: Map>, -) { +private constructor( + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { - @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders - @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams - fun _additionalQueryParams(): Map> = additionalQueryParams + fun toBuilder() = Builder().from(this) - fun _additionalHeaders(): Map> = additionalHeaders + companion object { - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } + @JvmStatic fun none(): TopLevelHelloWorldParams = builder().build() - return other is TopLevelHelloWorldParams && - this.additionalQueryParams == other.additionalQueryParams && - this.additionalHeaders == other.additionalHeaders + /** Returns a mutable builder for constructing an instance of [TopLevelHelloWorldParams]. */ + @JvmStatic fun builder() = Builder() } - override fun hashCode(): Int { - return Objects.hash(additionalQueryParams, additionalHeaders) - } + /** A builder for [TopLevelHelloWorldParams]. */ + class Builder internal constructor() { - override fun toString() = - "TopLevelHelloWorldParams{additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() - fun toBuilder() = Builder().from(this) + @JvmSynthetic + internal fun from(topLevelHelloWorldParams: TopLevelHelloWorldParams) = apply { + additionalHeaders = topLevelHelloWorldParams.additionalHeaders.toBuilder() + additionalQueryParams = topLevelHelloWorldParams.additionalQueryParams.toBuilder() + } - companion object { + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - @JvmStatic fun builder() = Builder() - } + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } - @NoAutoDetect - class Builder { + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } - private var additionalQueryParams: MutableMap> = mutableMapOf() - private var additionalHeaders: MutableMap> = mutableMapOf() + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } - @JvmSynthetic - internal fun from(topLevelHelloWorldParams: TopLevelHelloWorldParams) = apply { - additionalQueryParams(topLevelHelloWorldParams.additionalQueryParams) - additionalHeaders(topLevelHelloWorldParams.additionalHeaders) + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun additionalQueryParams(additionalQueryParams: Map>) = apply { - this.additionalQueryParams.clear() - putAllQueryParams(additionalQueryParams) + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) } - fun putQueryParam(name: String, value: String) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) } - fun putQueryParams(name: String, values: Iterable) = apply { - this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) } - fun putAllQueryParams(additionalQueryParams: Map>) = apply { - additionalQueryParams.forEach(this::putQueryParams) + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun removeQueryParam(name: String) = apply { - this.additionalQueryParams.put(name, mutableListOf()) + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) } - fun additionalHeaders(additionalHeaders: Map>) = apply { - this.additionalHeaders.clear() - putAllHeaders(additionalHeaders) + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) } - fun putHeader(name: String, value: String) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) } - fun putHeaders(name: String, values: Iterable) = apply { - this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) } - fun putAllHeaders(additionalHeaders: Map>) = apply { - additionalHeaders.forEach(this::putHeaders) + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) } - fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + 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 [TopLevelHelloWorldParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ fun build(): TopLevelHelloWorldParams = - TopLevelHelloWorldParams( - additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), - additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable() - ) + 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 + } + + return other is TopLevelHelloWorldParams && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams } + + override fun hashCode(): Int = Objects.hash(additionalHeaders, additionalQueryParams) + + override fun toString() = + "TopLevelHelloWorldParams{additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } 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 new file mode 100755 index 00000000..46f7ad70 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/User.kt @@ -0,0 +1,373 @@ +// 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.checkRequired +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 + +class User +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * URL of the user's Avatar image + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun avatarUrl(): Optional = avatarUrl.getOptional("avatar_url") + + /** + * Date of user creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * The user's email + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun email(): Optional = email.getOptional("email") + + /** + * Family name of the user + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun familyName(): Optional = familyName.getOptional("family_name") + + /** + * Given name of the user + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun givenName(): Optional = givenName.getOptional("given_name") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [avatarUrl]. + * + * Unlike [avatarUrl], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("avatar_url") @ExcludeMissing fun _avatarUrl(): JsonField = avatarUrl + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [email]. + * + * Unlike [email], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("email") @ExcludeMissing fun _email(): JsonField = email + + /** + * Returns the raw JSON value of [familyName]. + * + * Unlike [familyName], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("family_name") @ExcludeMissing fun _familyName(): JsonField = familyName + + /** + * Returns the raw JSON value of [givenName]. + * + * Unlike [givenName], this method doesn't throw if the JSON field has an unexpected type. + */ + @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 = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [User]. + * + * The following fields are required: + * ```java + * .id() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [User]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var avatarUrl: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var email: JsonField = JsonMissing.of() + private var familyName: JsonField = JsonMissing.of() + private var givenName: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(user: User) = apply { + id = user.id + avatarUrl = user.avatarUrl + created = user.created + email = user.email + familyName = user.familyName + givenName = user.givenName + additionalProperties = user.additionalProperties.toMutableMap() + } + + /** Unique identifier for the user */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** URL of the user's Avatar image */ + fun avatarUrl(avatarUrl: String?) = avatarUrl(JsonField.ofNullable(avatarUrl)) + + /** Alias for calling [Builder.avatarUrl] with `avatarUrl.orElse(null)`. */ + fun avatarUrl(avatarUrl: Optional) = avatarUrl(avatarUrl.getOrNull()) + + /** + * Sets [Builder.avatarUrl] to an arbitrary JSON value. + * + * You should usually call [Builder.avatarUrl] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun avatarUrl(avatarUrl: JsonField) = apply { this.avatarUrl = avatarUrl } + + /** Date of user creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** The user's email */ + fun email(email: String?) = email(JsonField.ofNullable(email)) + + /** Alias for calling [Builder.email] with `email.orElse(null)`. */ + fun email(email: Optional) = email(email.getOrNull()) + + /** + * Sets [Builder.email] to an arbitrary JSON value. + * + * You should usually call [Builder.email] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun email(email: JsonField) = apply { this.email = email } + + /** Family name of the user */ + fun familyName(familyName: String?) = familyName(JsonField.ofNullable(familyName)) + + /** Alias for calling [Builder.familyName] with `familyName.orElse(null)`. */ + fun familyName(familyName: Optional) = familyName(familyName.getOrNull()) + + /** + * Sets [Builder.familyName] to an arbitrary JSON value. + * + * You should usually call [Builder.familyName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun familyName(familyName: JsonField) = apply { this.familyName = familyName } + + /** Given name of the user */ + fun givenName(givenName: String?) = givenName(JsonField.ofNullable(givenName)) + + /** Alias for calling [Builder.givenName] with `givenName.orElse(null)`. */ + fun givenName(givenName: Optional) = givenName(givenName.getOrNull()) + + /** + * Sets [Builder.givenName] to an arbitrary JSON value. + * + * You should usually call [Builder.givenName] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun givenName(givenName: JsonField) = apply { this.givenName = givenName } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [User]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): User = + User( + checkRequired("id", id), + avatarUrl, + created, + email, + familyName, + givenName, + 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 + } + + return other is User && + id == other.id && + avatarUrl == other.avatarUrl && + created == other.created && + email == other.email && + familyName == other.familyName && + givenName == other.givenName && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(id, avatarUrl, created, email, familyName, givenName, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "User{id=$id, avatarUrl=$avatarUrl, created=$created, email=$email, familyName=$familyName, givenName=$givenName, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..e8fa075b --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPage.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.UserService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see UserService.list */ +class UserListPage +private constructor( + private val service: UserService, + private val params: UserListParams, + private val response: UserListPageResponse, +) : Page { + + /** + * Delegates to [UserListPageResponse], but gracefully handles missing data. + * + * @see UserListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): UserListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): UserListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): UserListParams = params + + /** The response that this page was parsed from. */ + fun response(): UserListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UserListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserListPage]. */ + class Builder internal constructor() { + + private var service: UserService? = null + private var params: UserListParams? = null + private var response: UserListPageResponse? = null + + @JvmSynthetic + internal fun from(userListPage: UserListPage) = apply { + service = userListPage.service + params = userListPage.params + response = userListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..8635b6e5 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageAsync.kt @@ -0,0 +1,138 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.UserServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see UserServiceAsync.list */ +class UserListPageAsync +private constructor( + private val service: UserServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: UserListParams, + private val response: UserListPageResponse, +) : PageAsync { + + /** + * Delegates to [UserListPageResponse], but gracefully handles missing data. + * + * @see UserListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): UserListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): UserListParams = params + + /** The response that this page was parsed from. */ + fun response(): UserListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [UserListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserListPageAsync]. */ + class Builder internal constructor() { + + private var service: UserServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: UserListParams? = null + private var response: UserListPageResponse? = null + + @JvmSynthetic + internal fun from(userListPageAsync: UserListPageAsync) = apply { + service = userListPageAsync.service + streamHandlerExecutor = userListPageAsync.streamHandlerExecutor + params = userListPageAsync.params + response = userListPageAsync.response + } + + fun service(service: UserServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): UserListPageAsync = + UserListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "UserListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..9d561b45 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListPageResponse.kt @@ -0,0 +1,193 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is UserListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..6b14d619 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserListParams.kt @@ -0,0 +1,691 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all users. The users are sorted by creation date, with the most recently-created users + * coming first + */ +class UserListParams +private constructor( + private val email: Email?, + private val endingBefore: String?, + private val familyName: FamilyName?, + private val givenName: GivenName?, + private val ids: Ids?, + private val limit: Long?, + private val orgName: String?, + private val startingAfter: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Email of the user to search for. You may pass the param multiple times to filter for more + * than one email + */ + fun email(): Optional = Optional.ofNullable(email) + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Family name of the user to search for. You may pass the param multiple times to filter for + * more than one family name + */ + fun familyName(): Optional = Optional.ofNullable(familyName) + + /** + * Given name of the user to search for. You may pass the param multiple times to filter for + * more than one given name + */ + fun givenName(): Optional = Optional.ofNullable(givenName) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** Filter search results to within a particular organization */ + fun orgName(): Optional = Optional.ofNullable(orgName) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): UserListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [UserListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserListParams]. */ + class Builder internal constructor() { + + private var email: Email? = null + private var endingBefore: String? = null + private var familyName: FamilyName? = null + private var givenName: GivenName? = null + private var ids: Ids? = null + private var limit: Long? = null + private var orgName: String? = null + private var startingAfter: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(userListParams: UserListParams) = apply { + email = userListParams.email + endingBefore = userListParams.endingBefore + familyName = userListParams.familyName + givenName = userListParams.givenName + ids = userListParams.ids + limit = userListParams.limit + orgName = userListParams.orgName + startingAfter = userListParams.startingAfter + additionalHeaders = userListParams.additionalHeaders.toBuilder() + additionalQueryParams = userListParams.additionalQueryParams.toBuilder() + } + + /** + * Email of the user to search for. You may pass the param multiple times to filter for more + * than one email + */ + fun email(email: Email?) = apply { this.email = email } + + /** Alias for calling [Builder.email] with `email.orElse(null)`. */ + fun email(email: Optional) = email(email.getOrNull()) + + /** Alias for calling [email] with `Email.ofString(string)`. */ + fun email(string: String) = email(Email.ofString(string)) + + /** Alias for calling [email] with `Email.ofStrings(strings)`. */ + fun emailOfStrings(strings: List) = email(Email.ofStrings(strings)) + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Family name of the user to search for. You may pass the param multiple times to filter + * for more than one family name + */ + fun familyName(familyName: FamilyName?) = apply { this.familyName = familyName } + + /** Alias for calling [Builder.familyName] with `familyName.orElse(null)`. */ + fun familyName(familyName: Optional) = familyName(familyName.getOrNull()) + + /** Alias for calling [familyName] with `FamilyName.ofString(string)`. */ + fun familyName(string: String) = familyName(FamilyName.ofString(string)) + + /** Alias for calling [familyName] with `FamilyName.ofStrings(strings)`. */ + fun familyNameOfStrings(strings: List) = familyName(FamilyName.ofStrings(strings)) + + /** + * Given name of the user to search for. You may pass the param multiple times to filter for + * more than one given name + */ + fun givenName(givenName: GivenName?) = apply { this.givenName = givenName } + + /** Alias for calling [Builder.givenName] with `givenName.orElse(null)`. */ + fun givenName(givenName: Optional) = givenName(givenName.getOrNull()) + + /** Alias for calling [givenName] with `GivenName.ofString(string)`. */ + fun givenName(string: String) = givenName(GivenName.ofString(string)) + + /** Alias for calling [givenName] with `GivenName.ofStrings(strings)`. */ + fun givenNameOfStrings(strings: List) = givenName(GivenName.ofStrings(strings)) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** Filter search results to within a particular organization */ + fun orgName(orgName: String?) = apply { this.orgName = orgName } + + /** Alias for calling [Builder.orgName] with `orgName.orElse(null)`. */ + fun orgName(orgName: Optional) = orgName(orgName.getOrNull()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [UserListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UserListParams = + UserListParams( + email, + endingBefore, + familyName, + givenName, + ids, + limit, + orgName, + startingAfter, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Email + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Email") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Email && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Email{string=$string}" + strings != null -> "Email{strings=$strings}" + else -> throw IllegalStateException("Invalid Email") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Email(string = string) + + @JvmStatic fun ofStrings(strings: List) = Email(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Email] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + /** + * Family name of the user to search for. You may pass the param multiple times to filter for + * more than one family name + */ + class FamilyName + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid FamilyName") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FamilyName && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "FamilyName{string=$string}" + strings != null -> "FamilyName{strings=$strings}" + else -> throw IllegalStateException("Invalid FamilyName") + } + + companion object { + + @JvmStatic fun ofString(string: String) = FamilyName(string = string) + + @JvmStatic + fun ofStrings(strings: List) = FamilyName(strings = strings.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [FamilyName] to a value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + /** + * Given name of the user to search for. You may pass the param multiple times to filter for + * more than one given name + */ + class GivenName + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid GivenName") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is GivenName && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "GivenName{string=$string}" + strings != null -> "GivenName{strings=$strings}" + else -> throw IllegalStateException("Invalid GivenName") + } + + companion object { + + @JvmStatic fun ofString(string: String) = GivenName(string = string) + + @JvmStatic + fun ofStrings(strings: List) = GivenName(strings = strings.toImmutable()) + } + + /** + * An interface that defines how to map each variant of [GivenName] to a value of type [T]. + */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UserListParams && + email == other.email && + endingBefore == other.endingBefore && + familyName == other.familyName && + givenName == other.givenName && + ids == other.ids && + limit == other.limit && + orgName == other.orgName && + startingAfter == other.startingAfter && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + email, + endingBefore, + familyName, + givenName, + ids, + limit, + orgName, + startingAfter, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "UserListParams{email=$email, endingBefore=$endingBefore, familyName=$familyName, givenName=$givenName, ids=$ids, limit=$limit, orgName=$orgName, startingAfter=$startingAfter, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..b403a90a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/UserRetrieveParams.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Params +import com.braintrustdata.api.core.http.Headers +import com.braintrustdata.api.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a user object by its id */ +class UserRetrieveParams +private constructor( + private val userId: String?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** User id */ + fun userId(): Optional = Optional.ofNullable(userId) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): UserRetrieveParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [UserRetrieveParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [UserRetrieveParams]. */ + class Builder internal constructor() { + + private var userId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(userRetrieveParams: UserRetrieveParams) = apply { + userId = userRetrieveParams.userId + additionalHeaders = userRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = userRetrieveParams.additionalQueryParams.toBuilder() + } + + /** User id */ + fun userId(userId: String?) = apply { this.userId = userId } + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [UserRetrieveParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): UserRetrieveParams = + UserRetrieveParams(userId, additionalHeaders.build(), additionalQueryParams.build()) + } + + 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 + } + + return other is UserRetrieveParams && + userId == other.userId && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(userId, additionalHeaders, additionalQueryParams) + + override fun toString() = + "UserRetrieveParams{userId=$userId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..c95c3d06 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/View.kt @@ -0,0 +1,737 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.checkRequired +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 + +class View +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 + * + * @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 id(): String = id.getRequired("id") + + /** + * Name of the view + * + * @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 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") + + /** + * 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") + + /** + * Date of view creation + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun created(): Optional = created.getOptional("created") + + /** + * 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") + + /** + * 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") + + /** + * Identifies the user who created the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [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 [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 + + /** + * 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 + + /** + * Returns the raw JSON value of [created]. + * + * Unlike [created], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created") @ExcludeMissing fun _created(): JsonField = created + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = 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 + + /** + * 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 + + @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 [View]. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [View]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var name: JsonField? = null + private var objectId: JsonField? = null + private var objectType: JsonField? = null + private var viewType: JsonField? = null + private var created: JsonField = JsonMissing.of() + 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(view: View) = apply { + id = view.id + name = view.name + objectId = view.objectId + objectType = view.objectType + viewType = view.viewType + created = view.created + deletedAt = view.deletedAt + options = view.options + userId = view.userId + viewData = view.viewData + additionalProperties = view.additionalProperties.toMutableMap() + } + + /** Unique identifier for the view */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + /** 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 + } + + /** 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 } + + /** Date of view creation */ + fun created(created: OffsetDateTime?) = created(JsonField.ofNullable(created)) + + /** Alias for calling [Builder.created] with `created.orElse(null)`. */ + fun created(created: Optional) = created(created.getOrNull()) + + /** + * Sets [Builder.created] to an arbitrary JSON value. + * + * You should usually call [Builder.created] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun created(created: JsonField) = apply { this.created = created } + + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { this.deletedAt = deletedAt } + + /** Options for the view in the app */ + fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) + + /** + * 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 } + + /** Identifies the user who created the view */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + /** The view definition */ + fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) + + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [View]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): View = + View( + checkRequired("id", id), + checkRequired("name", name), + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + checkRequired("viewType", viewType), + created, + deletedAt, + options, + userId, + viewData, + 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 { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROJECTS = of("projects") + + @JvmField val EXPERIMENTS = of("experiments") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val PLAYGROUNDS = of("playgrounds") + + @JvmField val PLAYGROUND = of("playground") + + @JvmField val DATASETS = of("datasets") + + @JvmField val DATASET = of("dataset") + + @JvmField val PROMPTS = of("prompts") + + @JvmField val TOOLS = of("tools") + + @JvmField val SCORERS = of("scorers") + + @JvmField val LOGS = of("logs") + + @JvmStatic fun of(value: String) = ViewType(JsonField.of(value)) + } + + /** An enum containing [ViewType]'s known values. */ + enum class Known { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + } + + /** + * An enum containing [ViewType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ViewType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + /** An enum member indicating that [ViewType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROJECTS -> Value.PROJECTS + EXPERIMENTS -> Value.EXPERIMENTS + EXPERIMENT -> Value.EXPERIMENT + PLAYGROUNDS -> Value.PLAYGROUNDS + PLAYGROUND -> Value.PLAYGROUND + DATASETS -> Value.DATASETS + DATASET -> Value.DATASET + PROMPTS -> Value.PROMPTS + TOOLS -> Value.TOOLS + SCORERS -> Value.SCORERS + LOGS -> Value.LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PROJECTS -> Known.PROJECTS + EXPERIMENTS -> Known.EXPERIMENTS + EXPERIMENT -> Known.EXPERIMENT + PLAYGROUNDS -> Known.PLAYGROUNDS + PLAYGROUND -> Known.PLAYGROUND + DATASETS -> Known.DATASETS + DATASET -> Known.DATASET + PROMPTS -> Known.PROMPTS + TOOLS -> Known.TOOLS + SCORERS -> Known.SCORERS + LOGS -> Known.LOGS + else -> throw BraintrustInvalidDataException("Unknown ViewType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ViewType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is View && + id == other.id && + name == other.name && + objectId == other.objectId && + objectType == other.objectType && + viewType == other.viewType && + created == other.created && + deletedAt == other.deletedAt && + options == other.options && + userId == other.userId && + viewData == other.viewData && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + name, + objectId, + objectType, + viewType, + created, + deletedAt, + options, + userId, + viewData, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "View{id=$id, name=$name, objectId=$objectId, objectType=$objectType, viewType=$viewType, created=$created, deletedAt=$deletedAt, options=$options, userId=$userId, viewData=$viewData, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..29b4d710 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewCreateParams.kt @@ -0,0 +1,1126 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.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.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 + +/** + * Create a new view. If there is an existing view with the same name as the one specified in the + * request, will return the existing view unmodified + */ +class ViewCreateParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the view + * + * @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 = body.name() + + /** + * 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 = body.objectId() + + /** + * 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 = body.objectType() + + /** + * 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 = body.viewType() + + /** + * 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 = body.deletedAt() + + /** + * 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 = body.options() + + /** + * Identifies the user who created the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = body.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 = body.viewData() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + /** + * Returns the raw JSON value of [viewType]. + * + * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _viewType(): JsonField = body._viewType() + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _deletedAt(): JsonField = body._deletedAt() + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _options(): JsonField = body._options() + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _userId(): JsonField = body._userId() + + /** + * Returns the raw JSON value of [viewData]. + * + * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _viewData(): JsonField = body._viewData() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewCreateParams]. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewCreateParams]. */ + 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(viewCreateParams: ViewCreateParams) = apply { + body = viewCreateParams.body.toBuilder() + additionalHeaders = viewCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = viewCreateParams.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] + * - [viewType] + * - [deletedAt] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the view */ + 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 view applies to */ + 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 object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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 { 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()) + + /** + * 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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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) } + + 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 [ViewCreateParams]. + * + * 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(): ViewCreateParams = + ViewCreateParams(body.build(), additionalHeaders.build(), additionalQueryParams.build()) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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(), + ) + + /** + * Name of the view + * + * @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 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * Identifies the user who created the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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") + + /** + * 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 [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 + + /** + * 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 + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = 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 + + /** + * 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 + + @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() + } + + /** 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 + } + + /** 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 } + + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { + this.deletedAt = deletedAt + } + + /** Options for the view in the app */ + fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) + + /** + * 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 } + + /** Identifies the user who created the view */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + /** The view definition */ + fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) + + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + 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 a 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 (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 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + objectId, + objectType, + viewType, + deletedAt, + options, + userId, + viewData, + additionalProperties, + ) + } + + 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. */ + class ViewType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROJECTS = of("projects") + + @JvmField val EXPERIMENTS = of("experiments") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val PLAYGROUNDS = of("playgrounds") + + @JvmField val PLAYGROUND = of("playground") + + @JvmField val DATASETS = of("datasets") + + @JvmField val DATASET = of("dataset") + + @JvmField val PROMPTS = of("prompts") + + @JvmField val TOOLS = of("tools") + + @JvmField val SCORERS = of("scorers") + + @JvmField val LOGS = of("logs") + + @JvmStatic fun of(value: String) = ViewType(JsonField.of(value)) + } + + /** An enum containing [ViewType]'s known values. */ + enum class Known { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + } + + /** + * An enum containing [ViewType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ViewType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + /** An enum member indicating that [ViewType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROJECTS -> Value.PROJECTS + EXPERIMENTS -> Value.EXPERIMENTS + EXPERIMENT -> Value.EXPERIMENT + PLAYGROUNDS -> Value.PLAYGROUNDS + PLAYGROUND -> Value.PLAYGROUND + DATASETS -> Value.DATASETS + DATASET -> Value.DATASET + PROMPTS -> Value.PROMPTS + TOOLS -> Value.TOOLS + SCORERS -> Value.SCORERS + LOGS -> Value.LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PROJECTS -> Known.PROJECTS + EXPERIMENTS -> Known.EXPERIMENTS + EXPERIMENT -> Known.EXPERIMENT + PLAYGROUNDS -> Known.PLAYGROUNDS + PLAYGROUND -> Known.PLAYGROUND + DATASETS -> Known.DATASETS + DATASET -> Known.DATASET + PROMPTS -> Known.PROMPTS + TOOLS -> Known.TOOLS + SCORERS -> Known.SCORERS + LOGS -> Known.LOGS + else -> throw BraintrustInvalidDataException("Unknown ViewType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ViewType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ViewCreateParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ViewCreateParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..1ad28233 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewData.kt @@ -0,0 +1,157 @@ +// 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.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 */ +class ViewData +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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 = search.getOptional("search") + + /** + * Returns the raw JSON value of [search]. + * + * Unlike [search], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("search") @ExcludeMissing fun _search(): JsonField = search + + @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 [ViewData]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewData]. */ + class Builder internal constructor() { + + private var search: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(viewData: ViewData) = apply { + search = viewData.search + additionalProperties = viewData.additionalProperties.toMutableMap() + } + + fun search(search: ViewDataSearch?) = search(JsonField.ofNullable(search)) + + /** Alias for calling [Builder.search] with `search.orElse(null)`. */ + fun search(search: Optional) = search(search.getOrNull()) + + /** + * Sets [Builder.search] to an arbitrary JSON value. + * + * You should usually call [Builder.search] with a well-typed [ViewDataSearch] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun search(search: JsonField) = apply { this.search = search } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ViewData]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is ViewData && + search == other.search && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(search, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ViewData{search=$search, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..100f0481 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDataSearch.kt @@ -0,0 +1,330 @@ +// 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.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 + +class ViewDataSearch +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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> = 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> = 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> = 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> = tag.getOptional("tag") + + /** + * Returns the raw JSON value of [filter]. + * + * Unlike [filter], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("filter") @ExcludeMissing fun _filter(): JsonField> = filter + + /** + * Returns the raw JSON value of [match]. + * + * Unlike [match], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("match") @ExcludeMissing fun _match(): JsonField> = match + + /** + * Returns the raw JSON value of [sort]. + * + * Unlike [sort], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("sort") @ExcludeMissing fun _sort(): JsonField> = sort + + /** + * Returns the raw JSON value of [tag]. + * + * Unlike [tag], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("tag") @ExcludeMissing fun _tag(): JsonField> = tag + + @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 [ViewDataSearch]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewDataSearch]. */ + class Builder internal constructor() { + + private var filter: JsonField>? = null + private var match: JsonField>? = null + private var sort: JsonField>? = null + private var tag: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(viewDataSearch: ViewDataSearch) = apply { + filter = viewDataSearch.filter.map { it.toMutableList() } + match = viewDataSearch.match.map { it.toMutableList() } + sort = viewDataSearch.sort.map { it.toMutableList() } + tag = viewDataSearch.tag.map { it.toMutableList() } + additionalProperties = viewDataSearch.additionalProperties.toMutableMap() + } + + fun filter(filter: List?) = filter(JsonField.ofNullable(filter)) + + /** Alias for calling [Builder.filter] with `filter.orElse(null)`. */ + fun filter(filter: Optional>) = filter(filter.getOrNull()) + + /** + * Sets [Builder.filter] to an arbitrary JSON value. + * + * You should usually call [Builder.filter] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun filter(filter: JsonField>) = apply { + this.filter = filter.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [Builder.filter]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addFilter(filter: JsonValue) = apply { + this.filter = + (this.filter ?: JsonField.of(mutableListOf())).also { + checkKnown("filter", it).add(filter) + } + } + + fun match(match: List?) = match(JsonField.ofNullable(match)) + + /** Alias for calling [Builder.match] with `match.orElse(null)`. */ + fun match(match: Optional>) = match(match.getOrNull()) + + /** + * Sets [Builder.match] to an arbitrary JSON value. + * + * You should usually call [Builder.match] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun match(match: JsonField>) = apply { + this.match = match.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [Builder.match]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addMatch(match: JsonValue) = apply { + this.match = + (this.match ?: JsonField.of(mutableListOf())).also { + checkKnown("match", it).add(match) + } + } + + fun sort(sort: List?) = sort(JsonField.ofNullable(sort)) + + /** Alias for calling [Builder.sort] with `sort.orElse(null)`. */ + fun sort(sort: Optional>) = sort(sort.getOrNull()) + + /** + * Sets [Builder.sort] to an arbitrary JSON value. + * + * You should usually call [Builder.sort] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun sort(sort: JsonField>) = apply { + this.sort = sort.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [Builder.sort]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addSort(sort: JsonValue) = apply { + this.sort = + (this.sort ?: JsonField.of(mutableListOf())).also { + checkKnown("sort", it).add(sort) + } + } + + fun tag(tag: List?) = tag(JsonField.ofNullable(tag)) + + /** Alias for calling [Builder.tag] with `tag.orElse(null)`. */ + fun tag(tag: Optional>) = tag(tag.getOrNull()) + + /** + * Sets [Builder.tag] to an arbitrary JSON value. + * + * You should usually call [Builder.tag] with a well-typed `List` value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun tag(tag: JsonField>) = apply { + this.tag = tag.map { it.toMutableList() } + } + + /** + * Adds a single [JsonValue] to [Builder.tag]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addTag(tag: JsonValue) = apply { + this.tag = + (this.tag ?: JsonField.of(mutableListOf())).also { checkKnown("tag", 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 [ViewDataSearch]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ViewDataSearch = + ViewDataSearch( + (filter ?: JsonMissing.of()).map { it.toImmutable() }, + (match ?: JsonMissing.of()).map { it.toImmutable() }, + (sort ?: JsonMissing.of()).map { it.toImmutable() }, + (tag ?: JsonMissing.of()).map { it.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 + } + + return other is ViewDataSearch && + filter == other.filter && + match == other.match && + sort == other.sort && + tag == other.tag && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(filter, match, sort, tag, additionalProperties) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ViewDataSearch{filter=$filter, match=$match, sort=$sort, tag=$tag, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..c675954c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewDeleteParams.kt @@ -0,0 +1,520 @@ +// 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.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.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 + +/** Delete a view object by its id */ +class ViewDeleteParams +private constructor( + private val viewId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** View id */ + fun viewId(): Optional = Optional.ofNullable(viewId) + + /** + * 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 = body.objectId() + + /** + * 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 = body.objectType() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewDeleteParams]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewDeleteParams]. */ + 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(viewDeleteParams: ViewDeleteParams) = apply { + viewId = viewDeleteParams.viewId + body = viewDeleteParams.body.toBuilder() + additionalHeaders = viewDeleteParams.additionalHeaders.toBuilder() + additionalQueryParams = viewDeleteParams.additionalQueryParams.toBuilder() + } + + /** View id */ + fun viewId(viewId: String?) = apply { this.viewId = viewId } + + /** Alias for calling [Builder.viewId] with `viewId.orElse(null)`. */ + fun viewId(viewId: Optional) = viewId(viewId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [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) } + + /** + * 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 object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(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 { body.objectType(objectType) } + + 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 [ViewDeleteParams]. + * + * 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(): ViewDeleteParams = + ViewDeleteParams( + viewId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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 other is Body && + objectId == other.objectId && + objectType == other.objectType && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash(objectId, objectType, additionalProperties) + } + + 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 + } + + return other is ViewDeleteParams && + viewId == other.viewId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(viewId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ViewDeleteParams{viewId=$viewId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..f4f062c2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPage.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPager +import com.braintrustdata.api.core.Page +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.blocking.ViewService +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** @see ViewService.list */ +class ViewListPage +private constructor( + private val service: ViewService, + private val params: ViewListParams, + private val response: ViewListPageResponse, +) : Page { + + /** + * Delegates to [ViewListPageResponse], but gracefully handles missing data. + * + * @see ViewListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ViewListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): ViewListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): ViewListParams = params + + /** The response that this page was parsed from. */ + fun response(): ViewListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewListPage]. */ + class Builder internal constructor() { + + private var service: ViewService? = null + private var params: ViewListParams? = null + private var response: ViewListPageResponse? = null + + @JvmSynthetic + internal fun from(viewListPage: ViewListPage) = apply { + service = viewListPage.service + params = viewListPage.params + response = viewListPage.response + } + + 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), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ViewListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + 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 new file mode 100755 index 00000000..a2cffbac --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageAsync.kt @@ -0,0 +1,138 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.AutoPagerAsync +import com.braintrustdata.api.core.PageAsync +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.services.async.ViewServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrNull + +/** @see ViewServiceAsync.list */ +class ViewListPageAsync +private constructor( + private val service: ViewServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: ViewListParams, + private val response: ViewListPageResponse, +) : PageAsync { + + /** + * Delegates to [ViewListPageResponse], but gracefully handles missing data. + * + * @see ViewListPageResponse.objects + */ + fun objects(): List = + response._objects().getOptional("objects").getOrNull() ?: emptyList() + + override fun items(): List = objects() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): ViewListParams = + if (params.endingBefore().isPresent) { + params.toBuilder().endingBefore(items().first()._id().getOptional("id")).build() + } else { + params.toBuilder().startingAfter(items().last()._id().getOptional("id")).build() + } + + override fun nextPage(): CompletableFuture = service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): ViewListParams = params + + /** The response that this page was parsed from. */ + fun response(): ViewListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewListPageAsync]. */ + class Builder internal constructor() { + + private var service: ViewServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: ViewListParams? = null + private var response: ViewListPageResponse? = null + + @JvmSynthetic + internal fun from(viewListPageAsync: ViewListPageAsync) = apply { + service = viewListPageAsync.service + streamHandlerExecutor = viewListPageAsync.streamHandlerExecutor + params = viewListPageAsync.params + response = viewListPageAsync.response + } + + fun service(service: ViewServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** 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() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): ViewListPageAsync = + ViewListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ViewListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "ViewListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, 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..b44c4997 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListPageResponse.kt @@ -0,0 +1,193 @@ +// 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 +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +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 other is ViewListPageResponse && + objects == other.objects && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(objects, additionalProperties) } + + 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 new file mode 100755 index 00000000..3577873a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewListParams.kt @@ -0,0 +1,442 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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.core.toImmutable +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** + * List out all views. The views are sorted by creation date, with the most recently-created views + * coming first + */ +class ViewListParams +private constructor( + private val objectId: String, + private val objectType: AclObjectType, + private val endingBefore: String?, + private val ids: Ids?, + private val limit: Long?, + private val startingAfter: String?, + private val viewName: String?, + private val viewType: ViewType?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** The id of the object the ACL applies to */ + fun objectId(): String = objectId + + /** The object type that the ACL applies to */ + fun objectType(): AclObjectType = objectType + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(): Optional = Optional.ofNullable(endingBefore) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, include + * the query param multiple times + */ + fun ids(): Optional = Optional.ofNullable(ids) + + /** Limit the number of objects to return */ + fun limit(): Optional = Optional.ofNullable(limit) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` + * and `ending_before` + */ + fun startingAfter(): Optional = Optional.ofNullable(startingAfter) + + /** Name of the view to search for */ + fun viewName(): Optional = Optional.ofNullable(viewName) + + /** Type of table that the view corresponds to. */ + fun viewType(): Optional = Optional.ofNullable(viewType) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewListParams]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewListParams]. */ + class Builder internal constructor() { + + private var objectId: String? = null + private var objectType: AclObjectType? = null + private var endingBefore: String? = null + private var ids: Ids? = null + private var limit: Long? = null + private var startingAfter: String? = null + private var viewName: String? = null + private var viewType: ViewType? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(viewListParams: ViewListParams) = apply { + objectId = viewListParams.objectId + objectType = viewListParams.objectType + endingBefore = viewListParams.endingBefore + ids = viewListParams.ids + limit = viewListParams.limit + startingAfter = viewListParams.startingAfter + viewName = viewListParams.viewName + viewType = viewListParams.viewType + additionalHeaders = viewListParams.additionalHeaders.toBuilder() + additionalQueryParams = viewListParams.additionalQueryParams.toBuilder() + } + + /** The id of the object the ACL applies to */ + fun objectId(objectId: String) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { this.objectType = objectType } + + /** + * Pagination cursor id. + * + * For example, if the initial item in the last page you fetched had an id of `foo`, pass + * `ending_before=foo` to fetch the previous page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun endingBefore(endingBefore: String?) = apply { this.endingBefore = endingBefore } + + /** Alias for calling [Builder.endingBefore] with `endingBefore.orElse(null)`. */ + fun endingBefore(endingBefore: Optional) = endingBefore(endingBefore.getOrNull()) + + /** + * Filter search results to a particular set of object IDs. To specify a list of IDs, + * include the query param multiple times + */ + fun ids(ids: Ids?) = apply { this.ids = ids } + + /** Alias for calling [Builder.ids] with `ids.orElse(null)`. */ + fun ids(ids: Optional) = ids(ids.getOrNull()) + + /** Alias for calling [ids] with `Ids.ofString(string)`. */ + fun ids(string: String) = ids(Ids.ofString(string)) + + /** Alias for calling [ids] with `Ids.ofStrings(strings)`. */ + fun idsOfStrings(strings: List) = ids(Ids.ofStrings(strings)) + + /** Limit the number of objects to return */ + fun limit(limit: Long?) = apply { this.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()) + + /** + * Pagination cursor id. + * + * For example, if the final item in the last page you fetched had an id of `foo`, pass + * `starting_after=foo` to fetch the next page. Note: you may only pass one of + * `starting_after` and `ending_before` + */ + fun startingAfter(startingAfter: String?) = apply { this.startingAfter = startingAfter } + + /** Alias for calling [Builder.startingAfter] with `startingAfter.orElse(null)`. */ + fun startingAfter(startingAfter: Optional) = + startingAfter(startingAfter.getOrNull()) + + /** Name of the view to search for */ + fun viewName(viewName: String?) = apply { this.viewName = viewName } + + /** Alias for calling [Builder.viewName] with `viewName.orElse(null)`. */ + fun viewName(viewName: Optional) = viewName(viewName.getOrNull()) + + /** Type of table that the view corresponds to. */ + fun viewType(viewType: ViewType?) = apply { this.viewType = viewType } + + /** 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) + } + + 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 [ViewListParams]. + * + * 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(): ViewListParams = + ViewListParams( + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + endingBefore, + ids, + limit, + startingAfter, + viewName, + viewType, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + */ + class Ids + private constructor( + private val string: String? = null, + private val strings: List? = null, + ) { + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun accept(visitor: Visitor): T = + when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> throw IllegalStateException("Invalid Ids") + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Ids && string == other.string && strings == other.strings + } + + override fun hashCode(): Int = Objects.hash(string, strings) + + override fun toString(): String = + when { + string != null -> "Ids{string=$string}" + strings != null -> "Ids{strings=$strings}" + else -> throw IllegalStateException("Invalid Ids") + } + + companion object { + + @JvmStatic fun ofString(string: String) = Ids(string = string) + + @JvmStatic fun ofStrings(strings: List) = Ids(strings = strings.toImmutable()) + } + + /** An interface that defines how to map each variant of [Ids] to a value of type [T]. */ + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ViewListParams && + objectId == other.objectId && + objectType == other.objectType && + endingBefore == other.endingBefore && + ids == other.ids && + limit == other.limit && + startingAfter == other.startingAfter && + viewName == other.viewName && + viewType == other.viewType && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + objectId, + objectType, + endingBefore, + ids, + limit, + startingAfter, + viewName, + viewType, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "ViewListParams{objectId=$objectId, objectType=$objectType, endingBefore=$endingBefore, ids=$ids, limit=$limit, startingAfter=$startingAfter, viewName=$viewName, viewType=$viewType, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..6dbe6150 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewOptions.kt @@ -0,0 +1,591 @@ +// 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.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 */ +class ViewOptions +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + 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> = 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 = 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 = + 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 = 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 = 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 = rowHeight.getOptional("rowHeight") + + /** + * Returns the raw JSON value of [columnOrder]. + * + * Unlike [columnOrder], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("columnOrder") + @ExcludeMissing + fun _columnOrder(): JsonField> = columnOrder + + /** + * Returns the raw JSON value of [columnSizing]. + * + * Unlike [columnSizing], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("columnSizing") + @ExcludeMissing + fun _columnSizing(): JsonField = columnSizing + + /** + * Returns the raw JSON value of [columnVisibility]. + * + * Unlike [columnVisibility], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("columnVisibility") + @ExcludeMissing + fun _columnVisibility(): JsonField = columnVisibility + + /** + * Returns the raw JSON value of [grouping]. + * + * Unlike [grouping], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("grouping") @ExcludeMissing fun _grouping(): JsonField = grouping + + /** + * Returns the raw JSON value of [layout]. + * + * Unlike [layout], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("layout") @ExcludeMissing fun _layout(): JsonField = layout + + /** + * Returns the raw JSON value of [rowHeight]. + * + * Unlike [rowHeight], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("rowHeight") @ExcludeMissing fun _rowHeight(): JsonField = rowHeight + + @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 [ViewOptions]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewOptions]. */ + class Builder internal constructor() { + + private var columnOrder: JsonField>? = null + private var columnSizing: JsonField = JsonMissing.of() + private var columnVisibility: JsonField = JsonMissing.of() + private var grouping: JsonField = JsonMissing.of() + private var layout: JsonField = JsonMissing.of() + private var rowHeight: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(viewOptions: ViewOptions) = apply { + columnOrder = viewOptions.columnOrder.map { it.toMutableList() } + columnSizing = viewOptions.columnSizing + columnVisibility = viewOptions.columnVisibility + grouping = viewOptions.grouping + layout = viewOptions.layout + rowHeight = viewOptions.rowHeight + additionalProperties = viewOptions.additionalProperties.toMutableMap() + } + + fun columnOrder(columnOrder: List?) = columnOrder(JsonField.ofNullable(columnOrder)) + + /** Alias for calling [Builder.columnOrder] with `columnOrder.orElse(null)`. */ + fun columnOrder(columnOrder: Optional>) = columnOrder(columnOrder.getOrNull()) + + /** + * Sets [Builder.columnOrder] to an arbitrary JSON value. + * + * You should usually call [Builder.columnOrder] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun columnOrder(columnOrder: JsonField>) = apply { + this.columnOrder = columnOrder.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.columnOrder]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addColumnOrder(columnOrder: String) = apply { + this.columnOrder = + (this.columnOrder ?: JsonField.of(mutableListOf())).also { + checkKnown("columnOrder", it).add(columnOrder) + } + } + + fun columnSizing(columnSizing: ColumnSizing?) = + columnSizing(JsonField.ofNullable(columnSizing)) + + /** Alias for calling [Builder.columnSizing] with `columnSizing.orElse(null)`. */ + fun columnSizing(columnSizing: Optional) = + columnSizing(columnSizing.getOrNull()) + + /** + * Sets [Builder.columnSizing] to an arbitrary JSON value. + * + * You should usually call [Builder.columnSizing] with a well-typed [ColumnSizing] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun columnSizing(columnSizing: JsonField) = apply { + this.columnSizing = columnSizing + } + + fun columnVisibility(columnVisibility: ColumnVisibility?) = + columnVisibility(JsonField.ofNullable(columnVisibility)) + + /** Alias for calling [Builder.columnVisibility] with `columnVisibility.orElse(null)`. */ + fun columnVisibility(columnVisibility: Optional) = + columnVisibility(columnVisibility.getOrNull()) + + /** + * Sets [Builder.columnVisibility] to an arbitrary JSON value. + * + * You should usually call [Builder.columnVisibility] with a well-typed [ColumnVisibility] + * value instead. This method is primarily for setting the field to an undocumented or not + * yet supported value. + */ + fun columnVisibility(columnVisibility: JsonField) = apply { + this.columnVisibility = columnVisibility + } + + fun grouping(grouping: String?) = grouping(JsonField.ofNullable(grouping)) + + /** Alias for calling [Builder.grouping] with `grouping.orElse(null)`. */ + fun grouping(grouping: Optional) = grouping(grouping.getOrNull()) + + /** + * Sets [Builder.grouping] to an arbitrary JSON value. + * + * You should usually call [Builder.grouping] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun grouping(grouping: JsonField) = apply { this.grouping = grouping } + + fun layout(layout: String?) = layout(JsonField.ofNullable(layout)) + + /** Alias for calling [Builder.layout] with `layout.orElse(null)`. */ + fun layout(layout: Optional) = layout(layout.getOrNull()) + + /** + * Sets [Builder.layout] to an arbitrary JSON value. + * + * You should usually call [Builder.layout] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun layout(layout: JsonField) = apply { this.layout = layout } + + fun rowHeight(rowHeight: String?) = rowHeight(JsonField.ofNullable(rowHeight)) + + /** Alias for calling [Builder.rowHeight] with `rowHeight.orElse(null)`. */ + fun rowHeight(rowHeight: Optional) = rowHeight(rowHeight.getOrNull()) + + /** + * Sets [Builder.rowHeight] to an arbitrary JSON value. + * + * You should usually call [Builder.rowHeight] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun rowHeight(rowHeight: JsonField) = apply { this.rowHeight = rowHeight } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [ViewOptions]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): ViewOptions = + ViewOptions( + (columnOrder ?: JsonMissing.of()).map { it.toImmutable() }, + columnSizing, + columnVisibility, + grouping, + layout, + rowHeight, + additionalProperties.toMutableMap(), + ) + } + + 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( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ColumnSizing]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ColumnSizing]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(columnSizing: ColumnSizing) = apply { + additionalProperties = columnSizing.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 [ColumnSizing]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is ColumnSizing && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ColumnSizing{additionalProperties=$additionalProperties}" + } + + class ColumnVisibility + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [ColumnVisibility]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ColumnVisibility]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(columnVisibility: ColumnVisibility) = apply { + additionalProperties = columnVisibility.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 [ColumnVisibility]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + 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 + } + + return other is ColumnVisibility && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "ColumnVisibility{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ViewOptions && + columnOrder == other.columnOrder && + columnSizing == other.columnSizing && + columnVisibility == other.columnVisibility && + grouping == other.grouping && + layout == other.layout && + rowHeight == other.rowHeight && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + columnOrder, + columnSizing, + columnVisibility, + grouping, + layout, + rowHeight, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ViewOptions{columnOrder=$columnOrder, columnSizing=$columnSizing, columnVisibility=$columnVisibility, grouping=$grouping, layout=$layout, rowHeight=$rowHeight, additionalProperties=$additionalProperties}" +} 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 new file mode 100755 index 00000000..db31cf9e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewReplaceParams.kt @@ -0,0 +1,1130 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.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.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 + +/** + * Create or replace view. If there is an existing view with the same name as the one specified in + * the request, will replace the existing view with the provided fields + */ +class ViewReplaceParams +private constructor( + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** + * Name of the view + * + * @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 = body.name() + + /** + * 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 = body.objectId() + + /** + * 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 = body.objectType() + + /** + * 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 = body.viewType() + + /** + * 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 = body.deletedAt() + + /** + * 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 = body.options() + + /** + * Identifies the user who created the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = body.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 = body.viewData() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + /** + * Returns the raw JSON value of [viewType]. + * + * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _viewType(): JsonField = body._viewType() + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _deletedAt(): JsonField = body._deletedAt() + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _options(): JsonField = body._options() + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _userId(): JsonField = body._userId() + + /** + * Returns the raw JSON value of [viewData]. + * + * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _viewData(): JsonField = body._viewData() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewReplaceParams]. + * + * The following fields are required: + * ```java + * .name() + * .objectId() + * .objectType() + * .viewType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewReplaceParams]. */ + 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(viewReplaceParams: ViewReplaceParams) = apply { + body = viewReplaceParams.body.toBuilder() + additionalHeaders = viewReplaceParams.additionalHeaders.toBuilder() + additionalQueryParams = viewReplaceParams.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] + * - [viewType] + * - [deletedAt] + * - etc. + */ + fun body(body: Body) = apply { this.body = body.toBuilder() } + + /** Name of the view */ + 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 view applies to */ + 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 object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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 { 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()) + + /** + * 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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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) } + + 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 [ViewReplaceParams]. + * + * 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(): ViewReplaceParams = + ViewReplaceParams( + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _body(): Body = body + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = additionalQueryParams + + class Body + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + private constructor( + private val 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(), + ) + + /** + * Name of the view + * + * @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 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") + + /** + * 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") + + /** + * 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") + + /** + * 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") + + /** + * Identifies the user who created the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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") + + /** + * 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 [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 + + /** + * 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 + + /** + * Returns the raw JSON value of [deletedAt]. + * + * Unlike [deletedAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("deleted_at") + @ExcludeMissing + fun _deletedAt(): JsonField = deletedAt + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = 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 + + /** + * 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 + + @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() + } + + /** 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 + } + + /** 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 } + + /** Date of role deletion, or null if the role is still active */ + fun deletedAt(deletedAt: OffsetDateTime?) = deletedAt(JsonField.ofNullable(deletedAt)) + + /** Alias for calling [Builder.deletedAt] with `deletedAt.orElse(null)`. */ + fun deletedAt(deletedAt: Optional) = deletedAt(deletedAt.getOrNull()) + + /** + * Sets [Builder.deletedAt] to an arbitrary JSON value. + * + * You should usually call [Builder.deletedAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun deletedAt(deletedAt: JsonField) = apply { + this.deletedAt = deletedAt + } + + /** Options for the view in the app */ + fun options(options: ViewOptions?) = options(JsonField.ofNullable(options)) + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) + + /** + * 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 } + + /** Identifies the user who created the view */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + /** The view definition */ + fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) + + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + + /** + * 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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() + * .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(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + 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 a 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 (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 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + name, + objectId, + objectType, + viewType, + deletedAt, + options, + userId, + viewData, + additionalProperties, + ) + } + + 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. */ + class ViewType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROJECTS = of("projects") + + @JvmField val EXPERIMENTS = of("experiments") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val PLAYGROUNDS = of("playgrounds") + + @JvmField val PLAYGROUND = of("playground") + + @JvmField val DATASETS = of("datasets") + + @JvmField val DATASET = of("dataset") + + @JvmField val PROMPTS = of("prompts") + + @JvmField val TOOLS = of("tools") + + @JvmField val SCORERS = of("scorers") + + @JvmField val LOGS = of("logs") + + @JvmStatic fun of(value: String) = ViewType(JsonField.of(value)) + } + + /** An enum containing [ViewType]'s known values. */ + enum class Known { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + } + + /** + * An enum containing [ViewType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ViewType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + /** An enum member indicating that [ViewType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROJECTS -> Value.PROJECTS + EXPERIMENTS -> Value.EXPERIMENTS + EXPERIMENT -> Value.EXPERIMENT + PLAYGROUNDS -> Value.PLAYGROUNDS + PLAYGROUND -> Value.PLAYGROUND + DATASETS -> Value.DATASETS + DATASET -> Value.DATASET + PROMPTS -> Value.PROMPTS + TOOLS -> Value.TOOLS + SCORERS -> Value.SCORERS + LOGS -> Value.LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PROJECTS -> Known.PROJECTS + EXPERIMENTS -> Known.EXPERIMENTS + EXPERIMENT -> Known.EXPERIMENT + PLAYGROUNDS -> Known.PLAYGROUNDS + PLAYGROUND -> Known.PLAYGROUND + DATASETS -> Known.DATASETS + DATASET -> Known.DATASET + PROMPTS -> Known.PROMPTS + TOOLS -> Known.TOOLS + SCORERS -> Known.SCORERS + LOGS -> Known.LOGS + else -> throw BraintrustInvalidDataException("Unknown ViewType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ViewType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ViewReplaceParams && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = Objects.hash(body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ViewReplaceParams{body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100755 index 00000000..d61fa274 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewRetrieveParams.kt @@ -0,0 +1,240 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +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 java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get a view object by its id */ +class ViewRetrieveParams +private constructor( + private val viewId: String?, + private val objectId: String, + private val objectType: AclObjectType, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** View id */ + fun viewId(): Optional = Optional.ofNullable(viewId) + + /** The id of the object the ACL applies to */ + fun objectId(): String = objectId + + /** The object type that the ACL applies to */ + fun objectType(): AclObjectType = objectType + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewRetrieveParams]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [ViewRetrieveParams]. */ + class Builder internal constructor() { + + private var viewId: String? = null + private var objectId: String? = null + private var objectType: AclObjectType? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(viewRetrieveParams: ViewRetrieveParams) = apply { + viewId = viewRetrieveParams.viewId + objectId = viewRetrieveParams.objectId + objectType = viewRetrieveParams.objectType + additionalHeaders = viewRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = viewRetrieveParams.additionalQueryParams.toBuilder() + } + + /** View id */ + fun viewId(viewId: String?) = apply { this.viewId = viewId } + + /** Alias for calling [Builder.viewId] with `viewId.orElse(null)`. */ + fun viewId(viewId: Optional) = viewId(viewId.getOrNull()) + + /** The id of the object the ACL applies to */ + fun objectId(objectId: String) = apply { this.objectId = objectId } + + /** The object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { this.objectType = objectType } + + 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 [ViewRetrieveParams]. + * + * 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(): ViewRetrieveParams = + ViewRetrieveParams( + viewId, + checkRequired("objectId", objectId), + checkRequired("objectType", objectType), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + } + + return other is ViewRetrieveParams && + viewId == other.viewId && + objectId == other.objectId && + objectType == other.objectType && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(viewId, objectId, objectType, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ViewRetrieveParams{viewId=$viewId, objectId=$objectId, objectType=$objectType, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} 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 new file mode 100644 index 00000000..6744a88f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewType.kt @@ -0,0 +1,186 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +import com.braintrustdata.api.core.JsonField +import com.braintrustdata.api.errors.BraintrustInvalidDataException +import com.fasterxml.jackson.annotation.JsonCreator + +/** Type of table that the view corresponds to. */ +class ViewType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't match + * any known member, and you want to know that value. For example, if the SDK is on an older + * version than the API, then the API may respond with new members that the SDK is unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROJECTS = of("projects") + + @JvmField val EXPERIMENTS = of("experiments") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val PLAYGROUNDS = of("playgrounds") + + @JvmField val PLAYGROUND = of("playground") + + @JvmField val DATASETS = of("datasets") + + @JvmField val DATASET = of("dataset") + + @JvmField val PROMPTS = of("prompts") + + @JvmField val TOOLS = of("tools") + + @JvmField val SCORERS = of("scorers") + + @JvmField val LOGS = of("logs") + + @JvmStatic fun of(value: String) = ViewType(JsonField.of(value)) + } + + /** An enum containing [ViewType]'s known values. */ + enum class Known { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + } + + /** + * An enum containing [ViewType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ViewType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the SDK + * is on an older version than the API, then the API may respond with new members that the SDK + * is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + /** An enum member indicating that [ViewType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] if + * the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want to + * throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROJECTS -> Value.PROJECTS + EXPERIMENTS -> Value.EXPERIMENTS + EXPERIMENT -> Value.EXPERIMENT + PLAYGROUNDS -> Value.PLAYGROUNDS + PLAYGROUND -> Value.PLAYGROUND + DATASETS -> Value.DATASETS + DATASET -> Value.DATASET + PROMPTS -> Value.PROMPTS + TOOLS -> Value.TOOLS + SCORERS -> Value.SCORERS + LOGS -> Value.LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't want + * to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PROJECTS -> Known.PROJECTS + EXPERIMENTS -> Known.EXPERIMENTS + EXPERIMENT -> Known.EXPERIMENT + PLAYGROUNDS -> Known.PLAYGROUNDS + PLAYGROUND -> Known.PLAYGROUND + DATASETS -> Known.DATASETS + DATASET -> Known.DATASET + PROMPTS -> Known.PROMPTS + TOOLS -> Known.TOOLS + SCORERS -> Known.SCORERS + LOGS -> Known.LOGS + else -> throw BraintrustInvalidDataException("Unknown ViewType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging and + * generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { 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 + } + + return other is ViewType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewUpdateParams.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewUpdateParams.kt new file mode 100755 index 00000000..45655990 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/models/ViewUpdateParams.kt @@ -0,0 +1,1064 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.Enum +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.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.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 + +/** + * Partially update a view object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields or + * setting them to null. + */ +class ViewUpdateParams +private constructor( + private val viewId: String?, + private val body: Body, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + /** View id */ + fun viewId(): Optional = Optional.ofNullable(viewId) + + /** + * 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 = body.objectId() + + /** + * 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 = body.objectType() + + /** + * Name of the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun name(): Optional = body.name() + + /** + * 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 = body.options() + + /** + * Identifies the user who created the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun userId(): Optional = body.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 = body.viewData() + + /** + * 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 = body.viewType() + + /** + * Returns the raw JSON value of [objectId]. + * + * Unlike [objectId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectId(): JsonField = body._objectId() + + /** + * Returns the raw JSON value of [objectType]. + * + * Unlike [objectType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _objectType(): JsonField = body._objectType() + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _name(): JsonField = body._name() + + /** + * Returns the raw JSON value of [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _options(): JsonField = body._options() + + /** + * Returns the raw JSON value of [userId]. + * + * Unlike [userId], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _userId(): JsonField = body._userId() + + /** + * Returns the raw JSON value of [viewData]. + * + * Unlike [viewData], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _viewData(): JsonField = body._viewData() + + /** + * Returns the raw JSON value of [viewType]. + * + * Unlike [viewType], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _viewType(): JsonField = body._viewType() + + fun _additionalBodyProperties(): Map = body._additionalProperties() + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [ViewUpdateParams]. + * + * The following fields are required: + * ```java + * .objectId() + * .objectType() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** 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() + } + + /** View id */ + fun viewId(viewId: String?) = apply { this.viewId = viewId } + + /** Alias for calling [Builder.viewId] with `viewId.orElse(null)`. */ + fun viewId(viewId: Optional) = viewId(viewId.getOrNull()) + + /** + * Sets the entire request body. + * + * This is generally only useful if you are already constructing the body separately. + * Otherwise, it's more convenient to use the top-level setters instead: + * - [objectId] + * - [objectType] + * - [name] + * - [options] + * - [userId] + * - etc. + */ + 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) } + + /** + * 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 object type that the ACL applies to */ + fun objectType(objectType: AclObjectType) = apply { body.objectType(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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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 { 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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) } + + /** 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()) + + /** + * 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) } + + 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 [ViewUpdateParams]. + * + * 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(): ViewUpdateParams = + ViewUpdateParams( + viewId, + body.build(), + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + 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 + @JsonCreator(mode = JsonCreator.Mode.DISABLED) + 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()) + + /** + * 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") + + /** + * Name of the view + * + * @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") + + /** + * 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") + + /** + * Identifies the user who created the view + * + * @throws BraintrustInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun userId(): Optional = userId.getOptional("user_id") + + /** + * 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") + + /** + * 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") + + /** + * 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 + + /** + * 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 [options]. + * + * Unlike [options], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("options") @ExcludeMissing fun _options(): JsonField = 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 + + /** + * 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 + + /** + * 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 + + @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 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 + } + + /** 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)) + + /** Alias for calling [Builder.options] with `options.orElse(null)`. */ + fun options(options: Optional) = options(options.getOrNull()) + + /** + * 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 } + + /** Identifies the user who created the view */ + fun userId(userId: String?) = userId(JsonField.ofNullable(userId)) + + /** Alias for calling [Builder.userId] with `userId.orElse(null)`. */ + fun userId(userId: Optional) = userId(userId.getOrNull()) + + /** + * Sets [Builder.userId] to an arbitrary JSON value. + * + * You should usually call [Builder.userId] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun userId(userId: JsonField) = apply { this.userId = userId } + + /** The view definition */ + fun viewData(viewData: ViewData?) = viewData(JsonField.ofNullable(viewData)) + + /** Alias for calling [Builder.viewData] with `viewData.orElse(null)`. */ + fun viewData(viewData: Optional) = viewData(viewData.getOrNull()) + + /** + * 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 } + + /** 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 additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.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), + name, + options, + userId, + viewData, + viewType, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): Body = apply { + if (validated) { + return@apply + } + + 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 a 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 (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 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 + } + + private val hashCode: Int by lazy { + Objects.hash( + objectId, + objectType, + name, + options, + userId, + viewData, + viewType, + additionalProperties, + ) + } + + 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. */ + class ViewType @JsonCreator private constructor(private val value: JsonField) : Enum { + + /** + * Returns this class instance's raw value. + * + * This is usually only useful if this instance was deserialized from data that doesn't + * match any known member, and you want to know that value. For example, if the SDK is on an + * older version than the API, then the API may respond with new members that the SDK is + * unaware of. + */ + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PROJECTS = of("projects") + + @JvmField val EXPERIMENTS = of("experiments") + + @JvmField val EXPERIMENT = of("experiment") + + @JvmField val PLAYGROUNDS = of("playgrounds") + + @JvmField val PLAYGROUND = of("playground") + + @JvmField val DATASETS = of("datasets") + + @JvmField val DATASET = of("dataset") + + @JvmField val PROMPTS = of("prompts") + + @JvmField val TOOLS = of("tools") + + @JvmField val SCORERS = of("scorers") + + @JvmField val LOGS = of("logs") + + @JvmStatic fun of(value: String) = ViewType(JsonField.of(value)) + } + + /** An enum containing [ViewType]'s known values. */ + enum class Known { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + } + + /** + * An enum containing [ViewType]'s known values, as well as an [_UNKNOWN] member. + * + * An instance of [ViewType] can contain an unknown value in a couple of cases: + * - It was deserialized from data that doesn't match any known member. For example, if the + * SDK is on an older version than the API, then the API may respond with new members that + * the SDK is unaware of. + * - It was constructed with an arbitrary value using the [of] method. + */ + enum class Value { + PROJECTS, + EXPERIMENTS, + EXPERIMENT, + PLAYGROUNDS, + PLAYGROUND, + DATASETS, + DATASET, + PROMPTS, + TOOLS, + SCORERS, + LOGS, + /** An enum member indicating that [ViewType] was instantiated with an unknown value. */ + _UNKNOWN, + } + + /** + * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN] + * if the class was instantiated with an unknown value. + * + * Use the [known] method instead if you're certain the value is always known or if you want + * to throw for the unknown case. + */ + fun value(): Value = + when (this) { + PROJECTS -> Value.PROJECTS + EXPERIMENTS -> Value.EXPERIMENTS + EXPERIMENT -> Value.EXPERIMENT + PLAYGROUNDS -> Value.PLAYGROUNDS + PLAYGROUND -> Value.PLAYGROUND + DATASETS -> Value.DATASETS + DATASET -> Value.DATASET + PROMPTS -> Value.PROMPTS + TOOLS -> Value.TOOLS + SCORERS -> Value.SCORERS + LOGS -> Value.LOGS + else -> Value._UNKNOWN + } + + /** + * Returns an enum member corresponding to this class instance's value. + * + * Use the [value] method instead if you're uncertain the value is always known and don't + * want to throw for the unknown case. + * + * @throws BraintrustInvalidDataException if this class instance's value is a not a known + * member. + */ + fun known(): Known = + when (this) { + PROJECTS -> Known.PROJECTS + EXPERIMENTS -> Known.EXPERIMENTS + EXPERIMENT -> Known.EXPERIMENT + PLAYGROUNDS -> Known.PLAYGROUNDS + PLAYGROUND -> Known.PLAYGROUND + DATASETS -> Known.DATASETS + DATASET -> Known.DATASET + PROMPTS -> Known.PROMPTS + TOOLS -> Known.TOOLS + SCORERS -> Known.SCORERS + LOGS -> Known.LOGS + else -> throw BraintrustInvalidDataException("Unknown ViewType: $value") + } + + /** + * Returns this class instance's primitive wire representation. + * + * This differs from the [toString] method because that method is primarily for debugging + * and generally doesn't throw. + * + * @throws BraintrustInvalidDataException if this class instance's value does not have the + * expected primitive type. + */ + fun asString(): String = + _value().asString().orElseThrow { + 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 + } + + return other is ViewType && value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ViewUpdateParams && + viewId == other.viewId && + body == other.body && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash(viewId, body, additionalHeaders, additionalQueryParams) + + override fun toString() = + "ViewUpdateParams{viewId=$viewId, body=$body, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/Handlers.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/Handlers.kt deleted file mode 100644 index c698a776..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/Handlers.kt +++ /dev/null @@ -1,130 +0,0 @@ -@file:JvmName("Handlers") - -package com.braintrustdata.api.services - -import com.braintrustdata.api.core.http.BinaryResponseContent -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.BraintrustException -import com.braintrustdata.api.errors.InternalServerException -import com.braintrustdata.api.errors.NotFoundException -import com.braintrustdata.api.errors.PermissionDeniedException -import com.braintrustdata.api.errors.RateLimitException -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 com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import java.io.InputStream -import java.io.OutputStream - -@JvmSynthetic internal fun emptyHandler(): Handler = EmptyHandler - -private object EmptyHandler : Handler { - override fun handle(response: HttpResponse): Void? = null -} - -@JvmSynthetic internal fun stringHandler(): Handler = StringHandler - -@JvmSynthetic internal fun binaryHandler(): Handler = BinaryHandler - -private object StringHandler : Handler { - override fun handle(response: HttpResponse): String { - return response.body().readBytes().toString(Charsets.UTF_8) - } -} - -private object BinaryHandler : Handler { - override fun handle(response: HttpResponse): BinaryResponseContent { - return BinaryResponseContentImpl(response) - } -} - -@JvmSynthetic -internal inline fun jsonHandler(jsonMapper: JsonMapper): Handler { - return object : Handler { - override fun handle(response: HttpResponse): T { - try { - return jsonMapper.readValue(response.body(), jacksonTypeRef()) - } catch (e: Exception) { - throw BraintrustException("Error reading response", e) - } - } - } -} - -@JvmSynthetic -internal fun errorHandler(jsonMapper: JsonMapper): Handler { - val handler = jsonHandler(jsonMapper) - - return object : Handler { - override fun handle(response: HttpResponse): BraintrustError { - try { - return handler.handle(response) - } catch (e: Exception) { - return BraintrustError.builder().build() - } - } - } -} - -@JvmSynthetic -internal fun Handler.withErrorHandler(errorHandler: Handler): Handler { - return object : Handler { - override fun handle(response: HttpResponse): T { - when (val statusCode = response.statusCode()) { - in 200..299 -> return this@withErrorHandler.handle(response) - 400 -> throw BadRequestException(response.headers(), errorHandler.handle(response)) - 401 -> - throw UnauthorizedException(response.headers(), errorHandler.handle(response)) - 403 -> - throw PermissionDeniedException( - response.headers(), - errorHandler.handle(response) - ) - 404 -> throw NotFoundException(response.headers(), errorHandler.handle(response)) - 422 -> - throw UnprocessableEntityException( - response.headers(), - errorHandler.handle(response) - ) - 429 -> throw RateLimitException(response.headers(), errorHandler.handle(response)) - in 500..599 -> - throw InternalServerException( - statusCode, - response.headers(), - errorHandler.handle(response) - ) - else -> - throw UnexpectedStatusCodeException( - statusCode, - response.headers(), - StringHandler.handle(response) - ) - } - } - } -} - -class BinaryResponseContentImpl -constructor( - private val response: HttpResponse, -) : BinaryResponseContent { - override fun contentType(): String? { - return response.headers().get("Content-Type").firstOrNull() - } - - override fun body(): InputStream { - return response.body() - } - - override fun writeTo(outputStream: OutputStream) { - response.body().copyTo(outputStream) - } - - override fun close() { - response.body().close() - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/HttpRequestBodies.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/HttpRequestBodies.kt deleted file mode 100644 index 362fd9fa..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/HttpRequestBodies.kt +++ /dev/null @@ -1,56 +0,0 @@ -@file:JvmName("HttpRequestBodies") - -package com.braintrustdata.api.services - -import com.braintrustdata.api.core.http.HttpRequestBody -import com.braintrustdata.api.errors.BraintrustException -import com.fasterxml.jackson.databind.json.JsonMapper -import java.io.OutputStream -import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder - -@JvmSynthetic -internal inline fun json( - jsonMapper: JsonMapper, - value: T, -): HttpRequestBody { - return object : HttpRequestBody { - override fun writeTo(outputStream: OutputStream) { - try { - return jsonMapper.writeValue(outputStream, value) - } catch (e: Exception) { - throw BraintrustException("Error writing request", e) - } - } - - override fun contentType(): String = "application/json" - - override fun repeatable(): Boolean = true - - override fun close() {} - } -} - -@JvmSynthetic -internal fun multipartFormData( - files: Map, -): HttpRequestBody { - val builder = MultipartEntityBuilder.create() - files.forEach { file, bytes -> builder.addBinaryBody(file, bytes) } - val entity = builder.build() - - return object : HttpRequestBody { - override fun writeTo(outputStream: OutputStream) { - try { - return entity.writeTo(outputStream) - } catch (e: Exception) { - throw BraintrustException("Error writing request", e) - } - } - - override fun contentType(): String = entity.contentType - - override fun repeatable(): Boolean = entity.isRepeatable - - override fun close() = entity.close() - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsync.kt new file mode 100755 index 00000000..53d5b9f8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsync.kt @@ -0,0 +1,302 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.Acl +import com.braintrustdata.api.models.AclBatchUpdateParams +import com.braintrustdata.api.models.AclBatchUpdateResponse +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.AclListParams +import com.braintrustdata.api.models.AclRetrieveParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface AclServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AclServiceAsync + + /** + * Create a new acl. If there is an existing acl with the same contents as the one specified in + * the request, will return the existing acl unmodified + */ + fun create(params: AclCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: AclCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get an acl object by its id */ + fun retrieve(aclId: String): CompletableFuture = retrieve(aclId, AclRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + aclId: String, + params: AclRetrieveParams = AclRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = retrieve(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + aclId: String, + params: AclRetrieveParams = AclRetrieveParams.none(), + ): CompletableFuture = retrieve(aclId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: AclRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: AclRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(aclId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(aclId, AclRetrieveParams.none(), requestOptions) + + /** + * List out all acls. The acls are sorted by creation date, with the most recently-created acls + * coming first + */ + fun list(params: AclListParams): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + params: AclListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Delete an acl object by its id */ + fun delete(aclId: String): CompletableFuture = delete(aclId, AclDeleteParams.none()) + + /** @see delete */ + fun delete( + aclId: String, + params: AclDeleteParams = AclDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see delete */ + fun delete( + aclId: String, + params: AclDeleteParams = AclDeleteParams.none(), + ): CompletableFuture = delete(aclId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: AclDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: AclDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(aclId: String, requestOptions: RequestOptions): CompletableFuture = + delete(aclId, AclDeleteParams.none(), requestOptions) + + /** + * Batch update acls. This operation is idempotent, so adding acls which already exist will have + * no effect, and removing acls which do not exist will have no effect. + */ + fun batchUpdate(): CompletableFuture = + batchUpdate(AclBatchUpdateParams.none()) + + /** @see batchUpdate */ + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see batchUpdate */ + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none() + ): CompletableFuture = batchUpdate(params, RequestOptions.none()) + + /** @see batchUpdate */ + fun batchUpdate(requestOptions: RequestOptions): CompletableFuture = + batchUpdate(AclBatchUpdateParams.none(), requestOptions) + + /** Delete a single acl */ + fun findAndDelete(params: AclFindAndDeleteParams): CompletableFuture = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [AclServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AclServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/acl`, but is otherwise the same as + * [AclServiceAsync.create]. + */ + fun create(params: AclCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: AclCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/acl/{acl_id}`, but is otherwise the same as + * [AclServiceAsync.retrieve]. + */ + fun retrieve(aclId: String): CompletableFuture> = + retrieve(aclId, AclRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + aclId: String, + params: AclRetrieveParams = AclRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + aclId: String, + params: AclRetrieveParams = AclRetrieveParams.none(), + ): CompletableFuture> = retrieve(aclId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: AclRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: AclRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + aclId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(aclId, AclRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/acl`, but is otherwise the same as + * [AclServiceAsync.list]. + */ + fun list(params: AclListParams): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + params: AclListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `delete /v1/acl/{acl_id}`, but is otherwise the same as + * [AclServiceAsync.delete]. + */ + fun delete(aclId: String): CompletableFuture> = + delete(aclId, AclDeleteParams.none()) + + /** @see delete */ + fun delete( + aclId: String, + params: AclDeleteParams = AclDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see delete */ + fun delete( + aclId: String, + params: AclDeleteParams = AclDeleteParams.none(), + ): CompletableFuture> = delete(aclId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: AclDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: AclDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + aclId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(aclId, AclDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/acl/batch_update`, but is otherwise the same as + * [AclServiceAsync.batchUpdate]. + */ + fun batchUpdate(): CompletableFuture> = + batchUpdate(AclBatchUpdateParams.none()) + + /** @see batchUpdate */ + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see batchUpdate */ + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none() + ): CompletableFuture> = + batchUpdate(params, RequestOptions.none()) + + /** @see batchUpdate */ + fun batchUpdate( + requestOptions: RequestOptions + ): CompletableFuture> = + batchUpdate(AclBatchUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/acl`, but is otherwise the same as + * [AclServiceAsync.findAndDelete]. + */ + fun findAndDelete(params: AclFindAndDeleteParams): CompletableFuture> = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..a9dee716 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncImpl.kt @@ -0,0 +1,294 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.Acl +import com.braintrustdata.api.models.AclBatchUpdateParams +import com.braintrustdata.api.models.AclBatchUpdateResponse +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 +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class AclServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + AclServiceAsync { + + private val withRawResponse: AclServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AclServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AclServiceAsync = + AclServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: AclCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/acl + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: AclRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/acl/{acl_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: AclListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/acl + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: AclDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/acl/{acl_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun batchUpdate( + params: AclBatchUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/acl/batch_update + withRawResponse().batchUpdate(params, requestOptions).thenApply { it.parse() } + + override fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/acl + withRawResponse().findAndDelete(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AclServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AclServiceAsync.WithRawResponse = + AclServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: AclCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: AclRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aclId", params.aclId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: AclListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + AclListPageAsync.builder() + .service(AclServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: AclDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aclId", params.aclId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val batchUpdateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun batchUpdate( + params: AclBatchUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl", "batch_update") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { batchUpdateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val findAndDeleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { findAndDeleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsync.kt new file mode 100644 index 00000000..2a3e9996 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsync.kt @@ -0,0 +1,388 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.AiSecretListParams +import com.braintrustdata.api.models.AiSecretReplaceParams +import com.braintrustdata.api.models.AiSecretRetrieveParams +import com.braintrustdata.api.models.AiSecretUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface AiSecretServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AiSecretServiceAsync + + /** + * Create a new ai_secret. If there is an existing ai_secret with the same name as the one + * specified in the request, will return the existing ai_secret unmodified + */ + fun create(params: AiSecretCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: AiSecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get an ai_secret object by its id */ + fun retrieve(aiSecretId: String): CompletableFuture = + retrieve(aiSecretId, AiSecretRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + ): CompletableFuture = retrieve(aiSecretId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: AiSecretRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(aiSecretId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(aiSecretId, AiSecretRetrieveParams.none(), requestOptions) + + /** + * Partially update an ai_secret object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(aiSecretId: String): CompletableFuture = + update(aiSecretId, AiSecretUpdateParams.none()) + + /** @see update */ + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see update */ + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + ): CompletableFuture = update(aiSecretId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: AiSecretUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: AiSecretUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(aiSecretId: String, requestOptions: RequestOptions): CompletableFuture = + update(aiSecretId, AiSecretUpdateParams.none(), requestOptions) + + /** + * List out all ai_secrets. The ai_secrets are sorted by creation date, with the most + * recently-created ai_secrets coming first + */ + fun list(): CompletableFuture = list(AiSecretListParams.none()) + + /** @see list */ + fun list( + params: AiSecretListParams = AiSecretListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: AiSecretListParams = AiSecretListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(AiSecretListParams.none(), requestOptions) + + /** Delete an ai_secret object by its id */ + fun delete(aiSecretId: String): CompletableFuture = + delete(aiSecretId, AiSecretDeleteParams.none()) + + /** @see delete */ + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see delete */ + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + ): CompletableFuture = delete(aiSecretId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: AiSecretDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: AiSecretDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(aiSecretId: String, requestOptions: RequestOptions): CompletableFuture = + delete(aiSecretId, AiSecretDeleteParams.none(), requestOptions) + + /** Delete a single ai_secret */ + fun findAndDelete(params: AiSecretFindAndDeleteParams): CompletableFuture = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * Create or replace ai_secret. If there is an existing ai_secret with the same name as the one + * specified in the request, will replace the existing ai_secret with the provided fields + */ + fun replace(params: AiSecretReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: AiSecretReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [AiSecretServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): AiSecretServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/ai_secret`, but is otherwise the same as + * [AiSecretServiceAsync.create]. + */ + fun create(params: AiSecretCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: AiSecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/ai_secret/{ai_secret_id}`, but is otherwise the + * same as [AiSecretServiceAsync.retrieve]. + */ + fun retrieve(aiSecretId: String): CompletableFuture> = + retrieve(aiSecretId, AiSecretRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + ): CompletableFuture> = + retrieve(aiSecretId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: AiSecretRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + aiSecretId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(aiSecretId, AiSecretRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/ai_secret/{ai_secret_id}`, but is otherwise + * the same as [AiSecretServiceAsync.update]. + */ + fun update(aiSecretId: String): CompletableFuture> = + update(aiSecretId, AiSecretUpdateParams.none()) + + /** @see update */ + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see update */ + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + ): CompletableFuture> = + update(aiSecretId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: AiSecretUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: AiSecretUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + aiSecretId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(aiSecretId, AiSecretUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/ai_secret`, but is otherwise the same as + * [AiSecretServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(AiSecretListParams.none()) + + /** @see list */ + fun list( + params: AiSecretListParams = AiSecretListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: AiSecretListParams = AiSecretListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(AiSecretListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/ai_secret/{ai_secret_id}`, but is otherwise + * the same as [AiSecretServiceAsync.delete]. + */ + fun delete(aiSecretId: String): CompletableFuture> = + delete(aiSecretId, AiSecretDeleteParams.none()) + + /** @see delete */ + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see delete */ + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + ): CompletableFuture> = + delete(aiSecretId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: AiSecretDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: AiSecretDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + aiSecretId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(aiSecretId, AiSecretDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/ai_secret`, but is otherwise the same as + * [AiSecretServiceAsync.findAndDelete]. + */ + fun findAndDelete( + params: AiSecretFindAndDeleteParams + ): CompletableFuture> = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `put /v1/ai_secret`, but is otherwise the same as + * [AiSecretServiceAsync.replace]. + */ + fun replace(params: AiSecretReplaceParams): CompletableFuture> = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: AiSecretReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100644 index 00000000..247ce3f1 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncImpl.kt @@ -0,0 +1,339 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.AiSecretUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class AiSecretServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + AiSecretServiceAsync { + + private val withRawResponse: AiSecretServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AiSecretServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AiSecretServiceAsync = + AiSecretServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: AiSecretCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/ai_secret + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/ai_secret/{ai_secret_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: AiSecretUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/ai_secret/{ai_secret_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: AiSecretListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/ai_secret + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: AiSecretDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/ai_secret/{ai_secret_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/ai_secret + withRawResponse().findAndDelete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: AiSecretReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/ai_secret + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AiSecretServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AiSecretServiceAsync.WithRawResponse = + AiSecretServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: AiSecretCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aiSecretId", params.aiSecretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: AiSecretUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aiSecretId", params.aiSecretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: AiSecretListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + AiSecretListPageAsync.builder() + .service(AiSecretServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: AiSecretDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aiSecretId", params.aiSecretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val findAndDeleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { findAndDeleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: AiSecretReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsync.kt new file mode 100644 index 00000000..4de06104 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsync.kt @@ -0,0 +1,262 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ApiKeyListParams +import com.braintrustdata.api.models.ApiKeyRetrieveParams +import com.braintrustdata.api.models.CreateApiKeyOutput +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface ApiKeyServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ApiKeyServiceAsync + + /** + * Create a new api_key. It is possible to have multiple API keys with the same name. There is + * no de-duplication + */ + fun create(params: ApiKeyCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get an api_key object by its id */ + fun retrieve(apiKeyId: String): CompletableFuture = + retrieve(apiKeyId, ApiKeyRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + ): CompletableFuture = retrieve(apiKeyId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ApiKeyRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: ApiKeyRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(apiKeyId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(apiKeyId, ApiKeyRetrieveParams.none(), requestOptions) + + /** + * List out all api_keys. The api_keys are sorted by creation date, with the most + * recently-created api_keys coming first + */ + fun list(): CompletableFuture = list(ApiKeyListParams.none()) + + /** @see list */ + fun list( + params: ApiKeyListParams = ApiKeyListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: ApiKeyListParams = ApiKeyListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(ApiKeyListParams.none(), requestOptions) + + /** Delete an api_key object by its id */ + fun delete(apiKeyId: String): CompletableFuture = + delete(apiKeyId, ApiKeyDeleteParams.none()) + + /** @see delete */ + fun delete( + apiKeyId: String, + params: ApiKeyDeleteParams = ApiKeyDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see delete */ + fun delete( + apiKeyId: String, + params: ApiKeyDeleteParams = ApiKeyDeleteParams.none(), + ): CompletableFuture = delete(apiKeyId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ApiKeyDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: ApiKeyDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(apiKeyId: String, requestOptions: RequestOptions): CompletableFuture = + delete(apiKeyId, ApiKeyDeleteParams.none(), requestOptions) + + /** + * A view of [ApiKeyServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ApiKeyServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/api_key`, but is otherwise the same as + * [ApiKeyServiceAsync.create]. + */ + fun create( + params: ApiKeyCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/api_key/{api_key_id}`, but is otherwise the same + * as [ApiKeyServiceAsync.retrieve]. + */ + fun retrieve(apiKeyId: String): CompletableFuture> = + retrieve(apiKeyId, ApiKeyRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + ): CompletableFuture> = + retrieve(apiKeyId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ApiKeyRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: ApiKeyRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + apiKeyId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(apiKeyId, ApiKeyRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/api_key`, but is otherwise the same as + * [ApiKeyServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(ApiKeyListParams.none()) + + /** @see list */ + fun list( + params: ApiKeyListParams = ApiKeyListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: ApiKeyListParams = ApiKeyListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ApiKeyListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/api_key/{api_key_id}`, but is otherwise the + * same as [ApiKeyServiceAsync.delete]. + */ + fun delete(apiKeyId: String): CompletableFuture> = + delete(apiKeyId, ApiKeyDeleteParams.none()) + + /** @see delete */ + fun delete( + apiKeyId: String, + params: ApiKeyDeleteParams = ApiKeyDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see delete */ + fun delete( + apiKeyId: String, + params: ApiKeyDeleteParams = ApiKeyDeleteParams.none(), + ): CompletableFuture> = + delete(apiKeyId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ApiKeyDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: ApiKeyDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + apiKeyId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(apiKeyId, ApiKeyDeleteParams.none(), requestOptions) + } +} 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 new file mode 100644 index 00000000..0bffa187 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncImpl.kt @@ -0,0 +1,218 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ApiKeyServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + ApiKeyServiceAsync { + + private val withRawResponse: ApiKeyServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ApiKeyServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ApiKeyServiceAsync = + ApiKeyServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/api_key + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: ApiKeyRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/api_key/{api_key_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: ApiKeyListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/api_key + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: ApiKeyDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/api_key/{api_key_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ApiKeyServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ApiKeyServiceAsync.WithRawResponse = + ApiKeyServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ApiKeyRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("apiKeyId", params.apiKeyId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ApiKeyListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ApiKeyListPageAsync.builder() + .service(ApiKeyServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ApiKeyDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("apiKeyId", params.apiKeyId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsync.kt old mode 100644 new mode 100755 index 9910812b..e352ecfc --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsync.kt @@ -1,117 +1,698 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.async +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.models.Dataset import com.braintrustdata.api.models.DatasetCreateParams import com.braintrustdata.api.models.DatasetDeleteParams import com.braintrustdata.api.models.DatasetFeedbackParams import com.braintrustdata.api.models.DatasetFetchParams import com.braintrustdata.api.models.DatasetFetchPostParams -import com.braintrustdata.api.models.DatasetFetchPostResponse -import com.braintrustdata.api.models.DatasetFetchResponse import com.braintrustdata.api.models.DatasetInsertParams -import com.braintrustdata.api.models.DatasetInsertResponse import com.braintrustdata.api.models.DatasetListPageAsync import com.braintrustdata.api.models.DatasetListParams -import com.braintrustdata.api.models.DatasetReplaceParams import com.braintrustdata.api.models.DatasetRetrieveParams +import com.braintrustdata.api.models.DatasetSummarizeParams import com.braintrustdata.api.models.DatasetUpdateParams +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchDatasetEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeDatasetResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface DatasetServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): DatasetServiceAsync + /** * Create a new dataset. If there is an existing dataset in the project with the same name as * the one specified in the request, will return the existing dataset unmodified */ - @JvmOverloads + fun create(params: DatasetCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ fun create( params: DatasetCreateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Get a dataset object by its id */ - @JvmOverloads + fun retrieve(datasetId: String): CompletableFuture = + retrieve(datasetId, DatasetRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + ): CompletableFuture = retrieve(datasetId, params, RequestOptions.none()) + + /** @see retrieve */ fun retrieve( params: DatasetRetrieveParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see retrieve */ + fun retrieve(params: DatasetRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(datasetId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(datasetId, DatasetRetrieveParams.none(), requestOptions) + /** * Partially update a dataset object. Specify the fields to update in the payload. Any * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /dataset/{id}` and then replace it with `PUT /dataset`. + * removing fields or setting them to null. */ - @JvmOverloads + fun update(datasetId: String): CompletableFuture = + update(datasetId, DatasetUpdateParams.none()) + + /** @see update */ + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see update */ + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + ): CompletableFuture = update(datasetId, params, RequestOptions.none()) + + /** @see update */ fun update( params: DatasetUpdateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see update */ + fun update(params: DatasetUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(datasetId: String, requestOptions: RequestOptions): CompletableFuture = + update(datasetId, DatasetUpdateParams.none(), requestOptions) + /** * List out all datasets. The datasets are sorted by creation date, with the most * recently-created datasets coming first */ - @JvmOverloads + fun list(): CompletableFuture = list(DatasetListParams.none()) + + /** @see list */ fun list( - params: DatasetListParams, - requestOptions: RequestOptions = RequestOptions.none() + params: DatasetListParams = DatasetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see list */ + fun list( + params: DatasetListParams = DatasetListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(DatasetListParams.none(), requestOptions) + /** Delete a dataset object by its id */ - @JvmOverloads + fun delete(datasetId: String): CompletableFuture = + delete(datasetId, DatasetDeleteParams.none()) + + /** @see delete */ + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see delete */ + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + ): CompletableFuture = delete(datasetId, params, RequestOptions.none()) + + /** @see delete */ fun delete( params: DatasetDeleteParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see delete */ + fun delete(params: DatasetDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(datasetId: String, requestOptions: RequestOptions): CompletableFuture = + delete(datasetId, DatasetDeleteParams.none(), requestOptions) + /** Log feedback for a set of dataset events */ - @JvmOverloads fun feedback( + datasetId: String, + params: DatasetFeedbackParams, + ): CompletableFuture = + feedback(datasetId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + datasetId: String, params: DatasetFeedbackParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + feedback(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see feedback */ + fun feedback(params: DatasetFeedbackParams): CompletableFuture = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + params: DatasetFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture /** * Fetch the events in a dataset. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body + * parameters in the URL query rather than in the request body. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetch(datasetId: String): CompletableFuture = + fetch(datasetId, DatasetFetchParams.none()) + + /** @see fetch */ + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + fetch(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + ): CompletableFuture = + fetch(datasetId, params, RequestOptions.none()) + + /** @see fetch */ fun fetch( params: DatasetFetchParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see fetch */ + fun fetch(params: DatasetFetchParams): CompletableFuture = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + fetch(datasetId, DatasetFetchParams.none(), requestOptions) /** * Fetch the events in a dataset. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query + * parameters in the request body rather than in the URL query. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetchPost(datasetId: String): CompletableFuture = + fetchPost(datasetId, DatasetFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + fetchPost(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + ): CompletableFuture = + fetchPost(datasetId, params, RequestOptions.none()) + + /** @see fetchPost */ fun fetchPost( params: DatasetFetchPostParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see fetchPost */ + fun fetchPost(params: DatasetFetchPostParams): CompletableFuture = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + fetchPost(datasetId, DatasetFetchPostParams.none(), requestOptions) /** Insert a set of events into the dataset */ - @JvmOverloads fun insert( + datasetId: String, params: DatasetInsertParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + ): CompletableFuture = insert(datasetId, params, RequestOptions.none()) + + /** @see insert */ + fun insert( + datasetId: String, + params: DatasetInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + insert(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see insert */ + fun insert(params: DatasetInsertParams): CompletableFuture = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Summarize dataset */ + fun summarize(datasetId: String): CompletableFuture = + summarize(datasetId, DatasetSummarizeParams.none()) + + /** @see summarize */ + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + summarize(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see summarize */ + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + ): CompletableFuture = + summarize(datasetId, params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see summarize */ + fun summarize(params: DatasetSummarizeParams): CompletableFuture = + summarize(params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + summarize(datasetId, DatasetSummarizeParams.none(), requestOptions) /** - * Create or replace a new dataset. If there is an existing dataset in the project with the same - * name as the one specified in the request, will replace the existing dataset with the provided - * fields + * A view of [DatasetServiceAsync] that provides access to raw HTTP responses for each method. */ - @JvmOverloads - fun replace( - params: DatasetReplaceParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): DatasetServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/dataset`, but is otherwise the same as + * [DatasetServiceAsync.create]. + */ + fun create(params: DatasetCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: DatasetCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/dataset/{dataset_id}`, but is otherwise the same + * as [DatasetServiceAsync.retrieve]. + */ + fun retrieve(datasetId: String): CompletableFuture> = + retrieve(datasetId, DatasetRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + ): CompletableFuture> = + retrieve(datasetId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: DatasetRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: DatasetRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(datasetId, DatasetRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/dataset/{dataset_id}`, but is otherwise the + * same as [DatasetServiceAsync.update]. + */ + fun update(datasetId: String): CompletableFuture> = + update(datasetId, DatasetUpdateParams.none()) + + /** @see update */ + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see update */ + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + ): CompletableFuture> = + update(datasetId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: DatasetUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: DatasetUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(datasetId, DatasetUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/dataset`, but is otherwise the same as + * [DatasetServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(DatasetListParams.none()) + + /** @see list */ + fun list( + params: DatasetListParams = DatasetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: DatasetListParams = DatasetListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(DatasetListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/dataset/{dataset_id}`, but is otherwise the + * same as [DatasetServiceAsync.delete]. + */ + fun delete(datasetId: String): CompletableFuture> = + delete(datasetId, DatasetDeleteParams.none()) + + /** @see delete */ + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see delete */ + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + ): CompletableFuture> = + delete(datasetId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: DatasetDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: DatasetDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(datasetId, DatasetDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/dataset/{dataset_id}/feedback`, but is + * otherwise the same as [DatasetServiceAsync.feedback]. + */ + fun feedback( + datasetId: String, + params: DatasetFeedbackParams, + ): CompletableFuture> = + feedback(datasetId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + datasetId: String, + params: DatasetFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + feedback(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see feedback */ + fun feedback( + params: DatasetFeedbackParams + ): CompletableFuture> = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + params: DatasetFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/dataset/{dataset_id}/fetch`, but is otherwise + * the same as [DatasetServiceAsync.fetch]. + */ + fun fetch( + datasetId: String + ): CompletableFuture> = + fetch(datasetId, DatasetFetchParams.none()) + + /** @see fetch */ + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + fetch(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + ): CompletableFuture> = + fetch(datasetId, params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + params: DatasetFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see fetch */ + fun fetch( + params: DatasetFetchParams + ): CompletableFuture> = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + fetch(datasetId, DatasetFetchParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/dataset/{dataset_id}/fetch`, but is otherwise + * the same as [DatasetServiceAsync.fetchPost]. + */ + fun fetchPost( + datasetId: String + ): CompletableFuture> = + fetchPost(datasetId, DatasetFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + fetchPost(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + ): CompletableFuture> = + fetchPost(datasetId, params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + params: DatasetFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see fetchPost */ + fun fetchPost( + params: DatasetFetchPostParams + ): CompletableFuture> = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + fetchPost(datasetId, DatasetFetchPostParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/dataset/{dataset_id}/insert`, but is otherwise + * the same as [DatasetServiceAsync.insert]. + */ + fun insert( + datasetId: String, + params: DatasetInsertParams, + ): CompletableFuture> = + insert(datasetId, params, RequestOptions.none()) + + /** @see insert */ + fun insert( + datasetId: String, + params: DatasetInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + insert(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see insert */ + fun insert( + params: DatasetInsertParams + ): CompletableFuture> = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/dataset/{dataset_id}/summarize`, but is + * otherwise the same as [DatasetServiceAsync.summarize]. + */ + fun summarize( + datasetId: String + ): CompletableFuture> = + summarize(datasetId, DatasetSummarizeParams.none()) + + /** @see summarize */ + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + summarize(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see summarize */ + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + ): CompletableFuture> = + summarize(datasetId, params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see summarize */ + fun summarize( + params: DatasetSummarizeParams + ): CompletableFuture> = + summarize(params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + datasetId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + summarize(datasetId, DatasetSummarizeParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index 9f2517b0..3c31da2f --- 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 @@ -4,338 +4,465 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +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.models.Dataset import com.braintrustdata.api.models.DatasetCreateParams import com.braintrustdata.api.models.DatasetDeleteParams import com.braintrustdata.api.models.DatasetFeedbackParams import com.braintrustdata.api.models.DatasetFetchParams import com.braintrustdata.api.models.DatasetFetchPostParams -import com.braintrustdata.api.models.DatasetFetchPostResponse -import com.braintrustdata.api.models.DatasetFetchResponse import com.braintrustdata.api.models.DatasetInsertParams -import com.braintrustdata.api.models.DatasetInsertResponse import com.braintrustdata.api.models.DatasetListPageAsync +import com.braintrustdata.api.models.DatasetListPageResponse import com.braintrustdata.api.models.DatasetListParams -import com.braintrustdata.api.models.DatasetReplaceParams import com.braintrustdata.api.models.DatasetRetrieveParams +import com.braintrustdata.api.models.DatasetSummarizeParams import com.braintrustdata.api.models.DatasetUpdateParams -import com.braintrustdata.api.services.emptyHandler -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchDatasetEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeDatasetResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull -class DatasetServiceAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : DatasetServiceAsync { +class DatasetServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + DatasetServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: DatasetServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): DatasetServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): DatasetServiceAsync = + DatasetServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** - * Create a new dataset. If there is an existing dataset in the project with the same name as - * the one specified in the request, will return the existing dataset unmodified - */ override fun create( params: DatasetCreateParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/dataset + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: DatasetRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/dataset/{dataset_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: DatasetUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/dataset/{dataset_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: DatasetListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/dataset + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: DatasetDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/dataset/{dataset_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun feedback( + params: DatasetFeedbackParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/dataset/{dataset_id}/feedback + withRawResponse().feedback(params, requestOptions).thenApply { it.parse() } + + override fun fetch( + params: DatasetFetchParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/dataset/{dataset_id}/fetch + withRawResponse().fetch(params, requestOptions).thenApply { it.parse() } + + override fun fetchPost( + params: DatasetFetchPostParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/dataset/{dataset_id}/fetch + withRawResponse().fetchPost(params, requestOptions).thenApply { it.parse() } + + override fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/dataset/{dataset_id}/insert + withRawResponse().insert(params, requestOptions).thenApply { it.parse() } + + override fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/dataset/{dataset_id}/summarize + withRawResponse().summarize(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DatasetServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): DatasetServiceAsync.WithRawResponse = + DatasetServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: DatasetCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Get a dataset object by its id */ - override fun retrieve( - params: DatasetRetrieveParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { retrieveHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun retrieve( + params: DatasetRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) - /** - * Partially update a dataset object. Specify the fields to update in the payload. Any - * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /dataset/{id}` and then replace it with `PUT /dataset`. - */ - override fun update( - params: DatasetUpdateParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "dataset", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { updateHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun update( + params: DatasetUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * List out all datasets. The datasets are sorted by creation date, with the most - * recently-created datasets coming first - */ - override fun list( - params: DatasetListParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "dataset") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { listHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun list( + params: DatasetListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + DatasetListPageAsync.builder() + .service(DatasetServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } } } - .let { DatasetListPageAsync.of(this, params, it) } } - } - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) - /** Delete a dataset object by its id */ - override fun delete( - params: DatasetDeleteParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "dataset", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { deleteHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun delete( + params: DatasetDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val feedbackHandler: Handler = emptyHandler().withErrorHandler(errorHandler) + private val feedbackHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Log feedback for a set of dataset events */ - override fun feedback( - params: DatasetFeedbackParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "feedback") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response.use { feedbackHandler.handle(it) } + override fun feedback( + params: DatasetFeedbackParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "feedback") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { feedbackHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } } - } - private val fetchHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val fetchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in a dataset. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body - */ - override fun fetch( - params: DatasetFetchParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { fetchHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetch( + params: DatasetFetchParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { fetchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val fetchPostHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val fetchPostHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in a dataset. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - override fun fetchPost( - params: DatasetFetchPostParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { fetchPostHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetchPost( + params: DatasetFetchPostParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { fetchPostHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val insertHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val insertHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Insert a set of events into the dataset */ - override fun insert( - params: DatasetInsertParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "insert") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { insertHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "insert") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { insertHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val replaceHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create or replace a new dataset. If there is an existing dataset in the project with the same - * name as the one specified in the request, will replace the existing dataset with the provided - * fields - */ - override fun replace( - params: DatasetReplaceParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("v1", "dataset") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { replaceHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val summarizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "summarize") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { summarizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsync.kt new file mode 100644 index 00000000..07a075b2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsync.kt @@ -0,0 +1,341 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.EnvVar +import com.braintrustdata.api.models.EnvVarCreateParams +import com.braintrustdata.api.models.EnvVarDeleteParams +import com.braintrustdata.api.models.EnvVarListParams +import com.braintrustdata.api.models.EnvVarListResponse +import com.braintrustdata.api.models.EnvVarReplaceParams +import com.braintrustdata.api.models.EnvVarRetrieveParams +import com.braintrustdata.api.models.EnvVarUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface EnvVarServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): EnvVarServiceAsync + + /** + * Create a new env_var. If there is an existing env_var with the same name as the one specified + * in the request, will return the existing env_var unmodified + */ + fun create(params: EnvVarCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: EnvVarCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get an env_var object by its id */ + fun retrieve(envVarId: String): CompletableFuture = + retrieve(envVarId, EnvVarRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + ): CompletableFuture = retrieve(envVarId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: EnvVarRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: EnvVarRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(envVarId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(envVarId, EnvVarRetrieveParams.none(), requestOptions) + + /** + * Partially update an env_var object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(envVarId: String, params: EnvVarUpdateParams): CompletableFuture = + update(envVarId, params, RequestOptions.none()) + + /** @see update */ + fun update( + envVarId: String, + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see update */ + fun update(params: EnvVarUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * List out all env_vars. The env_vars are sorted by creation date, with the most + * recently-created env_vars coming first + */ + fun list(): CompletableFuture = list(EnvVarListParams.none()) + + /** @see list */ + fun list( + params: EnvVarListParams = EnvVarListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: EnvVarListParams = EnvVarListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(EnvVarListParams.none(), requestOptions) + + /** Delete an env_var object by its id */ + fun delete(envVarId: String): CompletableFuture = + delete(envVarId, EnvVarDeleteParams.none()) + + /** @see delete */ + fun delete( + envVarId: String, + params: EnvVarDeleteParams = EnvVarDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see delete */ + fun delete( + envVarId: String, + params: EnvVarDeleteParams = EnvVarDeleteParams.none(), + ): CompletableFuture = delete(envVarId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: EnvVarDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: EnvVarDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(envVarId: String, requestOptions: RequestOptions): CompletableFuture = + delete(envVarId, EnvVarDeleteParams.none(), requestOptions) + + /** + * Create or replace env_var. If there is an existing env_var with the same name as the one + * specified in the request, will replace the existing env_var with the provided fields + */ + fun replace(params: EnvVarReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: EnvVarReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [EnvVarServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): EnvVarServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/env_var`, but is otherwise the same as + * [EnvVarServiceAsync.create]. + */ + fun create(params: EnvVarCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: EnvVarCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/env_var/{env_var_id}`, but is otherwise the same + * as [EnvVarServiceAsync.retrieve]. + */ + fun retrieve(envVarId: String): CompletableFuture> = + retrieve(envVarId, EnvVarRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + ): CompletableFuture> = + retrieve(envVarId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: EnvVarRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: EnvVarRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + envVarId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(envVarId, EnvVarRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/env_var/{env_var_id}`, but is otherwise the + * same as [EnvVarServiceAsync.update]. + */ + fun update( + envVarId: String, + params: EnvVarUpdateParams, + ): CompletableFuture> = + update(envVarId, params, RequestOptions.none()) + + /** @see update */ + fun update( + envVarId: String, + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see update */ + fun update(params: EnvVarUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/env_var`, but is otherwise the same as + * [EnvVarServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(EnvVarListParams.none()) + + /** @see list */ + fun list( + params: EnvVarListParams = EnvVarListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: EnvVarListParams = EnvVarListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(EnvVarListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/env_var/{env_var_id}`, but is otherwise the + * same as [EnvVarServiceAsync.delete]. + */ + fun delete(envVarId: String): CompletableFuture> = + delete(envVarId, EnvVarDeleteParams.none()) + + /** @see delete */ + fun delete( + envVarId: String, + params: EnvVarDeleteParams = EnvVarDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see delete */ + fun delete( + envVarId: String, + params: EnvVarDeleteParams = EnvVarDeleteParams.none(), + ): CompletableFuture> = + delete(envVarId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: EnvVarDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: EnvVarDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + envVarId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(envVarId, EnvVarDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/env_var`, but is otherwise the same as + * [EnvVarServiceAsync.replace]. + */ + fun replace(params: EnvVarReplaceParams): CompletableFuture> = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: EnvVarReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100644 index 00000000..dd7e690d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncImpl.kt @@ -0,0 +1,286 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.EnvVar +import com.braintrustdata.api.models.EnvVarCreateParams +import com.braintrustdata.api.models.EnvVarDeleteParams +import com.braintrustdata.api.models.EnvVarListParams +import com.braintrustdata.api.models.EnvVarListResponse +import com.braintrustdata.api.models.EnvVarReplaceParams +import com.braintrustdata.api.models.EnvVarRetrieveParams +import com.braintrustdata.api.models.EnvVarUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class EnvVarServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + EnvVarServiceAsync { + + private val withRawResponse: EnvVarServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): EnvVarServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): EnvVarServiceAsync = + EnvVarServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: EnvVarCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/env_var + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: EnvVarRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/env_var/{env_var_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: EnvVarUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/env_var/{env_var_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: EnvVarListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/env_var + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: EnvVarDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/env_var/{env_var_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: EnvVarReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/env_var + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EnvVarServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): EnvVarServiceAsync.WithRawResponse = + EnvVarServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: EnvVarCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: EnvVarRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("envVarId", params.envVarId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: EnvVarUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("envVarId", params.envVarId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: EnvVarListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: EnvVarDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("envVarId", params.envVarId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: EnvVarReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsync.kt new file mode 100644 index 00000000..88ecbb29 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsync.kt @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.EvalCreateParams +import com.braintrustdata.api.models.SummarizeExperimentResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface EvalServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): EvalServiceAsync + + /** + * Launch an evaluation. This is the API-equivalent of the `Eval` function that is built into + * the Braintrust SDK. In the Eval API, you provide pointers to a dataset, task function, and + * scoring functions. The API will then run the evaluation, create an experiment, and return the + * results along with a link to the experiment. To learn more about evals, see the + * [Evals guide](https://www.braintrust.dev/docs/guides/evals). + */ + fun create(params: EvalCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: EvalCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [EvalServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): EvalServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/eval`, but is otherwise the same as + * [EvalServiceAsync.create]. + */ + fun create( + params: EvalCreateParams + ): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: EvalCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100644 index 00000000..ffdc48b0 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncImpl.kt @@ -0,0 +1,86 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.EvalCreateParams +import com.braintrustdata.api.models.SummarizeExperimentResponse +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +class EvalServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + EvalServiceAsync { + + private val withRawResponse: EvalServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): EvalServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): EvalServiceAsync = + EvalServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: EvalCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/eval + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EvalServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): EvalServiceAsync.WithRawResponse = + EvalServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: EvalCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "eval") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsync.kt old mode 100644 new mode 100755 index 6df5bb3e..32bc1644 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsync.kt @@ -1,118 +1,711 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.async +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.models.Experiment import com.braintrustdata.api.models.ExperimentCreateParams import com.braintrustdata.api.models.ExperimentDeleteParams import com.braintrustdata.api.models.ExperimentFeedbackParams import com.braintrustdata.api.models.ExperimentFetchParams import com.braintrustdata.api.models.ExperimentFetchPostParams -import com.braintrustdata.api.models.ExperimentFetchPostResponse -import com.braintrustdata.api.models.ExperimentFetchResponse import com.braintrustdata.api.models.ExperimentInsertParams -import com.braintrustdata.api.models.ExperimentInsertResponse import com.braintrustdata.api.models.ExperimentListPageAsync import com.braintrustdata.api.models.ExperimentListParams -import com.braintrustdata.api.models.ExperimentReplaceParams import com.braintrustdata.api.models.ExperimentRetrieveParams +import com.braintrustdata.api.models.ExperimentSummarizeParams import com.braintrustdata.api.models.ExperimentUpdateParams +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchExperimentEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeExperimentResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface ExperimentServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ExperimentServiceAsync + /** * Create a new experiment. If there is an existing experiment in the project with the same name - * as the one specified in the request, will create a new experiment from `name`, suffixed with - * a unique identifier + * as the one specified in the request, will return the existing experiment unmodified */ - @JvmOverloads + fun create(params: ExperimentCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ fun create( params: ExperimentCreateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Get an experiment object by its id */ - @JvmOverloads + fun retrieve(experimentId: String): CompletableFuture = + retrieve(experimentId, ExperimentRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + ): CompletableFuture = retrieve(experimentId, params, RequestOptions.none()) + + /** @see retrieve */ fun retrieve( params: ExperimentRetrieveParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see retrieve */ + fun retrieve(params: ExperimentRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + retrieve(experimentId, ExperimentRetrieveParams.none(), requestOptions) + /** * Partially update an experiment object. Specify the fields to update in the payload. Any * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /experiment/{id}` and then replace it with `PUT /experiment`. + * removing fields or setting them to null. */ - @JvmOverloads + fun update(experimentId: String): CompletableFuture = + update(experimentId, ExperimentUpdateParams.none()) + + /** @see update */ + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see update */ + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + ): CompletableFuture = update(experimentId, params, RequestOptions.none()) + + /** @see update */ fun update( params: ExperimentUpdateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see update */ + fun update(params: ExperimentUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + update(experimentId, ExperimentUpdateParams.none(), requestOptions) + /** * List out all experiments. The experiments are sorted by creation date, with the most * recently-created experiments coming first */ - @JvmOverloads + fun list(): CompletableFuture = list(ExperimentListParams.none()) + + /** @see list */ fun list( - params: ExperimentListParams, - requestOptions: RequestOptions = RequestOptions.none() + params: ExperimentListParams = ExperimentListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see list */ + fun list( + params: ExperimentListParams = ExperimentListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(ExperimentListParams.none(), requestOptions) + /** Delete an experiment object by its id */ - @JvmOverloads + fun delete(experimentId: String): CompletableFuture = + delete(experimentId, ExperimentDeleteParams.none()) + + /** @see delete */ + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see delete */ + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + ): CompletableFuture = delete(experimentId, params, RequestOptions.none()) + + /** @see delete */ fun delete( params: ExperimentDeleteParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see delete */ + fun delete(params: ExperimentDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(experimentId, ExperimentDeleteParams.none(), requestOptions) + /** Log feedback for a set of experiment events */ - @JvmOverloads + fun feedback( + experimentId: String, + params: ExperimentFeedbackParams, + ): CompletableFuture = + feedback(experimentId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + experimentId: String, + params: ExperimentFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + feedback(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see feedback */ + fun feedback(params: ExperimentFeedbackParams): CompletableFuture = + feedback(params, RequestOptions.none()) + + /** @see feedback */ fun feedback( params: ExperimentFeedbackParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture /** * Fetch the events in an experiment. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body + * parameters in the URL query rather than in the request body. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetch(experimentId: String): CompletableFuture = + fetch(experimentId, ExperimentFetchParams.none()) + + /** @see fetch */ + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + fetch(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + ): CompletableFuture = + fetch(experimentId, params, RequestOptions.none()) + + /** @see fetch */ fun fetch( params: ExperimentFetchParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see fetch */ + fun fetch(params: ExperimentFetchParams): CompletableFuture = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + fetch(experimentId, ExperimentFetchParams.none(), requestOptions) /** * Fetch the events in an experiment. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query + * parameters in the request body rather than in the URL query. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetchPost(experimentId: String): CompletableFuture = + fetchPost(experimentId, ExperimentFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + fetchPost(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + ): CompletableFuture = + fetchPost(experimentId, params, RequestOptions.none()) + + /** @see fetchPost */ fun fetchPost( params: ExperimentFetchPostParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see fetchPost */ + fun fetchPost( + params: ExperimentFetchPostParams + ): CompletableFuture = fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + fetchPost(experimentId, ExperimentFetchPostParams.none(), requestOptions) /** Insert a set of events into the experiment */ - @JvmOverloads fun insert( + experimentId: String, + params: ExperimentInsertParams, + ): CompletableFuture = insert(experimentId, params, RequestOptions.none()) + + /** @see insert */ + fun insert( + experimentId: String, params: ExperimentInsertParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + insert(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see insert */ + fun insert(params: ExperimentInsertParams): CompletableFuture = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Summarize experiment */ + fun summarize(experimentId: String): CompletableFuture = + summarize(experimentId, ExperimentSummarizeParams.none()) + + /** @see summarize */ + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + summarize(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see summarize */ + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + ): CompletableFuture = + summarize(experimentId, params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see summarize */ + fun summarize( + params: ExperimentSummarizeParams + ): CompletableFuture = summarize(params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + summarize(experimentId, ExperimentSummarizeParams.none(), requestOptions) /** - * Create or replace a new experiment. If there is an existing experiment in the project with - * the same name as the one specified in the request, will replace the existing experiment with - * the provided fields + * A view of [ExperimentServiceAsync] that provides access to raw HTTP responses for each + * method. */ - @JvmOverloads - fun replace( - params: ExperimentReplaceParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ExperimentServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/experiment`, but is otherwise the same as + * [ExperimentServiceAsync.create]. + */ + fun create(params: ExperimentCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ExperimentCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/experiment/{experiment_id}`, but is otherwise + * the same as [ExperimentServiceAsync.retrieve]. + */ + fun retrieve(experimentId: String): CompletableFuture> = + retrieve(experimentId, ExperimentRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + ): CompletableFuture> = + retrieve(experimentId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ExperimentRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve( + params: ExperimentRetrieveParams + ): CompletableFuture> = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(experimentId, ExperimentRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/experiment/{experiment_id}`, but is otherwise + * the same as [ExperimentServiceAsync.update]. + */ + fun update(experimentId: String): CompletableFuture> = + update(experimentId, ExperimentUpdateParams.none()) + + /** @see update */ + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see update */ + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + ): CompletableFuture> = + update(experimentId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ExperimentUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: ExperimentUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(experimentId, ExperimentUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/experiment`, but is otherwise the same as + * [ExperimentServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(ExperimentListParams.none()) + + /** @see list */ + fun list( + params: ExperimentListParams = ExperimentListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: ExperimentListParams = ExperimentListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ExperimentListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/experiment/{experiment_id}`, but is otherwise + * the same as [ExperimentServiceAsync.delete]. + */ + fun delete(experimentId: String): CompletableFuture> = + delete(experimentId, ExperimentDeleteParams.none()) + + /** @see delete */ + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see delete */ + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + ): CompletableFuture> = + delete(experimentId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ExperimentDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: ExperimentDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(experimentId, ExperimentDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/experiment/{experiment_id}/feedback`, but is + * otherwise the same as [ExperimentServiceAsync.feedback]. + */ + fun feedback( + experimentId: String, + params: ExperimentFeedbackParams, + ): CompletableFuture> = + feedback(experimentId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + experimentId: String, + params: ExperimentFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + feedback(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see feedback */ + fun feedback( + params: ExperimentFeedbackParams + ): CompletableFuture> = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + params: ExperimentFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/experiment/{experiment_id}/fetch`, but is + * otherwise the same as [ExperimentServiceAsync.fetch]. + */ + fun fetch( + experimentId: String + ): CompletableFuture> = + fetch(experimentId, ExperimentFetchParams.none()) + + /** @see fetch */ + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + fetch(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + ): CompletableFuture> = + fetch(experimentId, params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + params: ExperimentFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see fetch */ + fun fetch( + params: ExperimentFetchParams + ): CompletableFuture> = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + fetch(experimentId, ExperimentFetchParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/experiment/{experiment_id}/fetch`, but is + * otherwise the same as [ExperimentServiceAsync.fetchPost]. + */ + fun fetchPost( + experimentId: String + ): CompletableFuture> = + fetchPost(experimentId, ExperimentFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + fetchPost(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + ): CompletableFuture> = + fetchPost(experimentId, params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + params: ExperimentFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see fetchPost */ + fun fetchPost( + params: ExperimentFetchPostParams + ): CompletableFuture> = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + fetchPost(experimentId, ExperimentFetchPostParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/experiment/{experiment_id}/insert`, but is + * otherwise the same as [ExperimentServiceAsync.insert]. + */ + fun insert( + experimentId: String, + params: ExperimentInsertParams, + ): CompletableFuture> = + insert(experimentId, params, RequestOptions.none()) + + /** @see insert */ + fun insert( + experimentId: String, + params: ExperimentInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + insert(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see insert */ + fun insert( + params: ExperimentInsertParams + ): CompletableFuture> = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/experiment/{experiment_id}/summarize`, but is + * otherwise the same as [ExperimentServiceAsync.summarize]. + */ + fun summarize( + experimentId: String + ): CompletableFuture> = + summarize(experimentId, ExperimentSummarizeParams.none()) + + /** @see summarize */ + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + summarize(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see summarize */ + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + ): CompletableFuture> = + summarize(experimentId, params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see summarize */ + fun summarize( + params: ExperimentSummarizeParams + ): CompletableFuture> = + summarize(params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + experimentId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + summarize(experimentId, ExperimentSummarizeParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index 9f6cd987..a90f64f0 --- 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 @@ -4,341 +4,468 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +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.models.Experiment import com.braintrustdata.api.models.ExperimentCreateParams import com.braintrustdata.api.models.ExperimentDeleteParams import com.braintrustdata.api.models.ExperimentFeedbackParams import com.braintrustdata.api.models.ExperimentFetchParams import com.braintrustdata.api.models.ExperimentFetchPostParams -import com.braintrustdata.api.models.ExperimentFetchPostResponse -import com.braintrustdata.api.models.ExperimentFetchResponse import com.braintrustdata.api.models.ExperimentInsertParams -import com.braintrustdata.api.models.ExperimentInsertResponse import com.braintrustdata.api.models.ExperimentListPageAsync +import com.braintrustdata.api.models.ExperimentListPageResponse import com.braintrustdata.api.models.ExperimentListParams -import com.braintrustdata.api.models.ExperimentReplaceParams import com.braintrustdata.api.models.ExperimentRetrieveParams +import com.braintrustdata.api.models.ExperimentSummarizeParams import com.braintrustdata.api.models.ExperimentUpdateParams -import com.braintrustdata.api.services.emptyHandler -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchExperimentEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeExperimentResponse import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull -class ExperimentServiceAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : ExperimentServiceAsync { +class ExperimentServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + ExperimentServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ExperimentServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ExperimentServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): ExperimentServiceAsync = + ExperimentServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** - * Create a new experiment. If there is an existing experiment in the project with the same name - * as the one specified in the request, will create a new experiment from `name`, suffixed with - * a unique identifier - */ override fun create( params: ExperimentCreateParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/experiment + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: ExperimentRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/experiment/{experiment_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: ExperimentUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/experiment/{experiment_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: ExperimentListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/experiment + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: ExperimentDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/experiment/{experiment_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun feedback( + params: ExperimentFeedbackParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/experiment/{experiment_id}/feedback + withRawResponse().feedback(params, requestOptions).thenApply { it.parse() } + + override fun fetch( + params: ExperimentFetchParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/experiment/{experiment_id}/fetch + withRawResponse().fetch(params, requestOptions).thenApply { it.parse() } + + override fun fetchPost( + params: ExperimentFetchPostParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/experiment/{experiment_id}/fetch + withRawResponse().fetchPost(params, requestOptions).thenApply { it.parse() } + + override fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/experiment/{experiment_id}/insert + withRawResponse().insert(params, requestOptions).thenApply { it.parse() } + + override fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/experiment/{experiment_id}/summarize + withRawResponse().summarize(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ExperimentServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ExperimentServiceAsync.WithRawResponse = + ExperimentServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ExperimentCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Get an experiment object by its id */ - override fun retrieve( - params: ExperimentRetrieveParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { retrieveHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun retrieve( + params: ExperimentRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Partially update an experiment object. Specify the fields to update in the payload. Any - * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /experiment/{id}` and then replace it with `PUT /experiment`. - */ - override fun update( - params: ExperimentUpdateParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "experiment", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { updateHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun update( + params: ExperimentUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * List out all experiments. The experiments are sorted by creation date, with the most - * recently-created experiments coming first - */ - override fun list( - params: ExperimentListParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "experiment") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { listHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun list( + params: ExperimentListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ExperimentListPageAsync.builder() + .service(ExperimentServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } } } - .let { ExperimentListPageAsync.of(this, params, it) } } - } - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Delete an experiment object by its id */ - override fun delete( - params: ExperimentDeleteParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "experiment", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { deleteHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun delete( + params: ExperimentDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val feedbackHandler: Handler = emptyHandler().withErrorHandler(errorHandler) + private val feedbackHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Log feedback for a set of experiment events */ - override fun feedback( - params: ExperimentFeedbackParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "feedback") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response.use { feedbackHandler.handle(it) } + override fun feedback( + params: ExperimentFeedbackParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "feedback") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { feedbackHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } } - } - private val fetchHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val fetchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in an experiment. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body - */ - override fun fetch( - params: ExperimentFetchParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { fetchHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetch( + params: ExperimentFetchParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { fetchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val fetchPostHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val fetchPostHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in an experiment. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - override fun fetchPost( - params: ExperimentFetchPostParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { fetchPostHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetchPost( + params: ExperimentFetchPostParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { fetchPostHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val insertHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val insertHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Insert a set of events into the experiment */ - override fun insert( - params: ExperimentInsertParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "insert") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { insertHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "insert") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { insertHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val replaceHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create or replace a new experiment. If there is an existing experiment in the project with - * the same name as the one specified in the request, will replace the existing experiment with - * the provided fields - */ - override fun replace( - params: ExperimentReplaceParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("v1", "experiment") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { replaceHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val summarizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "summarize") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { summarizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsync.kt new file mode 100755 index 00000000..5aec01d2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsync.kt @@ -0,0 +1,445 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.FunctionListParams +import com.braintrustdata.api.models.FunctionReplaceParams +import com.braintrustdata.api.models.FunctionRetrieveParams +import com.braintrustdata.api.models.FunctionUpdateParams +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface FunctionServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FunctionServiceAsync + + /** + * Create a new function. If there is an existing function in the project with the same slug as + * the one specified in the request, will return the existing function unmodified + */ + fun create(params: FunctionCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: FunctionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a function object by its id */ + fun retrieve(functionId: String): CompletableFuture = + retrieve(functionId, FunctionRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + ): CompletableFuture = retrieve(functionId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: FunctionRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(functionId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(functionId, FunctionRetrieveParams.none(), requestOptions) + + /** + * Partially update a function object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(functionId: String): CompletableFuture = + update(functionId, FunctionUpdateParams.none()) + + /** @see update */ + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see update */ + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + ): CompletableFuture = update(functionId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: FunctionUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: FunctionUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(functionId: String, requestOptions: RequestOptions): CompletableFuture = + update(functionId, FunctionUpdateParams.none(), requestOptions) + + /** + * List out all functions. The functions are sorted by creation date, with the most + * recently-created functions coming first + */ + fun list(): CompletableFuture = list(FunctionListParams.none()) + + /** @see list */ + fun list( + params: FunctionListParams = FunctionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: FunctionListParams = FunctionListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(FunctionListParams.none(), requestOptions) + + /** Delete a function object by its id */ + fun delete(functionId: String): CompletableFuture = + delete(functionId, FunctionDeleteParams.none()) + + /** @see delete */ + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see delete */ + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + ): CompletableFuture = delete(functionId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FunctionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: FunctionDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(functionId: String, requestOptions: RequestOptions): CompletableFuture = + delete(functionId, FunctionDeleteParams.none(), requestOptions) + + /** Invoke a function. */ + fun invoke(functionId: String): CompletableFuture> = + invoke(functionId, FunctionInvokeParams.none()) + + /** @see invoke */ + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + invoke(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see invoke */ + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + ): CompletableFuture> = + invoke(functionId, params, RequestOptions.none()) + + /** @see invoke */ + fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see invoke */ + fun invoke(params: FunctionInvokeParams): CompletableFuture> = + invoke(params, RequestOptions.none()) + + /** @see invoke */ + fun invoke( + functionId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + invoke(functionId, FunctionInvokeParams.none(), requestOptions) + + /** + * Create or replace function. If there is an existing function in the project with the same + * slug as the one specified in the request, will replace the existing function with the + * provided fields + */ + fun replace(params: FunctionReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: FunctionReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [FunctionServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): FunctionServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/function`, but is otherwise the same as + * [FunctionServiceAsync.create]. + */ + fun create(params: FunctionCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: FunctionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/function/{function_id}`, but is otherwise the + * same as [FunctionServiceAsync.retrieve]. + */ + fun retrieve(functionId: String): CompletableFuture> = + retrieve(functionId, FunctionRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + ): CompletableFuture> = + retrieve(functionId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: FunctionRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + functionId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(functionId, FunctionRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/function/{function_id}`, but is otherwise the + * same as [FunctionServiceAsync.update]. + */ + fun update(functionId: String): CompletableFuture> = + update(functionId, FunctionUpdateParams.none()) + + /** @see update */ + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see update */ + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + ): CompletableFuture> = + update(functionId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: FunctionUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: FunctionUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + functionId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(functionId, FunctionUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/function`, but is otherwise the same as + * [FunctionServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(FunctionListParams.none()) + + /** @see list */ + fun list( + params: FunctionListParams = FunctionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: FunctionListParams = FunctionListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(FunctionListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/function/{function_id}`, but is otherwise the + * same as [FunctionServiceAsync.delete]. + */ + fun delete(functionId: String): CompletableFuture> = + delete(functionId, FunctionDeleteParams.none()) + + /** @see delete */ + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see delete */ + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + ): CompletableFuture> = + delete(functionId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FunctionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: FunctionDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + functionId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(functionId, FunctionDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/function/{function_id}/invoke`, but is + * otherwise the same as [FunctionServiceAsync.invoke]. + */ + fun invoke( + functionId: String + ): CompletableFuture>> = + invoke(functionId, FunctionInvokeParams.none()) + + /** @see invoke */ + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> = + invoke(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see invoke */ + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + ): CompletableFuture>> = + invoke(functionId, params, RequestOptions.none()) + + /** @see invoke */ + fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture>> + + /** @see invoke */ + fun invoke( + params: FunctionInvokeParams + ): CompletableFuture>> = + invoke(params, RequestOptions.none()) + + /** @see invoke */ + fun invoke( + functionId: String, + requestOptions: RequestOptions, + ): CompletableFuture>> = + invoke(functionId, FunctionInvokeParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/function`, but is otherwise the same as + * [FunctionServiceAsync.replace]. + */ + fun replace(params: FunctionReplaceParams): CompletableFuture> = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: FunctionReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..e7a864d7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncImpl.kt @@ -0,0 +1,344 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.FunctionUpdateParams +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class FunctionServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + FunctionServiceAsync { + + private val withRawResponse: FunctionServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): FunctionServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FunctionServiceAsync = + FunctionServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: FunctionCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/function + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/function/{function_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: FunctionUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/function/{function_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: FunctionListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/function + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: FunctionDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/function/{function_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions, + ): CompletableFuture> = + // post /v1/function/{function_id}/invoke + withRawResponse().invoke(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: FunctionReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/function + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FunctionServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): FunctionServiceAsync.WithRawResponse = + FunctionServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: FunctionCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: FunctionUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: FunctionListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + FunctionListPageAsync.builder() + .service(FunctionServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: FunctionDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val invokeHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions, + ): CompletableFuture>> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0), "invoke") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { invokeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.ifPresent { it.validate() } + } + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: FunctionReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsync.kt new file mode 100755 index 00000000..07a132eb --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsync.kt @@ -0,0 +1,360 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.GroupListParams +import com.braintrustdata.api.models.GroupReplaceParams +import com.braintrustdata.api.models.GroupRetrieveParams +import com.braintrustdata.api.models.GroupUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface GroupServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): GroupServiceAsync + + /** + * Create a new group. If there is an existing group with the same name as the one specified in + * the request, will return the existing group unmodified + */ + fun create(params: GroupCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: GroupCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a group object by its id */ + fun retrieve(groupId: String): CompletableFuture = + retrieve(groupId, GroupRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + groupId: String, + params: GroupRetrieveParams = GroupRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + groupId: String, + params: GroupRetrieveParams = GroupRetrieveParams.none(), + ): CompletableFuture = retrieve(groupId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: GroupRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: GroupRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(groupId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(groupId, GroupRetrieveParams.none(), requestOptions) + + /** + * Partially update a group object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields + * or setting them to null. + */ + fun update(groupId: String): CompletableFuture = + update(groupId, GroupUpdateParams.none()) + + /** @see update */ + fun update( + groupId: String, + params: GroupUpdateParams = GroupUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see update */ + fun update( + groupId: String, + params: GroupUpdateParams = GroupUpdateParams.none(), + ): CompletableFuture = update(groupId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: GroupUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: GroupUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(groupId: String, requestOptions: RequestOptions): CompletableFuture = + update(groupId, GroupUpdateParams.none(), requestOptions) + + /** + * List out all groups. The groups are sorted by creation date, with the most recently-created + * groups coming first + */ + fun list(): CompletableFuture = list(GroupListParams.none()) + + /** @see list */ + fun list( + params: GroupListParams = GroupListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: GroupListParams = GroupListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(GroupListParams.none(), requestOptions) + + /** Delete a group object by its id */ + fun delete(groupId: String): CompletableFuture = + delete(groupId, GroupDeleteParams.none()) + + /** @see delete */ + fun delete( + groupId: String, + params: GroupDeleteParams = GroupDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see delete */ + fun delete( + groupId: String, + params: GroupDeleteParams = GroupDeleteParams.none(), + ): CompletableFuture = delete(groupId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: GroupDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: GroupDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(groupId: String, requestOptions: RequestOptions): CompletableFuture = + delete(groupId, GroupDeleteParams.none(), requestOptions) + + /** + * Create or replace group. If there is an existing group with the same name as the one + * specified in the request, will replace the existing group with the provided fields + */ + fun replace(params: GroupReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: GroupReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [GroupServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): GroupServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/group`, but is otherwise the same as + * [GroupServiceAsync.create]. + */ + fun create(params: GroupCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: GroupCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/group/{group_id}`, but is otherwise the same as + * [GroupServiceAsync.retrieve]. + */ + fun retrieve(groupId: String): CompletableFuture> = + retrieve(groupId, GroupRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + groupId: String, + params: GroupRetrieveParams = GroupRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + groupId: String, + params: GroupRetrieveParams = GroupRetrieveParams.none(), + ): CompletableFuture> = + retrieve(groupId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: GroupRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: GroupRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + groupId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(groupId, GroupRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/group/{group_id}`, but is otherwise the same + * as [GroupServiceAsync.update]. + */ + fun update(groupId: String): CompletableFuture> = + update(groupId, GroupUpdateParams.none()) + + /** @see update */ + fun update( + groupId: String, + params: GroupUpdateParams = GroupUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see update */ + fun update( + groupId: String, + params: GroupUpdateParams = GroupUpdateParams.none(), + ): CompletableFuture> = + update(groupId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: GroupUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: GroupUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + groupId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(groupId, GroupUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/group`, but is otherwise the same as + * [GroupServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(GroupListParams.none()) + + /** @see list */ + fun list( + params: GroupListParams = GroupListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: GroupListParams = GroupListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(GroupListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/group/{group_id}`, but is otherwise the same + * as [GroupServiceAsync.delete]. + */ + fun delete(groupId: String): CompletableFuture> = + delete(groupId, GroupDeleteParams.none()) + + /** @see delete */ + fun delete( + groupId: String, + params: GroupDeleteParams = GroupDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see delete */ + fun delete( + groupId: String, + params: GroupDeleteParams = GroupDeleteParams.none(), + ): CompletableFuture> = + delete(groupId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: GroupDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: GroupDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + groupId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(groupId, GroupDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/group`, but is otherwise the same as + * [GroupServiceAsync.replace]. + */ + fun replace(params: GroupReplaceParams): CompletableFuture> = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: GroupReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..2f06ad80 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncImpl.kt @@ -0,0 +1,295 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.GroupUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class GroupServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + GroupServiceAsync { + + private val withRawResponse: GroupServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): GroupServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): GroupServiceAsync = + GroupServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: GroupCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/group + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: GroupRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/group/{group_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: GroupUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/group/{group_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: GroupListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/group + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: GroupDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/group/{group_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: GroupReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/group + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + GroupServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): GroupServiceAsync.WithRawResponse = + GroupServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: GroupCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: GroupRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("groupId", params.groupId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: GroupUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("groupId", params.groupId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: GroupListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + GroupListPageAsync.builder() + .service(GroupServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: GroupDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("groupId", params.groupId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: GroupReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsync.kt new file mode 100755 index 00000000..326f5c44 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsync.kt @@ -0,0 +1,327 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.Organization +import com.braintrustdata.api.models.OrganizationDeleteParams +import com.braintrustdata.api.models.OrganizationListPageAsync +import com.braintrustdata.api.models.OrganizationListParams +import com.braintrustdata.api.models.OrganizationRetrieveParams +import com.braintrustdata.api.models.OrganizationUpdateParams +import com.braintrustdata.api.services.async.organizations.MemberServiceAsync +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface OrganizationServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): OrganizationServiceAsync + + fun members(): MemberServiceAsync + + /** Get an organization object by its id */ + fun retrieve(organizationId: String): CompletableFuture = + retrieve(organizationId, OrganizationRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + ): CompletableFuture = retrieve(organizationId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: OrganizationRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + retrieve(organizationId, OrganizationRetrieveParams.none(), requestOptions) + + /** + * Partially update an organization object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(organizationId: String): CompletableFuture = + update(organizationId, OrganizationUpdateParams.none()) + + /** @see update */ + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see update */ + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + ): CompletableFuture = update(organizationId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: OrganizationUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + organizationId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + update(organizationId, OrganizationUpdateParams.none(), requestOptions) + + /** + * List out all organizations. The organizations are sorted by creation date, with the most + * recently-created organizations coming first + */ + fun list(): CompletableFuture = list(OrganizationListParams.none()) + + /** @see list */ + fun list( + params: OrganizationListParams = OrganizationListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: OrganizationListParams = OrganizationListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(OrganizationListParams.none(), requestOptions) + + /** Delete an organization object by its id */ + fun delete(organizationId: String): CompletableFuture = + delete(organizationId, OrganizationDeleteParams.none()) + + /** @see delete */ + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see delete */ + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + ): CompletableFuture = delete(organizationId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: OrganizationDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + organizationId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(organizationId, OrganizationDeleteParams.none(), requestOptions) + + /** + * A view of [OrganizationServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): OrganizationServiceAsync.WithRawResponse + + fun members(): MemberServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/organization/{organization_id}`, but is + * otherwise the same as [OrganizationServiceAsync.retrieve]. + */ + fun retrieve(organizationId: String): CompletableFuture> = + retrieve(organizationId, OrganizationRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + ): CompletableFuture> = + retrieve(organizationId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve( + params: OrganizationRetrieveParams + ): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(organizationId, OrganizationRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/organization/{organization_id}`, but is + * otherwise the same as [OrganizationServiceAsync.update]. + */ + fun update(organizationId: String): CompletableFuture> = + update(organizationId, OrganizationUpdateParams.none()) + + /** @see update */ + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see update */ + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + ): CompletableFuture> = + update(organizationId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update( + params: OrganizationUpdateParams + ): CompletableFuture> = update(params, RequestOptions.none()) + + /** @see update */ + fun update( + organizationId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(organizationId, OrganizationUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/organization`, but is otherwise the same as + * [OrganizationServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(OrganizationListParams.none()) + + /** @see list */ + fun list( + params: OrganizationListParams = OrganizationListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: OrganizationListParams = OrganizationListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(OrganizationListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/organization/{organization_id}`, but is + * otherwise the same as [OrganizationServiceAsync.delete]. + */ + fun delete(organizationId: String): CompletableFuture> = + delete(organizationId, OrganizationDeleteParams.none()) + + /** @see delete */ + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see delete */ + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + ): CompletableFuture> = + delete(organizationId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete( + params: OrganizationDeleteParams + ): CompletableFuture> = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + organizationId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(organizationId, OrganizationDeleteParams.none(), requestOptions) + } +} 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 new file mode 100755 index 00000000..ba60634f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncImpl.kt @@ -0,0 +1,234 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.services.async.organizations.MemberServiceAsync +import com.braintrustdata.api.services.async.organizations.MemberServiceAsyncImpl +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class OrganizationServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + OrganizationServiceAsync { + + private val withRawResponse: OrganizationServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val members: MemberServiceAsync by lazy { MemberServiceAsyncImpl(clientOptions) } + + override fun withRawResponse(): OrganizationServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): OrganizationServiceAsync = + OrganizationServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun members(): MemberServiceAsync = members + + override fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/organization/{organization_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/organization/{organization_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: OrganizationListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/organization + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/organization/{organization_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + OrganizationServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val members: MemberServiceAsync.WithRawResponse by lazy { + MemberServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): OrganizationServiceAsync.WithRawResponse = + OrganizationServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun members(): MemberServiceAsync.WithRawResponse = members + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("organizationId", params.organizationId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("organizationId", params.organizationId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: OrganizationListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + OrganizationListPageAsync.builder() + .service(OrganizationServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("organizationId", params.organizationId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsync.kt new file mode 100755 index 00000000..cec1cff9 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsync.kt @@ -0,0 +1,380 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ProjectScoreListParams +import com.braintrustdata.api.models.ProjectScoreReplaceParams +import com.braintrustdata.api.models.ProjectScoreRetrieveParams +import com.braintrustdata.api.models.ProjectScoreUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface ProjectScoreServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ProjectScoreServiceAsync + + /** + * Create a new project_score. If there is an existing project_score in the project with the + * same name as the one specified in the request, will return the existing project_score + * unmodified + */ + fun create(params: ProjectScoreCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a project_score object by its id */ + fun retrieve(projectScoreId: String): CompletableFuture = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + ): CompletableFuture = retrieve(projectScoreId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: ProjectScoreRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none(), requestOptions) + + /** + * Partially update a project_score object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(projectScoreId: String): CompletableFuture = + update(projectScoreId, ProjectScoreUpdateParams.none()) + + /** @see update */ + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see update */ + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + ): CompletableFuture = update(projectScoreId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: ProjectScoreUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + projectScoreId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + update(projectScoreId, ProjectScoreUpdateParams.none(), requestOptions) + + /** + * List out all project_scores. The project_scores are sorted by creation date, with the most + * recently-created project_scores coming first + */ + fun list(): CompletableFuture = list(ProjectScoreListParams.none()) + + /** @see list */ + fun list( + params: ProjectScoreListParams = ProjectScoreListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: ProjectScoreListParams = ProjectScoreListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(ProjectScoreListParams.none(), requestOptions) + + /** Delete a project_score object by its id */ + fun delete(projectScoreId: String): CompletableFuture = + delete(projectScoreId, ProjectScoreDeleteParams.none()) + + /** @see delete */ + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + ): CompletableFuture = delete(projectScoreId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: ProjectScoreDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + projectScoreId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(projectScoreId, ProjectScoreDeleteParams.none(), requestOptions) + + /** + * Create or replace project_score. If there is an existing project_score in the project with + * the same name as the one specified in the request, will replace the existing project_score + * with the provided fields + */ + fun replace(params: ProjectScoreReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [ProjectScoreServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ProjectScoreServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project_score`, but is otherwise the same as + * [ProjectScoreServiceAsync.create]. + */ + fun create( + params: ProjectScoreCreateParams + ): CompletableFuture> = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/project_score/{project_score_id}`, but is + * otherwise the same as [ProjectScoreServiceAsync.retrieve]. + */ + fun retrieve(projectScoreId: String): CompletableFuture> = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + ): CompletableFuture> = + retrieve(projectScoreId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve( + params: ProjectScoreRetrieveParams + ): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/project_score/{project_score_id}`, but is + * otherwise the same as [ProjectScoreServiceAsync.update]. + */ + fun update(projectScoreId: String): CompletableFuture> = + update(projectScoreId, ProjectScoreUpdateParams.none()) + + /** @see update */ + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see update */ + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + ): CompletableFuture> = + update(projectScoreId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update( + params: ProjectScoreUpdateParams + ): CompletableFuture> = update(params, RequestOptions.none()) + + /** @see update */ + fun update( + projectScoreId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(projectScoreId, ProjectScoreUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/project_score`, but is otherwise the same as + * [ProjectScoreServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(ProjectScoreListParams.none()) + + /** @see list */ + fun list( + params: ProjectScoreListParams = ProjectScoreListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: ProjectScoreListParams = ProjectScoreListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ProjectScoreListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/project_score/{project_score_id}`, but is + * otherwise the same as [ProjectScoreServiceAsync.delete]. + */ + fun delete(projectScoreId: String): CompletableFuture> = + delete(projectScoreId, ProjectScoreDeleteParams.none()) + + /** @see delete */ + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + ): CompletableFuture> = + delete(projectScoreId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete( + params: ProjectScoreDeleteParams + ): CompletableFuture> = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + projectScoreId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(projectScoreId, ProjectScoreDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/project_score`, but is otherwise the same as + * [ProjectScoreServiceAsync.replace]. + */ + fun replace( + params: ProjectScoreReplaceParams + ): CompletableFuture> = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..944fc4a7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncImpl.kt @@ -0,0 +1,300 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.ProjectScoreUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ProjectScoreServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectScoreServiceAsync { + + private val withRawResponse: ProjectScoreServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ProjectScoreServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ProjectScoreServiceAsync = + ProjectScoreServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/project_score + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/project_score/{project_score_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/project_score/{project_score_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: ProjectScoreListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/project_score + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/project_score/{project_score_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/project_score + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectScoreServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ProjectScoreServiceAsync.WithRawResponse = + ProjectScoreServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectScoreId", params.projectScoreId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectScoreId", params.projectScoreId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ProjectScoreListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ProjectScoreListPageAsync.builder() + .service(ProjectScoreServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectScoreId", params.projectScoreId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsync.kt old mode 100644 new mode 100755 index 3117b807..ca90c67a --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsync.kt @@ -1,78 +1,340 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.async +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor 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.ProjectListParams -import com.braintrustdata.api.models.ProjectReplaceParams import com.braintrustdata.api.models.ProjectRetrieveParams import com.braintrustdata.api.models.ProjectUpdateParams -import com.braintrustdata.api.services.async.project.LogServiceAsync +import com.braintrustdata.api.services.async.projects.LogServiceAsync import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface ProjectServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ProjectServiceAsync + fun logs(): LogServiceAsync /** * Create a new project. If there is an existing project with the same name as the one specified * in the request, will return the existing project unmodified */ - @JvmOverloads + fun create(params: ProjectCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ fun create( params: ProjectCreateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture /** Get a project object by its id */ - @JvmOverloads + fun retrieve(projectId: String): CompletableFuture = + retrieve(projectId, ProjectRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + ): CompletableFuture = retrieve(projectId, params, RequestOptions.none()) + + /** @see retrieve */ fun retrieve( params: ProjectRetrieveParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see retrieve */ + fun retrieve(params: ProjectRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(projectId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(projectId, ProjectRetrieveParams.none(), requestOptions) + /** * Partially update a project object. Specify the fields to update in the payload. Any * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /project/{id}` and then replace it with `PUT /project`. + * removing fields or setting them to null. */ - @JvmOverloads + fun update(projectId: String): CompletableFuture = + update(projectId, ProjectUpdateParams.none()) + + /** @see update */ + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see update */ + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + ): CompletableFuture = update(projectId, params, RequestOptions.none()) + + /** @see update */ fun update( params: ProjectUpdateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see update */ + fun update(params: ProjectUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(projectId: String, requestOptions: RequestOptions): CompletableFuture = + update(projectId, ProjectUpdateParams.none(), requestOptions) + /** * List out all projects. The projects are sorted by creation date, with the most * recently-created projects coming first */ - @JvmOverloads + fun list(): CompletableFuture = list(ProjectListParams.none()) + + /** @see list */ fun list( - params: ProjectListParams, - requestOptions: RequestOptions = RequestOptions.none() + params: ProjectListParams = ProjectListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see list */ + fun list( + params: ProjectListParams = ProjectListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(ProjectListParams.none(), requestOptions) + /** Delete a project object by its id */ - @JvmOverloads + fun delete(projectId: String): CompletableFuture = + delete(projectId, ProjectDeleteParams.none()) + + /** @see delete */ + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + ): CompletableFuture = delete(projectId, params, RequestOptions.none()) + + /** @see delete */ fun delete( params: ProjectDeleteParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** @see delete */ + fun delete(params: ProjectDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(projectId: String, requestOptions: RequestOptions): CompletableFuture = + delete(projectId, ProjectDeleteParams.none(), requestOptions) + /** - * Create or replace a new project. If there is an existing project with the same name as the - * one specified in the request, will replace the existing project with the provided fields + * A view of [ProjectServiceAsync] that provides access to raw HTTP responses for each method. */ - @JvmOverloads - fun replace( - params: ProjectReplaceParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ProjectServiceAsync.WithRawResponse + + fun logs(): LogServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project`, but is otherwise the same as + * [ProjectServiceAsync.create]. + */ + fun create(params: ProjectCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ProjectCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/project/{project_id}`, but is otherwise the same + * as [ProjectServiceAsync.retrieve]. + */ + fun retrieve(projectId: String): CompletableFuture> = + retrieve(projectId, ProjectRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + ): CompletableFuture> = + retrieve(projectId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ProjectRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: ProjectRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + projectId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(projectId, ProjectRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/project/{project_id}`, but is otherwise the + * same as [ProjectServiceAsync.update]. + */ + fun update(projectId: String): CompletableFuture> = + update(projectId, ProjectUpdateParams.none()) + + /** @see update */ + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see update */ + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + ): CompletableFuture> = + update(projectId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ProjectUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: ProjectUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + projectId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(projectId, ProjectUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/project`, but is otherwise the same as + * [ProjectServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(ProjectListParams.none()) + + /** @see list */ + fun list( + params: ProjectListParams = ProjectListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: ProjectListParams = ProjectListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ProjectListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/project/{project_id}`, but is otherwise the + * same as [ProjectServiceAsync.delete]. + */ + fun delete(projectId: String): CompletableFuture> = + delete(projectId, ProjectDeleteParams.none()) + + /** @see delete */ + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + ): CompletableFuture> = + delete(projectId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ProjectDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: ProjectDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + projectId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(projectId, ProjectDeleteParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index 7e2353a1..b8ae8ac1 --- 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 @@ -4,220 +4,265 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +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.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.ProjectReplaceParams import com.braintrustdata.api.models.ProjectRetrieveParams import com.braintrustdata.api.models.ProjectUpdateParams -import com.braintrustdata.api.services.async.project.LogServiceAsync -import com.braintrustdata.api.services.async.project.LogServiceAsyncImpl -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler +import com.braintrustdata.api.services.async.projects.LogServiceAsync +import com.braintrustdata.api.services.async.projects.LogServiceAsyncImpl import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull -class ProjectServiceAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : ProjectServiceAsync { +class ProjectServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ProjectServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val logs: LogServiceAsync by lazy { LogServiceAsyncImpl(clientOptions) } - override fun logs(): LogServiceAsync = logs + override fun withRawResponse(): ProjectServiceAsync.WithRawResponse = withRawResponse - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): ProjectServiceAsync = + ProjectServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun logs(): LogServiceAsync = logs - /** - * Create a new project. If there is an existing project with the same name as the one specified - * in the request, will return the existing project unmodified - */ override fun create( params: ProjectCreateParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/project + withRawResponse().create(params, requestOptions).thenApply { it.parse() } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get a project object by its id */ override fun retrieve( params: ProjectRetrieveParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "project", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { retrieveHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/project/{project_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: ProjectUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/project/{project_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: ProjectListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/project + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: ProjectDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/project/{project_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val logs: LogServiceAsync.WithRawResponse by lazy { + LogServiceAsyncImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): ProjectServiceAsync.WithRawResponse = + ProjectServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun logs(): LogServiceAsync.WithRawResponse = logs + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ProjectCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Partially update a project object. Specify the fields to update in the payload. Any - * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /project/{id}` and then replace it with `PUT /project`. - */ - override fun update( - params: ProjectUpdateParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "project", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { updateHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun retrieve( + params: ProjectRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } - } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) - /** - * List out all projects. The projects are sorted by creation date, with the most - * recently-created projects coming first - */ - override fun list( - params: ProjectListParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "project") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { listHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun update( + params: ProjectUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } - .let { ProjectListPageAsync.of(this, params, it) } } - } - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Delete a project object by its id */ - override fun delete( - params: ProjectDeleteParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "project", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { deleteHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun list( + params: ProjectListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ProjectListPageAsync.builder() + .service(ProjectServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } } } } - } - private val replaceHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create or replace a new project. If there is an existing project with the same name as the - * one specified in the request, will replace the existing project with the provided fields - */ - override fun replace( - params: ProjectReplaceParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("v1", "project") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { replaceHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ProjectDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsync.kt new file mode 100755 index 00000000..2ea9f564 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsync.kt @@ -0,0 +1,375 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ProjectTagListParams +import com.braintrustdata.api.models.ProjectTagReplaceParams +import com.braintrustdata.api.models.ProjectTagRetrieveParams +import com.braintrustdata.api.models.ProjectTagUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface ProjectTagServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ProjectTagServiceAsync + + /** + * Create a new project_tag. If there is an existing project_tag in the project with the same + * name as the one specified in the request, will return the existing project_tag unmodified + */ + fun create(params: ProjectTagCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a project_tag object by its id */ + fun retrieve(projectTagId: String): CompletableFuture = + retrieve(projectTagId, ProjectTagRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + ): CompletableFuture = retrieve(projectTagId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: ProjectTagRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + retrieve(projectTagId, ProjectTagRetrieveParams.none(), requestOptions) + + /** + * Partially update a project_tag object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(projectTagId: String): CompletableFuture = + update(projectTagId, ProjectTagUpdateParams.none()) + + /** @see update */ + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see update */ + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + ): CompletableFuture = update(projectTagId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: ProjectTagUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + projectTagId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + update(projectTagId, ProjectTagUpdateParams.none(), requestOptions) + + /** + * List out all project_tags. The project_tags are sorted by creation date, with the most + * recently-created project_tags coming first + */ + fun list(): CompletableFuture = list(ProjectTagListParams.none()) + + /** @see list */ + fun list( + params: ProjectTagListParams = ProjectTagListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: ProjectTagListParams = ProjectTagListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(ProjectTagListParams.none(), requestOptions) + + /** Delete a project_tag object by its id */ + fun delete(projectTagId: String): CompletableFuture = + delete(projectTagId, ProjectTagDeleteParams.none()) + + /** @see delete */ + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + ): CompletableFuture = delete(projectTagId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: ProjectTagDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + projectTagId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(projectTagId, ProjectTagDeleteParams.none(), requestOptions) + + /** + * Create or replace project_tag. If there is an existing project_tag in the project with the + * same name as the one specified in the request, will replace the existing project_tag with the + * provided fields + */ + fun replace(params: ProjectTagReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [ProjectTagServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ProjectTagServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project_tag`, but is otherwise the same as + * [ProjectTagServiceAsync.create]. + */ + fun create(params: ProjectTagCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/project_tag/{project_tag_id}`, but is otherwise + * the same as [ProjectTagServiceAsync.retrieve]. + */ + fun retrieve(projectTagId: String): CompletableFuture> = + retrieve(projectTagId, ProjectTagRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + ): CompletableFuture> = + retrieve(projectTagId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve( + params: ProjectTagRetrieveParams + ): CompletableFuture> = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(projectTagId, ProjectTagRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/project_tag/{project_tag_id}`, but is + * otherwise the same as [ProjectTagServiceAsync.update]. + */ + fun update(projectTagId: String): CompletableFuture> = + update(projectTagId, ProjectTagUpdateParams.none()) + + /** @see update */ + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see update */ + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + ): CompletableFuture> = + update(projectTagId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: ProjectTagUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + projectTagId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(projectTagId, ProjectTagUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/project_tag`, but is otherwise the same as + * [ProjectTagServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(ProjectTagListParams.none()) + + /** @see list */ + fun list( + params: ProjectTagListParams = ProjectTagListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: ProjectTagListParams = ProjectTagListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(ProjectTagListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/project_tag/{project_tag_id}`, but is + * otherwise the same as [ProjectTagServiceAsync.delete]. + */ + fun delete(projectTagId: String): CompletableFuture> = + delete(projectTagId, ProjectTagDeleteParams.none()) + + /** @see delete */ + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + ): CompletableFuture> = + delete(projectTagId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: ProjectTagDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + projectTagId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(projectTagId, ProjectTagDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/project_tag`, but is otherwise the same as + * [ProjectTagServiceAsync.replace]. + */ + fun replace( + params: ProjectTagReplaceParams + ): CompletableFuture> = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..3257d2c7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncImpl.kt @@ -0,0 +1,300 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.ProjectTagUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ProjectTagServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectTagServiceAsync { + + private val withRawResponse: ProjectTagServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ProjectTagServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ProjectTagServiceAsync = + ProjectTagServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/project_tag + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/project_tag/{project_tag_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/project_tag/{project_tag_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: ProjectTagListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/project_tag + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/project_tag/{project_tag_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/project_tag + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectTagServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ProjectTagServiceAsync.WithRawResponse = + ProjectTagServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectTagId", params.projectTagId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectTagId", params.projectTagId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ProjectTagListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ProjectTagListPageAsync.builder() + .service(ProjectTagServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectTagId", params.projectTagId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsync.kt new file mode 100755 index 00000000..f961f5a7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsync.kt @@ -0,0 +1,362 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.PromptListParams +import com.braintrustdata.api.models.PromptReplaceParams +import com.braintrustdata.api.models.PromptRetrieveParams +import com.braintrustdata.api.models.PromptUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface PromptServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): PromptServiceAsync + + /** + * Create a new prompt. If there is an existing prompt in the project with the same slug as the + * one specified in the request, will return the existing prompt unmodified + */ + fun create(params: PromptCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: PromptCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a prompt object by its id */ + fun retrieve(promptId: String): CompletableFuture = + retrieve(promptId, PromptRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + ): CompletableFuture = retrieve(promptId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: PromptRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: PromptRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(promptId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(promptId, PromptRetrieveParams.none(), requestOptions) + + /** + * Partially update a prompt object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(promptId: String): CompletableFuture = + update(promptId, PromptUpdateParams.none()) + + /** @see update */ + fun update( + promptId: String, + params: PromptUpdateParams = PromptUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see update */ + fun update( + promptId: String, + params: PromptUpdateParams = PromptUpdateParams.none(), + ): CompletableFuture = update(promptId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: PromptUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: PromptUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(promptId: String, requestOptions: RequestOptions): CompletableFuture = + update(promptId, PromptUpdateParams.none(), requestOptions) + + /** + * List out all prompts. The prompts are sorted by creation date, with the most recently-created + * prompts coming first + */ + fun list(): CompletableFuture = list(PromptListParams.none()) + + /** @see list */ + fun list( + params: PromptListParams = PromptListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: PromptListParams = PromptListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(PromptListParams.none(), requestOptions) + + /** Delete a prompt object by its id */ + fun delete(promptId: String): CompletableFuture = + delete(promptId, PromptDeleteParams.none()) + + /** @see delete */ + fun delete( + promptId: String, + params: PromptDeleteParams = PromptDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see delete */ + fun delete( + promptId: String, + params: PromptDeleteParams = PromptDeleteParams.none(), + ): CompletableFuture = delete(promptId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: PromptDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: PromptDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(promptId: String, requestOptions: RequestOptions): CompletableFuture = + delete(promptId, PromptDeleteParams.none(), requestOptions) + + /** + * Create or replace prompt. If there is an existing prompt in the project with the same slug as + * the one specified in the request, will replace the existing prompt with the provided fields + */ + fun replace(params: PromptReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: PromptReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [PromptServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): PromptServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/prompt`, but is otherwise the same as + * [PromptServiceAsync.create]. + */ + fun create(params: PromptCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: PromptCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/prompt/{prompt_id}`, but is otherwise the same + * as [PromptServiceAsync.retrieve]. + */ + fun retrieve(promptId: String): CompletableFuture> = + retrieve(promptId, PromptRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + ): CompletableFuture> = + retrieve(promptId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: PromptRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: PromptRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + promptId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(promptId, PromptRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/prompt/{prompt_id}`, but is otherwise the same + * as [PromptServiceAsync.update]. + */ + fun update(promptId: String): CompletableFuture> = + update(promptId, PromptUpdateParams.none()) + + /** @see update */ + fun update( + promptId: String, + params: PromptUpdateParams = PromptUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see update */ + fun update( + promptId: String, + params: PromptUpdateParams = PromptUpdateParams.none(), + ): CompletableFuture> = + update(promptId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: PromptUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: PromptUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + promptId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(promptId, PromptUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/prompt`, but is otherwise the same as + * [PromptServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(PromptListParams.none()) + + /** @see list */ + fun list( + params: PromptListParams = PromptListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: PromptListParams = PromptListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(PromptListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/prompt/{prompt_id}`, but is otherwise the + * same as [PromptServiceAsync.delete]. + */ + fun delete(promptId: String): CompletableFuture> = + delete(promptId, PromptDeleteParams.none()) + + /** @see delete */ + fun delete( + promptId: String, + params: PromptDeleteParams = PromptDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see delete */ + fun delete( + promptId: String, + params: PromptDeleteParams = PromptDeleteParams.none(), + ): CompletableFuture> = + delete(promptId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: PromptDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: PromptDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + promptId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(promptId, PromptDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/prompt`, but is otherwise the same as + * [PromptServiceAsync.replace]. + */ + fun replace(params: PromptReplaceParams): CompletableFuture> = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: PromptReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..bff1e648 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncImpl.kt @@ -0,0 +1,295 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.PromptUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class PromptServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + PromptServiceAsync { + + private val withRawResponse: PromptServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): PromptServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): PromptServiceAsync = + PromptServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: PromptCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/prompt + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: PromptRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/prompt/{prompt_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: PromptUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/prompt/{prompt_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: PromptListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/prompt + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: PromptDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/prompt/{prompt_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: PromptReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/prompt + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PromptServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): PromptServiceAsync.WithRawResponse = + PromptServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: PromptCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: PromptRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("promptId", params.promptId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: PromptUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("promptId", params.promptId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: PromptListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + PromptListPageAsync.builder() + .service(PromptServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: PromptDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("promptId", params.promptId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: PromptReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsync.kt new file mode 100755 index 00000000..7699d12a --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsync.kt @@ -0,0 +1,350 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.RoleListParams +import com.braintrustdata.api.models.RoleReplaceParams +import com.braintrustdata.api.models.RoleRetrieveParams +import com.braintrustdata.api.models.RoleUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface RoleServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): RoleServiceAsync + + /** + * Create a new role. If there is an existing role with the same name as the one specified in + * the request, will return the existing role unmodified + */ + fun create(params: RoleCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: RoleCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a role object by its id */ + fun retrieve(roleId: String): CompletableFuture = + retrieve(roleId, RoleRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + roleId: String, + params: RoleRetrieveParams = RoleRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = retrieve(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + roleId: String, + params: RoleRetrieveParams = RoleRetrieveParams.none(), + ): CompletableFuture = retrieve(roleId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: RoleRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: RoleRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(roleId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(roleId, RoleRetrieveParams.none(), requestOptions) + + /** + * Partially update a role object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields + * or setting them to null. + */ + fun update(roleId: String): CompletableFuture = update(roleId, RoleUpdateParams.none()) + + /** @see update */ + fun update( + roleId: String, + params: RoleUpdateParams = RoleUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = update(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see update */ + fun update( + roleId: String, + params: RoleUpdateParams = RoleUpdateParams.none(), + ): CompletableFuture = update(roleId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: RoleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: RoleUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(roleId: String, requestOptions: RequestOptions): CompletableFuture = + update(roleId, RoleUpdateParams.none(), requestOptions) + + /** + * List out all roles. The roles are sorted by creation date, with the most recently-created + * roles coming first + */ + fun list(): CompletableFuture = list(RoleListParams.none()) + + /** @see list */ + fun list( + params: RoleListParams = RoleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list(params: RoleListParams = RoleListParams.none()): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(RoleListParams.none(), requestOptions) + + /** Delete a role object by its id */ + fun delete(roleId: String): CompletableFuture = delete(roleId, RoleDeleteParams.none()) + + /** @see delete */ + fun delete( + roleId: String, + params: RoleDeleteParams = RoleDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see delete */ + fun delete( + roleId: String, + params: RoleDeleteParams = RoleDeleteParams.none(), + ): CompletableFuture = delete(roleId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: RoleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: RoleDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(roleId: String, requestOptions: RequestOptions): CompletableFuture = + delete(roleId, RoleDeleteParams.none(), requestOptions) + + /** + * Create or replace role. If there is an existing role with the same name as the one specified + * in the request, will replace the existing role with the provided fields + */ + fun replace(params: RoleReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: RoleReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [RoleServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): RoleServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/role`, but is otherwise the same as + * [RoleServiceAsync.create]. + */ + fun create(params: RoleCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: RoleCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/role/{role_id}`, but is otherwise the same as + * [RoleServiceAsync.retrieve]. + */ + fun retrieve(roleId: String): CompletableFuture> = + retrieve(roleId, RoleRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + roleId: String, + params: RoleRetrieveParams = RoleRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + roleId: String, + params: RoleRetrieveParams = RoleRetrieveParams.none(), + ): CompletableFuture> = + retrieve(roleId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: RoleRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: RoleRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + roleId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(roleId, RoleRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/role/{role_id}`, but is otherwise the same as + * [RoleServiceAsync.update]. + */ + fun update(roleId: String): CompletableFuture> = + update(roleId, RoleUpdateParams.none()) + + /** @see update */ + fun update( + roleId: String, + params: RoleUpdateParams = RoleUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see update */ + fun update( + roleId: String, + params: RoleUpdateParams = RoleUpdateParams.none(), + ): CompletableFuture> = update(roleId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: RoleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: RoleUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + roleId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(roleId, RoleUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/role`, but is otherwise the same as + * [RoleServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(RoleListParams.none()) + + /** @see list */ + fun list( + params: RoleListParams = RoleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: RoleListParams = RoleListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(RoleListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/role/{role_id}`, but is otherwise the same as + * [RoleServiceAsync.delete]. + */ + fun delete(roleId: String): CompletableFuture> = + delete(roleId, RoleDeleteParams.none()) + + /** @see delete */ + fun delete( + roleId: String, + params: RoleDeleteParams = RoleDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see delete */ + fun delete( + roleId: String, + params: RoleDeleteParams = RoleDeleteParams.none(), + ): CompletableFuture> = delete(roleId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: RoleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: RoleDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + roleId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(roleId, RoleDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/role`, but is otherwise the same as + * [RoleServiceAsync.replace]. + */ + fun replace(params: RoleReplaceParams): CompletableFuture> = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: RoleReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..304d8cb5 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncImpl.kt @@ -0,0 +1,295 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.RoleUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class RoleServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + RoleServiceAsync { + + private val withRawResponse: RoleServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): RoleServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): RoleServiceAsync = + RoleServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: RoleCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/role + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: RoleRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/role/{role_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: RoleUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/role/{role_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: RoleListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/role + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: RoleDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/role/{role_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: RoleReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/role + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + RoleServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): RoleServiceAsync.WithRawResponse = + RoleServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: RoleCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: RoleRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("roleId", params.roleId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: RoleUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("roleId", params.roleId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: RoleListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + RoleListPageAsync.builder() + .service(RoleServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: RoleDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("roleId", params.roleId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: RoleReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsync.kt new file mode 100644 index 00000000..ffb031b8 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsync.kt @@ -0,0 +1,374 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.SpanIframeListParams +import com.braintrustdata.api.models.SpanIframeReplaceParams +import com.braintrustdata.api.models.SpanIframeRetrieveParams +import com.braintrustdata.api.models.SpanIframeUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface SpanIframeServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): SpanIframeServiceAsync + + /** + * Create a new span_iframe. If there is an existing span_iframe with the same name as the one + * specified in the request, will return the existing span_iframe unmodified + */ + fun create(params: SpanIframeCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a span_iframe object by its id */ + fun retrieve(spanIframeId: String): CompletableFuture = + retrieve(spanIframeId, SpanIframeRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + retrieve(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + ): CompletableFuture = retrieve(spanIframeId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: SpanIframeRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + retrieve(spanIframeId, SpanIframeRetrieveParams.none(), requestOptions) + + /** + * Partially update a span_iframe object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(spanIframeId: String): CompletableFuture = + update(spanIframeId, SpanIframeUpdateParams.none()) + + /** @see update */ + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + update(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see update */ + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + ): CompletableFuture = update(spanIframeId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update(params: SpanIframeUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + spanIframeId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + update(spanIframeId, SpanIframeUpdateParams.none(), requestOptions) + + /** + * List out all span_iframes. The span_iframes are sorted by creation date, with the most + * recently-created span_iframes coming first + */ + fun list(): CompletableFuture = list(SpanIframeListParams.none()) + + /** @see list */ + fun list( + params: SpanIframeListParams = SpanIframeListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list( + params: SpanIframeListParams = SpanIframeListParams.none() + ): CompletableFuture = list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(SpanIframeListParams.none(), requestOptions) + + /** Delete a span_iframe object by its id */ + fun delete(spanIframeId: String): CompletableFuture = + delete(spanIframeId, SpanIframeDeleteParams.none()) + + /** @see delete */ + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + delete(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see delete */ + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + ): CompletableFuture = delete(spanIframeId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see delete */ + fun delete(params: SpanIframeDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + spanIframeId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + delete(spanIframeId, SpanIframeDeleteParams.none(), requestOptions) + + /** + * Create or replace span_iframe. If there is an existing span_iframe with the same name as the + * one specified in the request, will replace the existing span_iframe with the provided fields + */ + fun replace(params: SpanIframeReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * A view of [SpanIframeServiceAsync] that provides access to raw HTTP responses for each + * method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): SpanIframeServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/span_iframe`, but is otherwise the same as + * [SpanIframeServiceAsync.create]. + */ + fun create(params: SpanIframeCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/span_iframe/{span_iframe_id}`, but is otherwise + * the same as [SpanIframeServiceAsync.retrieve]. + */ + fun retrieve(spanIframeId: String): CompletableFuture> = + retrieve(spanIframeId, SpanIframeRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + ): CompletableFuture> = + retrieve(spanIframeId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve( + params: SpanIframeRetrieveParams + ): CompletableFuture> = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(spanIframeId, SpanIframeRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/span_iframe/{span_iframe_id}`, but is + * otherwise the same as [SpanIframeServiceAsync.update]. + */ + fun update(spanIframeId: String): CompletableFuture> = + update(spanIframeId, SpanIframeUpdateParams.none()) + + /** @see update */ + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see update */ + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + ): CompletableFuture> = + update(spanIframeId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update(params: SpanIframeUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + spanIframeId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + update(spanIframeId, SpanIframeUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/span_iframe`, but is otherwise the same as + * [SpanIframeServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(SpanIframeListParams.none()) + + /** @see list */ + fun list( + params: SpanIframeListParams = SpanIframeListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: SpanIframeListParams = SpanIframeListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(SpanIframeListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/span_iframe/{span_iframe_id}`, but is + * otherwise the same as [SpanIframeServiceAsync.delete]. + */ + fun delete(spanIframeId: String): CompletableFuture> = + delete(spanIframeId, SpanIframeDeleteParams.none()) + + /** @see delete */ + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see delete */ + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + ): CompletableFuture> = + delete(spanIframeId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see delete */ + fun delete(params: SpanIframeDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + spanIframeId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + delete(spanIframeId, SpanIframeDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/span_iframe`, but is otherwise the same as + * [SpanIframeServiceAsync.replace]. + */ + fun replace( + params: SpanIframeReplaceParams + ): CompletableFuture> = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100644 index 00000000..cde9bd46 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncImpl.kt @@ -0,0 +1,300 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.SpanIframeUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class SpanIframeServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + SpanIframeServiceAsync { + + private val withRawResponse: SpanIframeServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): SpanIframeServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): SpanIframeServiceAsync = + SpanIframeServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/span_iframe + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/span_iframe/{span_iframe_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/span_iframe/{span_iframe_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: SpanIframeListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/span_iframe + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/span_iframe/{span_iframe_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/span_iframe + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SpanIframeServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): SpanIframeServiceAsync.WithRawResponse = + SpanIframeServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("spanIframeId", params.spanIframeId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("spanIframeId", params.spanIframeId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: SpanIframeListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + SpanIframeListPageAsync.builder() + .service(SpanIframeServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("spanIframeId", params.spanIframeId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsync.kt old mode 100644 new mode 100755 index 14126ddc..27da770d --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsync.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsync.kt @@ -1,19 +1,80 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.async +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.models.TopLevelHelloWorldParams import java.util.concurrent.CompletableFuture +import java.util.function.Consumer interface TopLevelServiceAsync { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): TopLevelServiceAsync + /** Default endpoint. Simply replies with 'Hello, World!'. Authorization is not required */ - @JvmOverloads + fun helloWorld(): CompletableFuture = helloWorld(TopLevelHelloWorldParams.none()) + + /** @see helloWorld */ fun helloWorld( - params: TopLevelHelloWorldParams, - requestOptions: RequestOptions = RequestOptions.none() + params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + + /** @see helloWorld */ + fun helloWorld( + params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none() + ): CompletableFuture = helloWorld(params, RequestOptions.none()) + + /** @see helloWorld */ + fun helloWorld(requestOptions: RequestOptions): CompletableFuture = + helloWorld(TopLevelHelloWorldParams.none(), requestOptions) + + /** + * A view of [TopLevelServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): TopLevelServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1`, but is otherwise the same as + * [TopLevelServiceAsync.helloWorld]. + */ + fun helloWorld(): CompletableFuture> = + helloWorld(TopLevelHelloWorldParams.none()) + + /** @see helloWorld */ + fun helloWorld( + params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see helloWorld */ + fun helloWorld( + params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none() + ): CompletableFuture> = helloWorld(params, RequestOptions.none()) + + /** @see helloWorld */ + fun helloWorld(requestOptions: RequestOptions): CompletableFuture> = + helloWorld(TopLevelHelloWorldParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index 139e294b..89144d24 --- 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 @@ -4,41 +4,73 @@ package com.braintrustdata.api.services.async import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.stringHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.core.http.parseable +import com.braintrustdata.api.core.prepareAsync import com.braintrustdata.api.models.TopLevelHelloWorldParams -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.stringHandler -import com.braintrustdata.api.services.withErrorHandler import java.util.concurrent.CompletableFuture +import java.util.function.Consumer -class TopLevelServiceAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : TopLevelServiceAsync { +class TopLevelServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + TopLevelServiceAsync { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: TopLevelServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): TopLevelServiceAsync.WithRawResponse = withRawResponse - private val helloWorldHandler: Handler = stringHandler().withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): TopLevelServiceAsync = + TopLevelServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Default endpoint. Simply replies with 'Hello, World!'. Authorization is not required */ override fun helloWorld( params: TopLevelHelloWorldParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response.use { helloWorldHandler.handle(it) } + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1 + withRawResponse().helloWorld(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + TopLevelServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): TopLevelServiceAsync.WithRawResponse = + TopLevelServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val helloWorldHandler: Handler = stringHandler() + + override fun helloWorld( + params: TopLevelHelloWorldParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response.use { helloWorldHandler.handle(it) } + } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsync.kt new file mode 100755 index 00000000..a1609c69 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsync.kt @@ -0,0 +1,154 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.User +import com.braintrustdata.api.models.UserListPageAsync +import com.braintrustdata.api.models.UserListParams +import com.braintrustdata.api.models.UserRetrieveParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface UserServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UserServiceAsync + + /** Get a user object by its id */ + fun retrieve(userId: String): CompletableFuture = + retrieve(userId, UserRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + userId: String, + params: UserRetrieveParams = UserRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = retrieve(params.toBuilder().userId(userId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + userId: String, + params: UserRetrieveParams = UserRetrieveParams.none(), + ): CompletableFuture = retrieve(userId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: UserRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see retrieve */ + fun retrieve(params: UserRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(userId: String, requestOptions: RequestOptions): CompletableFuture = + retrieve(userId, UserRetrieveParams.none(), requestOptions) + + /** + * List out all users. The users are sorted by creation date, with the most recently-created + * users coming first + */ + fun list(): CompletableFuture = list(UserListParams.none()) + + /** @see list */ + fun list( + params: UserListParams = UserListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list(params: UserListParams = UserListParams.none()): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): CompletableFuture = + list(UserListParams.none(), requestOptions) + + /** A view of [UserServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UserServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/user/{user_id}`, but is otherwise the same as + * [UserServiceAsync.retrieve]. + */ + fun retrieve(userId: String): CompletableFuture> = + retrieve(userId, UserRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + userId: String, + params: UserRetrieveParams = UserRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().userId(userId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + userId: String, + params: UserRetrieveParams = UserRetrieveParams.none(), + ): CompletableFuture> = + retrieve(userId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: UserRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see retrieve */ + fun retrieve(params: UserRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + userId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + retrieve(userId, UserRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/user`, but is otherwise the same as + * [UserServiceAsync.list]. + */ + fun list(): CompletableFuture> = + list(UserListParams.none()) + + /** @see list */ + fun list( + params: UserListParams = UserListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: UserListParams = UserListParams.none() + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + requestOptions: RequestOptions + ): CompletableFuture> = + list(UserListParams.none(), requestOptions) + } +} 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 new file mode 100755 index 00000000..558d7631 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncImpl.kt @@ -0,0 +1,136 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +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.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 +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class UserServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + UserServiceAsync { + + private val withRawResponse: UserServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UserServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): UserServiceAsync = + UserServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun retrieve( + params: UserRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/user/{user_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: UserListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/user + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UserServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UserServiceAsync.WithRawResponse = + UserServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: UserRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("userId", params.userId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "user", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: UserListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "user") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + UserListPageAsync.builder() + .service(UserServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsync.kt new file mode 100755 index 00000000..b0a95453 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsync.kt @@ -0,0 +1,270 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ViewListParams +import com.braintrustdata.api.models.ViewReplaceParams +import com.braintrustdata.api.models.ViewRetrieveParams +import com.braintrustdata.api.models.ViewUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface ViewServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ViewServiceAsync + + /** + * Create a new view. If there is an existing view with the same name as the one specified in + * the request, will return the existing view unmodified + */ + fun create(params: ViewCreateParams): CompletableFuture = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ViewCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Get a view object by its id */ + fun retrieve(viewId: String, params: ViewRetrieveParams): CompletableFuture = + retrieve(viewId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + viewId: String, + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = retrieve(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve(params: ViewRetrieveParams): CompletableFuture = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * Partially update a view object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields + * or setting them to null. + */ + fun update(viewId: String, params: ViewUpdateParams): CompletableFuture = + update(viewId, params, RequestOptions.none()) + + /** @see update */ + fun update( + viewId: String, + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = update(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see update */ + fun update(params: ViewUpdateParams): CompletableFuture = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * List out all views. The views are sorted by creation date, with the most recently-created + * views coming first + */ + fun list(params: ViewListParams): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + params: ViewListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** Delete a view object by its id */ + fun delete(viewId: String, params: ViewDeleteParams): CompletableFuture = + delete(viewId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + viewId: String, + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = delete(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see delete */ + fun delete(params: ViewDeleteParams): CompletableFuture = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * Create or replace view. If there is an existing view with the same name as the one specified + * in the request, will replace the existing view with the provided fields + */ + fun replace(params: ViewReplaceParams): CompletableFuture = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ViewReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [ViewServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ViewServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/view`, but is otherwise the same as + * [ViewServiceAsync.create]. + */ + fun create(params: ViewCreateParams): CompletableFuture> = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ViewCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/view/{view_id}`, but is otherwise the same as + * [ViewServiceAsync.retrieve]. + */ + fun retrieve( + viewId: String, + params: ViewRetrieveParams, + ): CompletableFuture> = + retrieve(viewId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + viewId: String, + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + retrieve(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve(params: ViewRetrieveParams): CompletableFuture> = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `patch /v1/view/{view_id}`, but is otherwise the same as + * [ViewServiceAsync.update]. + */ + fun update( + viewId: String, + params: ViewUpdateParams, + ): CompletableFuture> = update(viewId, params, RequestOptions.none()) + + /** @see update */ + fun update( + viewId: String, + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + update(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see update */ + fun update(params: ViewUpdateParams): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/view`, but is otherwise the same as + * [ViewServiceAsync.list]. + */ + fun list(params: ViewListParams): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + params: ViewListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `delete /v1/view/{view_id}`, but is otherwise the same as + * [ViewServiceAsync.delete]. + */ + fun delete( + viewId: String, + params: ViewDeleteParams, + ): CompletableFuture> = delete(viewId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + viewId: String, + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + delete(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see delete */ + fun delete(params: ViewDeleteParams): CompletableFuture> = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `put /v1/view`, but is otherwise the same as + * [ViewServiceAsync.replace]. + */ + fun replace(params: ViewReplaceParams): CompletableFuture> = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ViewReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100755 index 00000000..b9e958a2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncImpl.kt @@ -0,0 +1,295 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.ViewUpdateParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ViewServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + ViewServiceAsync { + + private val withRawResponse: ViewServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ViewServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ViewServiceAsync = + ViewServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: ViewCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/view + withRawResponse().create(params, requestOptions).thenApply { it.parse() } + + override fun retrieve( + params: ViewRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/view/{view_id} + withRawResponse().retrieve(params, requestOptions).thenApply { it.parse() } + + override fun update( + params: ViewUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/view/{view_id} + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + override fun list( + params: ViewListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/view + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + + override fun delete( + params: ViewDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // delete /v1/view/{view_id} + withRawResponse().delete(params, requestOptions).thenApply { it.parse() } + + override fun replace( + params: ViewReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // put /v1/view + withRawResponse().replace(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ViewServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ViewServiceAsync.WithRawResponse = + ViewServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ViewCreateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ViewRetrieveParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("viewId", params.viewId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view", params._pathParam(0)) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: ViewUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("viewId", params.viewId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ViewListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ViewListPageAsync.builder() + .service(ViewServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ViewDeleteParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("viewId", params.viewId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: ViewReplaceParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsync.kt new file mode 100644 index 00000000..5caf9ef7 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsync.kt @@ -0,0 +1,85 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async.organizations + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.OrganizationMemberUpdateParams +import com.braintrustdata.api.models.PatchOrganizationMembersOutput +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface MemberServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): MemberServiceAsync + + /** Modify organization membership */ + fun update(): CompletableFuture = + update(OrganizationMemberUpdateParams.none()) + + /** @see update */ + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see update */ + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none() + ): CompletableFuture = update(params, RequestOptions.none()) + + /** @see update */ + fun update(requestOptions: RequestOptions): CompletableFuture = + update(OrganizationMemberUpdateParams.none(), requestOptions) + + /** + * A view of [MemberServiceAsync] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): MemberServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `patch /v1/organization/members`, but is otherwise the + * same as [MemberServiceAsync.update]. + */ + fun update(): CompletableFuture> = + update(OrganizationMemberUpdateParams.none()) + + /** @see update */ + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see update */ + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none() + ): CompletableFuture> = + update(params, RequestOptions.none()) + + /** @see update */ + fun update( + requestOptions: RequestOptions + ): CompletableFuture> = + update(OrganizationMemberUpdateParams.none(), requestOptions) + } +} 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 new file mode 100644 index 00000000..3a0b4d49 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncImpl.kt @@ -0,0 +1,86 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async.organizations + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.OrganizationMemberUpdateParams +import com.braintrustdata.api.models.PatchOrganizationMembersOutput +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +class MemberServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + MemberServiceAsync { + + private val withRawResponse: MemberServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): MemberServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): MemberServiceAsync = + MemberServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun update( + params: OrganizationMemberUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // patch /v1/organization/members + withRawResponse().update(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + MemberServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): MemberServiceAsync.WithRawResponse = + MemberServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: OrganizationMemberUpdateParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", "members") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/project/LogServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/project/LogServiceAsync.kt deleted file mode 100644 index 95824f98..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/project/LogServiceAsync.kt +++ /dev/null @@ -1,52 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - -package com.braintrustdata.api.services.async.project - -import com.braintrustdata.api.core.RequestOptions -import com.braintrustdata.api.models.ProjectLogFeedbackParams -import com.braintrustdata.api.models.ProjectLogFetchParams -import com.braintrustdata.api.models.ProjectLogFetchPostParams -import com.braintrustdata.api.models.ProjectLogFetchPostResponse -import com.braintrustdata.api.models.ProjectLogFetchResponse -import com.braintrustdata.api.models.ProjectLogInsertParams -import com.braintrustdata.api.models.ProjectLogInsertResponse -import java.util.concurrent.CompletableFuture - -interface LogServiceAsync { - - /** Log feedback for a set of project logs events */ - @JvmOverloads - fun feedback( - params: ProjectLogFeedbackParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture - - /** - * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with - * the parameters in the URL query rather than in the request body - */ - @JvmOverloads - fun fetch( - params: ProjectLogFetchParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture - - /** - * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - @JvmOverloads - fun fetchPost( - params: ProjectLogFetchPostParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture - - /** Insert a set of events into the project logs */ - @JvmOverloads - fun insert( - params: ProjectLogInsertParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/project/LogServiceAsyncImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/project/LogServiceAsyncImpl.kt deleted file mode 100644 index 6a308ba4..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/project/LogServiceAsyncImpl.kt +++ /dev/null @@ -1,148 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.services.async.project - -import com.braintrustdata.api.core.ClientOptions -import com.braintrustdata.api.core.RequestOptions -import com.braintrustdata.api.core.http.HttpMethod -import com.braintrustdata.api.core.http.HttpRequest -import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError -import com.braintrustdata.api.models.ProjectLogFeedbackParams -import com.braintrustdata.api.models.ProjectLogFetchParams -import com.braintrustdata.api.models.ProjectLogFetchPostParams -import com.braintrustdata.api.models.ProjectLogFetchPostResponse -import com.braintrustdata.api.models.ProjectLogFetchResponse -import com.braintrustdata.api.models.ProjectLogInsertParams -import com.braintrustdata.api.models.ProjectLogInsertResponse -import com.braintrustdata.api.services.emptyHandler -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler -import java.util.concurrent.CompletableFuture - -class LogServiceAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : LogServiceAsync { - - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val feedbackHandler: Handler = emptyHandler().withErrorHandler(errorHandler) - - /** Log feedback for a set of project logs events */ - override fun feedback( - params: ProjectLogFeedbackParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "feedback") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response.use { feedbackHandler.handle(it) } - } - } - - private val fetchHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with - * the parameters in the URL query rather than in the request body - */ - override fun fetch( - params: ProjectLogFetchParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { fetchHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } - - private val fetchPostHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - override fun fetchPost( - params: ProjectLogFetchPostParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { fetchPostHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } - - private val insertHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Insert a set of events into the project logs */ - override fun insert( - params: ProjectLogInsertParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "insert") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response - -> - response - .use { insertHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsync.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsync.kt new file mode 100644 index 00000000..1cb8326f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsync.kt @@ -0,0 +1,318 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async.projects + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchProjectLogsEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.ProjectLogFeedbackParams +import com.braintrustdata.api.models.ProjectLogFetchParams +import com.braintrustdata.api.models.ProjectLogFetchPostParams +import com.braintrustdata.api.models.ProjectLogInsertParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +interface LogServiceAsync { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): LogServiceAsync + + /** Log feedback for a set of project logs events */ + fun feedback( + projectId: String, + params: ProjectLogFeedbackParams, + ): CompletableFuture = + feedback(projectId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + projectId: String, + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + feedback(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see feedback */ + fun feedback(params: ProjectLogFeedbackParams): CompletableFuture = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** + * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with + * the parameters in the URL query rather than in the request body. For more complex queries, + * use the `POST /btql` endpoint. + */ + fun fetch(projectId: String): CompletableFuture = + fetch(projectId, ProjectLogFetchParams.none()) + + /** @see fetch */ + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + fetch(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + ): CompletableFuture = + fetch(projectId, params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see fetch */ + fun fetch(params: ProjectLogFetchParams): CompletableFuture = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + projectId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + fetch(projectId, ProjectLogFetchParams.none(), requestOptions) + + /** + * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the + * parameters in the request body rather than in the URL query. For more complex queries, use + * the `POST /btql` endpoint. + */ + fun fetchPost(projectId: String): CompletableFuture = + fetchPost(projectId, ProjectLogFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + fetchPost(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + ): CompletableFuture = + fetchPost(projectId, params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see fetchPost */ + fun fetchPost( + params: ProjectLogFetchPostParams + ): CompletableFuture = fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + fetchPost(projectId, ProjectLogFetchPostParams.none(), requestOptions) + + /** Insert a set of events into the project logs */ + fun insert( + projectId: String, + params: ProjectLogInsertParams, + ): CompletableFuture = insert(projectId, params, RequestOptions.none()) + + /** @see insert */ + fun insert( + projectId: String, + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + insert(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see insert */ + fun insert(params: ProjectLogInsertParams): CompletableFuture = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** A view of [LogServiceAsync] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): LogServiceAsync.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project_logs/{project_id}/feedback`, but is + * otherwise the same as [LogServiceAsync.feedback]. + */ + fun feedback( + projectId: String, + params: ProjectLogFeedbackParams, + ): CompletableFuture> = + feedback(projectId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + projectId: String, + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + feedback(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see feedback */ + fun feedback( + params: ProjectLogFeedbackParams + ): CompletableFuture> = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** + * Returns a raw HTTP response for `get /v1/project_logs/{project_id}/fetch`, but is + * otherwise the same as [LogServiceAsync.fetch]. + */ + fun fetch( + projectId: String + ): CompletableFuture> = + fetch(projectId, ProjectLogFetchParams.none()) + + /** @see fetch */ + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + fetch(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + ): CompletableFuture> = + fetch(projectId, params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see fetch */ + fun fetch( + params: ProjectLogFetchParams + ): CompletableFuture> = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + projectId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + fetch(projectId, ProjectLogFetchParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/project_logs/{project_id}/fetch`, but is + * otherwise the same as [LogServiceAsync.fetchPost]. + */ + fun fetchPost( + projectId: String + ): CompletableFuture> = + fetchPost(projectId, ProjectLogFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + fetchPost(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + ): CompletableFuture> = + fetchPost(projectId, params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see fetchPost */ + fun fetchPost( + params: ProjectLogFetchPostParams + ): CompletableFuture> = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + fetchPost(projectId, ProjectLogFetchPostParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/project_logs/{project_id}/insert`, but is + * otherwise the same as [LogServiceAsync.insert]. + */ + fun insert( + projectId: String, + params: ProjectLogInsertParams, + ): CompletableFuture> = + insert(projectId, params, RequestOptions.none()) + + /** @see insert */ + fun insert( + projectId: String, + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + insert(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see insert */ + fun insert( + params: ProjectLogInsertParams + ): CompletableFuture> = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + } +} 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 new file mode 100644 index 00000000..6a10c298 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncImpl.kt @@ -0,0 +1,218 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async.projects + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchProjectLogsEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.ProjectLogFeedbackParams +import com.braintrustdata.api.models.ProjectLogFetchParams +import com.braintrustdata.api.models.ProjectLogFetchPostParams +import com.braintrustdata.api.models.ProjectLogInsertParams +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class LogServiceAsyncImpl internal constructor(private val clientOptions: ClientOptions) : + LogServiceAsync { + + private val withRawResponse: LogServiceAsync.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): LogServiceAsync.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): LogServiceAsync = + LogServiceAsyncImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/project_logs/{project_id}/feedback + withRawResponse().feedback(params, requestOptions).thenApply { it.parse() } + + override fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /v1/project_logs/{project_id}/fetch + withRawResponse().fetch(params, requestOptions).thenApply { it.parse() } + + override fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/project_logs/{project_id}/fetch + withRawResponse().fetchPost(params, requestOptions).thenApply { it.parse() } + + override fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // post /v1/project_logs/{project_id}/insert + withRawResponse().insert(params, requestOptions).thenApply { it.parse() } + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + LogServiceAsync.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): LogServiceAsync.WithRawResponse = + LogServiceAsyncImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val feedbackHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "feedback") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { feedbackHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val fetchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { fetchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val fetchPostHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { fetchPostHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + + private val insertHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "insert") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { insertHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclService.kt new file mode 100755 index 00000000..7821eba9 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclService.kt @@ -0,0 +1,297 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.Acl +import com.braintrustdata.api.models.AclBatchUpdateParams +import com.braintrustdata.api.models.AclBatchUpdateResponse +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.AclListParams +import com.braintrustdata.api.models.AclRetrieveParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface AclService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AclService + + /** + * Create a new acl. If there is an existing acl with the same contents as the one specified in + * the request, will return the existing acl unmodified + */ + fun create(params: AclCreateParams): Acl = create(params, RequestOptions.none()) + + /** @see create */ + fun create(params: AclCreateParams, requestOptions: RequestOptions = RequestOptions.none()): Acl + + /** Get an acl object by its id */ + fun retrieve(aclId: String): Acl = retrieve(aclId, AclRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + aclId: String, + params: AclRetrieveParams = AclRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Acl = retrieve(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve(aclId: String, params: AclRetrieveParams = AclRetrieveParams.none()): Acl = + retrieve(aclId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: AclRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Acl + + /** @see retrieve */ + fun retrieve(params: AclRetrieveParams): Acl = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(aclId: String, requestOptions: RequestOptions): Acl = + retrieve(aclId, AclRetrieveParams.none(), requestOptions) + + /** + * List out all acls. The acls are sorted by creation date, with the most recently-created acls + * coming first + */ + fun list(params: AclListParams): AclListPage = list(params, RequestOptions.none()) + + /** @see list */ + fun list( + params: AclListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AclListPage + + /** Delete an acl object by its id */ + fun delete(aclId: String): Acl = delete(aclId, AclDeleteParams.none()) + + /** @see delete */ + fun delete( + aclId: String, + params: AclDeleteParams = AclDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Acl = delete(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see delete */ + fun delete(aclId: String, params: AclDeleteParams = AclDeleteParams.none()): Acl = + delete(aclId, params, RequestOptions.none()) + + /** @see delete */ + fun delete(params: AclDeleteParams, requestOptions: RequestOptions = RequestOptions.none()): Acl + + /** @see delete */ + fun delete(params: AclDeleteParams): Acl = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(aclId: String, requestOptions: RequestOptions): Acl = + delete(aclId, AclDeleteParams.none(), requestOptions) + + /** + * Batch update acls. This operation is idempotent, so adding acls which already exist will have + * no effect, and removing acls which do not exist will have no effect. + */ + fun batchUpdate(): AclBatchUpdateResponse = batchUpdate(AclBatchUpdateParams.none()) + + /** @see batchUpdate */ + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): AclBatchUpdateResponse + + /** @see batchUpdate */ + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none() + ): AclBatchUpdateResponse = batchUpdate(params, RequestOptions.none()) + + /** @see batchUpdate */ + fun batchUpdate(requestOptions: RequestOptions): AclBatchUpdateResponse = + batchUpdate(AclBatchUpdateParams.none(), requestOptions) + + /** Delete a single acl */ + fun findAndDelete(params: AclFindAndDeleteParams): Acl = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Acl + + /** A view of [AclService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AclService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/acl`, but is otherwise the same as + * [AclService.create]. + */ + @MustBeClosed + fun create(params: AclCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: AclCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/acl/{acl_id}`, but is otherwise the same as + * [AclService.retrieve]. + */ + @MustBeClosed + fun retrieve(aclId: String): HttpResponseFor = + retrieve(aclId, AclRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + aclId: String, + params: AclRetrieveParams = AclRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = retrieve(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + aclId: String, + params: AclRetrieveParams = AclRetrieveParams.none(), + ): HttpResponseFor = retrieve(aclId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: AclRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: AclRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(aclId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(aclId, AclRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/acl`, but is otherwise the same as + * [AclService.list]. + */ + @MustBeClosed + fun list(params: AclListParams): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: AclListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `delete /v1/acl/{acl_id}`, but is otherwise the same as + * [AclService.delete]. + */ + @MustBeClosed + fun delete(aclId: String): HttpResponseFor = delete(aclId, AclDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + aclId: String, + params: AclDeleteParams = AclDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = delete(params.toBuilder().aclId(aclId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + aclId: String, + params: AclDeleteParams = AclDeleteParams.none(), + ): HttpResponseFor = delete(aclId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: AclDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: AclDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(aclId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(aclId, AclDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/acl/batch_update`, but is otherwise the same as + * [AclService.batchUpdate]. + */ + @MustBeClosed + fun batchUpdate(): HttpResponseFor = + batchUpdate(AclBatchUpdateParams.none()) + + /** @see batchUpdate */ + @MustBeClosed + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see batchUpdate */ + @MustBeClosed + fun batchUpdate( + params: AclBatchUpdateParams = AclBatchUpdateParams.none() + ): HttpResponseFor = batchUpdate(params, RequestOptions.none()) + + /** @see batchUpdate */ + @MustBeClosed + fun batchUpdate(requestOptions: RequestOptions): HttpResponseFor = + batchUpdate(AclBatchUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/acl`, but is otherwise the same as + * [AclService.findAndDelete]. + */ + @MustBeClosed + fun findAndDelete(params: AclFindAndDeleteParams): HttpResponseFor = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + @MustBeClosed + fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..ccff6e0c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AclServiceImpl.kt @@ -0,0 +1,261 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.Acl +import com.braintrustdata.api.models.AclBatchUpdateParams +import com.braintrustdata.api.models.AclBatchUpdateResponse +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 +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class AclServiceImpl internal constructor(private val clientOptions: ClientOptions) : AclService { + + private val withRawResponse: AclService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AclService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AclService = + AclServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: AclCreateParams, requestOptions: RequestOptions): Acl = + // post /v1/acl + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: AclRetrieveParams, requestOptions: RequestOptions): Acl = + // get /v1/acl/{acl_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun list(params: AclListParams, requestOptions: RequestOptions): AclListPage = + // get /v1/acl + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: AclDeleteParams, requestOptions: RequestOptions): Acl = + // delete /v1/acl/{acl_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun batchUpdate( + params: AclBatchUpdateParams, + requestOptions: RequestOptions, + ): AclBatchUpdateResponse = + // post /v1/acl/batch_update + withRawResponse().batchUpdate(params, requestOptions).parse() + + override fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions, + ): Acl = + // delete /v1/acl + withRawResponse().findAndDelete(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AclService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AclService.WithRawResponse = + AclServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: AclCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: AclRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aclId", params.aclId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: AclListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + AclListPage.builder() + .service(AclServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: AclDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aclId", params.aclId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val batchUpdateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun batchUpdate( + params: AclBatchUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl", "batch_update") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { batchUpdateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val findAndDeleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun findAndDelete( + params: AclFindAndDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "acl") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { findAndDeleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretService.kt new file mode 100644 index 00000000..d514dc2f --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretService.kt @@ -0,0 +1,385 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.AiSecretListParams +import com.braintrustdata.api.models.AiSecretReplaceParams +import com.braintrustdata.api.models.AiSecretRetrieveParams +import com.braintrustdata.api.models.AiSecretUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface AiSecretService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AiSecretService + + /** + * Create a new ai_secret. If there is an existing ai_secret with the same name as the one + * specified in the request, will return the existing ai_secret unmodified + */ + fun create(params: AiSecretCreateParams): AISecret = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: AiSecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret + + /** Get an ai_secret object by its id */ + fun retrieve(aiSecretId: String): AISecret = retrieve(aiSecretId, AiSecretRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret = retrieve(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + ): AISecret = retrieve(aiSecretId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret + + /** @see retrieve */ + fun retrieve(params: AiSecretRetrieveParams): AISecret = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(aiSecretId: String, requestOptions: RequestOptions): AISecret = + retrieve(aiSecretId, AiSecretRetrieveParams.none(), requestOptions) + + /** + * Partially update an ai_secret object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(aiSecretId: String): AISecret = update(aiSecretId, AiSecretUpdateParams.none()) + + /** @see update */ + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret = update(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see update */ + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + ): AISecret = update(aiSecretId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: AiSecretUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret + + /** @see update */ + fun update(params: AiSecretUpdateParams): AISecret = update(params, RequestOptions.none()) + + /** @see update */ + fun update(aiSecretId: String, requestOptions: RequestOptions): AISecret = + update(aiSecretId, AiSecretUpdateParams.none(), requestOptions) + + /** + * List out all ai_secrets. The ai_secrets are sorted by creation date, with the most + * recently-created ai_secrets coming first + */ + fun list(): AiSecretListPage = list(AiSecretListParams.none()) + + /** @see list */ + fun list( + params: AiSecretListParams = AiSecretListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): AiSecretListPage + + /** @see list */ + fun list(params: AiSecretListParams = AiSecretListParams.none()): AiSecretListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): AiSecretListPage = + list(AiSecretListParams.none(), requestOptions) + + /** Delete an ai_secret object by its id */ + fun delete(aiSecretId: String): AISecret = delete(aiSecretId, AiSecretDeleteParams.none()) + + /** @see delete */ + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret = delete(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see delete */ + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + ): AISecret = delete(aiSecretId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: AiSecretDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret + + /** @see delete */ + fun delete(params: AiSecretDeleteParams): AISecret = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(aiSecretId: String, requestOptions: RequestOptions): AISecret = + delete(aiSecretId, AiSecretDeleteParams.none(), requestOptions) + + /** Delete a single ai_secret */ + fun findAndDelete(params: AiSecretFindAndDeleteParams): AISecret = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret + + /** + * Create or replace ai_secret. If there is an existing ai_secret with the same name as the one + * specified in the request, will replace the existing ai_secret with the provided fields + */ + fun replace(params: AiSecretReplaceParams): AISecret = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: AiSecretReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): AISecret + + /** A view of [AiSecretService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): AiSecretService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/ai_secret`, but is otherwise the same as + * [AiSecretService.create]. + */ + @MustBeClosed + fun create(params: AiSecretCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: AiSecretCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/ai_secret/{ai_secret_id}`, but is otherwise the + * same as [AiSecretService.retrieve]. + */ + @MustBeClosed + fun retrieve(aiSecretId: String): HttpResponseFor = + retrieve(aiSecretId, AiSecretRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + aiSecretId: String, + params: AiSecretRetrieveParams = AiSecretRetrieveParams.none(), + ): HttpResponseFor = retrieve(aiSecretId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: AiSecretRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + aiSecretId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + retrieve(aiSecretId, AiSecretRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/ai_secret/{ai_secret_id}`, but is otherwise + * the same as [AiSecretService.update]. + */ + @MustBeClosed + fun update(aiSecretId: String): HttpResponseFor = + update(aiSecretId, AiSecretUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + aiSecretId: String, + params: AiSecretUpdateParams = AiSecretUpdateParams.none(), + ): HttpResponseFor = update(aiSecretId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: AiSecretUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: AiSecretUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update(aiSecretId: String, requestOptions: RequestOptions): HttpResponseFor = + update(aiSecretId, AiSecretUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/ai_secret`, but is otherwise the same as + * [AiSecretService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(AiSecretListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: AiSecretListParams = AiSecretListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: AiSecretListParams = AiSecretListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(AiSecretListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/ai_secret/{ai_secret_id}`, but is otherwise + * the same as [AiSecretService.delete]. + */ + @MustBeClosed + fun delete(aiSecretId: String): HttpResponseFor = + delete(aiSecretId, AiSecretDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().aiSecretId(aiSecretId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + aiSecretId: String, + params: AiSecretDeleteParams = AiSecretDeleteParams.none(), + ): HttpResponseFor = delete(aiSecretId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: AiSecretDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: AiSecretDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(aiSecretId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(aiSecretId, AiSecretDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/ai_secret`, but is otherwise the same as + * [AiSecretService.findAndDelete]. + */ + @MustBeClosed + fun findAndDelete(params: AiSecretFindAndDeleteParams): HttpResponseFor = + findAndDelete(params, RequestOptions.none()) + + /** @see findAndDelete */ + @MustBeClosed + fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `put /v1/ai_secret`, but is otherwise the same as + * [AiSecretService.replace]. + */ + @MustBeClosed + fun replace(params: AiSecretReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: AiSecretReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100644 index 00000000..d93a7fcd --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceImpl.kt @@ -0,0 +1,304 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.AiSecretUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class AiSecretServiceImpl internal constructor(private val clientOptions: ClientOptions) : + AiSecretService { + + private val withRawResponse: AiSecretService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): AiSecretService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): AiSecretService = + AiSecretServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: AiSecretCreateParams, requestOptions: RequestOptions): AISecret = + // post /v1/ai_secret + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions, + ): AISecret = + // get /v1/ai_secret/{ai_secret_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: AiSecretUpdateParams, requestOptions: RequestOptions): AISecret = + // patch /v1/ai_secret/{ai_secret_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: AiSecretListParams, + requestOptions: RequestOptions, + ): AiSecretListPage = + // get /v1/ai_secret + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: AiSecretDeleteParams, requestOptions: RequestOptions): AISecret = + // delete /v1/ai_secret/{ai_secret_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions, + ): AISecret = + // delete /v1/ai_secret + withRawResponse().findAndDelete(params, requestOptions).parse() + + override fun replace(params: AiSecretReplaceParams, requestOptions: RequestOptions): AISecret = + // put /v1/ai_secret + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + AiSecretService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): AiSecretService.WithRawResponse = + AiSecretServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: AiSecretCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: AiSecretRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aiSecretId", params.aiSecretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: AiSecretUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aiSecretId", params.aiSecretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: AiSecretListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + AiSecretListPage.builder() + .service(AiSecretServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: AiSecretDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("aiSecretId", params.aiSecretId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val findAndDeleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun findAndDelete( + params: AiSecretFindAndDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { findAndDeleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: AiSecretReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "ai_secret") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyService.kt new file mode 100644 index 00000000..7955b47d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyService.kt @@ -0,0 +1,252 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ApiKeyListParams +import com.braintrustdata.api.models.ApiKeyRetrieveParams +import com.braintrustdata.api.models.CreateApiKeyOutput +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface ApiKeyService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ApiKeyService + + /** + * Create a new api_key. It is possible to have multiple API keys with the same name. There is + * no de-duplication + */ + fun create(params: ApiKeyCreateParams): CreateApiKeyOutput = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CreateApiKeyOutput + + /** Get an api_key object by its id */ + fun retrieve(apiKeyId: String): ApiKey = retrieve(apiKeyId, ApiKeyRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ApiKey = retrieve(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + ): ApiKey = retrieve(apiKeyId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ApiKeyRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ApiKey + + /** @see retrieve */ + fun retrieve(params: ApiKeyRetrieveParams): ApiKey = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(apiKeyId: String, requestOptions: RequestOptions): ApiKey = + retrieve(apiKeyId, ApiKeyRetrieveParams.none(), requestOptions) + + /** + * List out all api_keys. The api_keys are sorted by creation date, with the most + * recently-created api_keys coming first + */ + fun list(): ApiKeyListPage = list(ApiKeyListParams.none()) + + /** @see list */ + fun list( + params: ApiKeyListParams = ApiKeyListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ApiKeyListPage + + /** @see list */ + fun list(params: ApiKeyListParams = ApiKeyListParams.none()): ApiKeyListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): ApiKeyListPage = + list(ApiKeyListParams.none(), requestOptions) + + /** Delete an api_key object by its id */ + fun delete(apiKeyId: String): ApiKey = delete(apiKeyId, ApiKeyDeleteParams.none()) + + /** @see delete */ + fun delete( + apiKeyId: String, + params: ApiKeyDeleteParams = ApiKeyDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ApiKey = delete(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see delete */ + fun delete(apiKeyId: String, params: ApiKeyDeleteParams = ApiKeyDeleteParams.none()): ApiKey = + delete(apiKeyId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ApiKeyDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ApiKey + + /** @see delete */ + fun delete(params: ApiKeyDeleteParams): ApiKey = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(apiKeyId: String, requestOptions: RequestOptions): ApiKey = + delete(apiKeyId, ApiKeyDeleteParams.none(), requestOptions) + + /** A view of [ApiKeyService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ApiKeyService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/api_key`, but is otherwise the same as + * [ApiKeyService.create]. + */ + @MustBeClosed + fun create(params: ApiKeyCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/api_key/{api_key_id}`, but is otherwise the same + * as [ApiKeyService.retrieve]. + */ + @MustBeClosed + fun retrieve(apiKeyId: String): HttpResponseFor = + retrieve(apiKeyId, ApiKeyRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + apiKeyId: String, + params: ApiKeyRetrieveParams = ApiKeyRetrieveParams.none(), + ): HttpResponseFor = retrieve(apiKeyId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: ApiKeyRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: ApiKeyRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(apiKeyId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(apiKeyId, ApiKeyRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/api_key`, but is otherwise the same as + * [ApiKeyService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(ApiKeyListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ApiKeyListParams = ApiKeyListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: ApiKeyListParams = ApiKeyListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ApiKeyListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/api_key/{api_key_id}`, but is otherwise the + * same as [ApiKeyService.delete]. + */ + @MustBeClosed + fun delete(apiKeyId: String): HttpResponseFor = + delete(apiKeyId, ApiKeyDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + apiKeyId: String, + params: ApiKeyDeleteParams = ApiKeyDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().apiKeyId(apiKeyId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + apiKeyId: String, + params: ApiKeyDeleteParams = ApiKeyDeleteParams.none(), + ): HttpResponseFor = delete(apiKeyId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: ApiKeyDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: ApiKeyDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(apiKeyId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(apiKeyId, ApiKeyDeleteParams.none(), requestOptions) + } +} 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 new file mode 100644 index 00000000..9f803003 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceImpl.kt @@ -0,0 +1,195 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ApiKeyServiceImpl internal constructor(private val clientOptions: ClientOptions) : + ApiKeyService { + + private val withRawResponse: ApiKeyService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ApiKeyService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ApiKeyService = + ApiKeyServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions, + ): CreateApiKeyOutput = + // post /v1/api_key + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: ApiKeyRetrieveParams, requestOptions: RequestOptions): ApiKey = + // get /v1/api_key/{api_key_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun list(params: ApiKeyListParams, requestOptions: RequestOptions): ApiKeyListPage = + // get /v1/api_key + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: ApiKeyDeleteParams, requestOptions: RequestOptions): ApiKey = + // delete /v1/api_key/{api_key_id} + withRawResponse().delete(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ApiKeyService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ApiKeyService.WithRawResponse = + ApiKeyServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ApiKeyCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ApiKeyRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("apiKeyId", params.apiKeyId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ApiKeyListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ApiKeyListPage.builder() + .service(ApiKeyServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ApiKeyDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("apiKeyId", params.apiKeyId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "api_key", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetService.kt old mode 100644 new mode 100755 index afd96996..0caaa200 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetService.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/DatasetService.kt @@ -1,116 +1,682 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.blocking +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.models.Dataset import com.braintrustdata.api.models.DatasetCreateParams import com.braintrustdata.api.models.DatasetDeleteParams import com.braintrustdata.api.models.DatasetFeedbackParams import com.braintrustdata.api.models.DatasetFetchParams import com.braintrustdata.api.models.DatasetFetchPostParams -import com.braintrustdata.api.models.DatasetFetchPostResponse -import com.braintrustdata.api.models.DatasetFetchResponse import com.braintrustdata.api.models.DatasetInsertParams -import com.braintrustdata.api.models.DatasetInsertResponse import com.braintrustdata.api.models.DatasetListPage import com.braintrustdata.api.models.DatasetListParams -import com.braintrustdata.api.models.DatasetReplaceParams import com.braintrustdata.api.models.DatasetRetrieveParams +import com.braintrustdata.api.models.DatasetSummarizeParams import com.braintrustdata.api.models.DatasetUpdateParams +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchDatasetEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeDatasetResponse +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer interface DatasetService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): DatasetService + /** * Create a new dataset. If there is an existing dataset in the project with the same name as * the one specified in the request, will return the existing dataset unmodified */ - @JvmOverloads + fun create(params: DatasetCreateParams): Dataset = create(params, RequestOptions.none()) + + /** @see create */ fun create( params: DatasetCreateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Dataset /** Get a dataset object by its id */ - @JvmOverloads + fun retrieve(datasetId: String): Dataset = retrieve(datasetId, DatasetRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Dataset = retrieve(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + ): Dataset = retrieve(datasetId, params, RequestOptions.none()) + + /** @see retrieve */ fun retrieve( params: DatasetRetrieveParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Dataset + /** @see retrieve */ + fun retrieve(params: DatasetRetrieveParams): Dataset = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(datasetId: String, requestOptions: RequestOptions): Dataset = + retrieve(datasetId, DatasetRetrieveParams.none(), requestOptions) + /** * Partially update a dataset object. Specify the fields to update in the payload. Any * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /dataset/{id}` and then replace it with `PUT /dataset`. + * removing fields or setting them to null. */ - @JvmOverloads + fun update(datasetId: String): Dataset = update(datasetId, DatasetUpdateParams.none()) + + /** @see update */ + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Dataset = update(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see update */ + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + ): Dataset = update(datasetId, params, RequestOptions.none()) + + /** @see update */ fun update( params: DatasetUpdateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Dataset + /** @see update */ + fun update(params: DatasetUpdateParams): Dataset = update(params, RequestOptions.none()) + + /** @see update */ + fun update(datasetId: String, requestOptions: RequestOptions): Dataset = + update(datasetId, DatasetUpdateParams.none(), requestOptions) + /** * List out all datasets. The datasets are sorted by creation date, with the most * recently-created datasets coming first */ - @JvmOverloads + fun list(): DatasetListPage = list(DatasetListParams.none()) + + /** @see list */ fun list( - params: DatasetListParams, - requestOptions: RequestOptions = RequestOptions.none() + params: DatasetListParams = DatasetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): DatasetListPage + /** @see list */ + fun list(params: DatasetListParams = DatasetListParams.none()): DatasetListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): DatasetListPage = + list(DatasetListParams.none(), requestOptions) + /** Delete a dataset object by its id */ - @JvmOverloads + fun delete(datasetId: String): Dataset = delete(datasetId, DatasetDeleteParams.none()) + + /** @see delete */ + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Dataset = delete(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see delete */ + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + ): Dataset = delete(datasetId, params, RequestOptions.none()) + + /** @see delete */ fun delete( params: DatasetDeleteParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Dataset + /** @see delete */ + fun delete(params: DatasetDeleteParams): Dataset = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(datasetId: String, requestOptions: RequestOptions): Dataset = + delete(datasetId, DatasetDeleteParams.none(), requestOptions) + /** Log feedback for a set of dataset events */ - @JvmOverloads + fun feedback(datasetId: String, params: DatasetFeedbackParams): FeedbackResponseSchema = + feedback(datasetId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + datasetId: String, + params: DatasetFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FeedbackResponseSchema = + feedback(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see feedback */ + fun feedback(params: DatasetFeedbackParams): FeedbackResponseSchema = + feedback(params, RequestOptions.none()) + + /** @see feedback */ fun feedback( params: DatasetFeedbackParams, - requestOptions: RequestOptions = RequestOptions.none() - ) + requestOptions: RequestOptions = RequestOptions.none(), + ): FeedbackResponseSchema /** * Fetch the events in a dataset. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body + * parameters in the URL query rather than in the request body. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetch(datasetId: String): FetchDatasetEventsResponse = + fetch(datasetId, DatasetFetchParams.none()) + + /** @see fetch */ + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchDatasetEventsResponse = + fetch(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + ): FetchDatasetEventsResponse = fetch(datasetId, params, RequestOptions.none()) + + /** @see fetch */ fun fetch( params: DatasetFetchParams, - requestOptions: RequestOptions = RequestOptions.none() - ): DatasetFetchResponse + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchDatasetEventsResponse + + /** @see fetch */ + fun fetch(params: DatasetFetchParams): FetchDatasetEventsResponse = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch(datasetId: String, requestOptions: RequestOptions): FetchDatasetEventsResponse = + fetch(datasetId, DatasetFetchParams.none(), requestOptions) /** * Fetch the events in a dataset. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query + * parameters in the request body rather than in the URL query. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetchPost(datasetId: String): FetchDatasetEventsResponse = + fetchPost(datasetId, DatasetFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchDatasetEventsResponse = + fetchPost(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + ): FetchDatasetEventsResponse = fetchPost(datasetId, params, RequestOptions.none()) + + /** @see fetchPost */ fun fetchPost( params: DatasetFetchPostParams, - requestOptions: RequestOptions = RequestOptions.none() - ): DatasetFetchPostResponse + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchDatasetEventsResponse + + /** @see fetchPost */ + fun fetchPost(params: DatasetFetchPostParams): FetchDatasetEventsResponse = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost(datasetId: String, requestOptions: RequestOptions): FetchDatasetEventsResponse = + fetchPost(datasetId, DatasetFetchPostParams.none(), requestOptions) /** Insert a set of events into the dataset */ - @JvmOverloads + fun insert(datasetId: String, params: DatasetInsertParams): InsertEventsResponse = + insert(datasetId, params, RequestOptions.none()) + + /** @see insert */ fun insert( + datasetId: String, params: DatasetInsertParams, - requestOptions: RequestOptions = RequestOptions.none() - ): DatasetInsertResponse + requestOptions: RequestOptions = RequestOptions.none(), + ): InsertEventsResponse = + insert(params.toBuilder().datasetId(datasetId).build(), requestOptions) - /** - * Create or replace a new dataset. If there is an existing dataset in the project with the same - * name as the one specified in the request, will replace the existing dataset with the provided - * fields - */ - @JvmOverloads - fun replace( - params: DatasetReplaceParams, - requestOptions: RequestOptions = RequestOptions.none() - ): Dataset + /** @see insert */ + fun insert(params: DatasetInsertParams): InsertEventsResponse = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): InsertEventsResponse + + /** Summarize dataset */ + fun summarize(datasetId: String): SummarizeDatasetResponse = + summarize(datasetId, DatasetSummarizeParams.none()) + + /** @see summarize */ + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): SummarizeDatasetResponse = + summarize(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see summarize */ + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + ): SummarizeDatasetResponse = summarize(datasetId, params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SummarizeDatasetResponse + + /** @see summarize */ + fun summarize(params: DatasetSummarizeParams): SummarizeDatasetResponse = + summarize(params, RequestOptions.none()) + + /** @see summarize */ + fun summarize(datasetId: String, requestOptions: RequestOptions): SummarizeDatasetResponse = + summarize(datasetId, DatasetSummarizeParams.none(), requestOptions) + + /** A view of [DatasetService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): DatasetService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/dataset`, but is otherwise the same as + * [DatasetService.create]. + */ + @MustBeClosed + fun create(params: DatasetCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: DatasetCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/dataset/{dataset_id}`, but is otherwise the same + * as [DatasetService.retrieve]. + */ + @MustBeClosed + fun retrieve(datasetId: String): HttpResponseFor = + retrieve(datasetId, DatasetRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + datasetId: String, + params: DatasetRetrieveParams = DatasetRetrieveParams.none(), + ): HttpResponseFor = retrieve(datasetId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: DatasetRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: DatasetRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(datasetId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(datasetId, DatasetRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/dataset/{dataset_id}`, but is otherwise the + * same as [DatasetService.update]. + */ + @MustBeClosed + fun update(datasetId: String): HttpResponseFor = + update(datasetId, DatasetUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + datasetId: String, + params: DatasetUpdateParams = DatasetUpdateParams.none(), + ): HttpResponseFor = update(datasetId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: DatasetUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: DatasetUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update(datasetId: String, requestOptions: RequestOptions): HttpResponseFor = + update(datasetId, DatasetUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/dataset`, but is otherwise the same as + * [DatasetService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(DatasetListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: DatasetListParams = DatasetListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: DatasetListParams = DatasetListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(DatasetListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/dataset/{dataset_id}`, but is otherwise the + * same as [DatasetService.delete]. + */ + @MustBeClosed + fun delete(datasetId: String): HttpResponseFor = + delete(datasetId, DatasetDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + datasetId: String, + params: DatasetDeleteParams = DatasetDeleteParams.none(), + ): HttpResponseFor = delete(datasetId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: DatasetDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: DatasetDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(datasetId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(datasetId, DatasetDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/dataset/{dataset_id}/feedback`, but is + * otherwise the same as [DatasetService.feedback]. + */ + @MustBeClosed + fun feedback( + datasetId: String, + params: DatasetFeedbackParams, + ): HttpResponseFor = + feedback(datasetId, params, RequestOptions.none()) + + /** @see feedback */ + @MustBeClosed + fun feedback( + datasetId: String, + params: DatasetFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + feedback(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see feedback */ + @MustBeClosed + fun feedback(params: DatasetFeedbackParams): HttpResponseFor = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + @MustBeClosed + fun feedback( + params: DatasetFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/dataset/{dataset_id}/fetch`, but is otherwise + * the same as [DatasetService.fetch]. + */ + @MustBeClosed + fun fetch(datasetId: String): HttpResponseFor = + fetch(datasetId, DatasetFetchParams.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + fetch(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetch */ + @MustBeClosed + fun fetch( + datasetId: String, + params: DatasetFetchParams = DatasetFetchParams.none(), + ): HttpResponseFor = + fetch(datasetId, params, RequestOptions.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + params: DatasetFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see fetch */ + @MustBeClosed + fun fetch(params: DatasetFetchParams): HttpResponseFor = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + datasetId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + fetch(datasetId, DatasetFetchParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/dataset/{dataset_id}/fetch`, but is otherwise + * the same as [DatasetService.fetchPost]. + */ + @MustBeClosed + fun fetchPost(datasetId: String): HttpResponseFor = + fetchPost(datasetId, DatasetFetchPostParams.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + fetchPost(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + datasetId: String, + params: DatasetFetchPostParams = DatasetFetchPostParams.none(), + ): HttpResponseFor = + fetchPost(datasetId, params, RequestOptions.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + params: DatasetFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost(params: DatasetFetchPostParams): HttpResponseFor = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + datasetId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + fetchPost(datasetId, DatasetFetchPostParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/dataset/{dataset_id}/insert`, but is otherwise + * the same as [DatasetService.insert]. + */ + @MustBeClosed + fun insert( + datasetId: String, + params: DatasetInsertParams, + ): HttpResponseFor = insert(datasetId, params, RequestOptions.none()) + + /** @see insert */ + @MustBeClosed + fun insert( + datasetId: String, + params: DatasetInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + insert(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see insert */ + @MustBeClosed + fun insert(params: DatasetInsertParams): HttpResponseFor = + insert(params, RequestOptions.none()) + + /** @see insert */ + @MustBeClosed + fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/dataset/{dataset_id}/summarize`, but is + * otherwise the same as [DatasetService.summarize]. + */ + @MustBeClosed + fun summarize(datasetId: String): HttpResponseFor = + summarize(datasetId, DatasetSummarizeParams.none()) + + /** @see summarize */ + @MustBeClosed + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + summarize(params.toBuilder().datasetId(datasetId).build(), requestOptions) + + /** @see summarize */ + @MustBeClosed + fun summarize( + datasetId: String, + params: DatasetSummarizeParams = DatasetSummarizeParams.none(), + ): HttpResponseFor = + summarize(datasetId, params, RequestOptions.none()) + + /** @see summarize */ + @MustBeClosed + fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see summarize */ + @MustBeClosed + fun summarize(params: DatasetSummarizeParams): HttpResponseFor = + summarize(params, RequestOptions.none()) + + /** @see summarize */ + @MustBeClosed + fun summarize( + datasetId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + summarize(datasetId, DatasetSummarizeParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index 14f00e36..e1691602 --- 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 @@ -4,308 +4,420 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +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.models.Dataset import com.braintrustdata.api.models.DatasetCreateParams import com.braintrustdata.api.models.DatasetDeleteParams import com.braintrustdata.api.models.DatasetFeedbackParams import com.braintrustdata.api.models.DatasetFetchParams import com.braintrustdata.api.models.DatasetFetchPostParams -import com.braintrustdata.api.models.DatasetFetchPostResponse -import com.braintrustdata.api.models.DatasetFetchResponse import com.braintrustdata.api.models.DatasetInsertParams -import com.braintrustdata.api.models.DatasetInsertResponse import com.braintrustdata.api.models.DatasetListPage +import com.braintrustdata.api.models.DatasetListPageResponse import com.braintrustdata.api.models.DatasetListParams -import com.braintrustdata.api.models.DatasetReplaceParams import com.braintrustdata.api.models.DatasetRetrieveParams +import com.braintrustdata.api.models.DatasetSummarizeParams import com.braintrustdata.api.models.DatasetUpdateParams -import com.braintrustdata.api.services.emptyHandler -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler - -class DatasetServiceImpl -constructor( - private val clientOptions: ClientOptions, -) : DatasetService { - - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create a new dataset. If there is an existing dataset in the project with the same name as - * the one specified in the request, will return the existing dataset unmodified - */ - override fun create(params: DatasetCreateParams, requestOptions: RequestOptions): Dataset { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchDatasetEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeDatasetResponse +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class DatasetServiceImpl internal constructor(private val clientOptions: ClientOptions) : + DatasetService { + + private val withRawResponse: DatasetService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): DatasetService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): DatasetService = + DatasetServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: DatasetCreateParams, requestOptions: RequestOptions): Dataset = + // post /v1/dataset + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: DatasetRetrieveParams, requestOptions: RequestOptions): Dataset = + // get /v1/dataset/{dataset_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: DatasetUpdateParams, requestOptions: RequestOptions): Dataset = + // patch /v1/dataset/{dataset_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list(params: DatasetListParams, requestOptions: RequestOptions): DatasetListPage = + // get /v1/dataset + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: DatasetDeleteParams, requestOptions: RequestOptions): Dataset = + // delete /v1/dataset/{dataset_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun feedback( + params: DatasetFeedbackParams, + requestOptions: RequestOptions, + ): FeedbackResponseSchema = + // post /v1/dataset/{dataset_id}/feedback + withRawResponse().feedback(params, requestOptions).parse() + + override fun fetch( + params: DatasetFetchParams, + requestOptions: RequestOptions, + ): FetchDatasetEventsResponse = + // get /v1/dataset/{dataset_id}/fetch + withRawResponse().fetch(params, requestOptions).parse() + + override fun fetchPost( + params: DatasetFetchPostParams, + requestOptions: RequestOptions, + ): FetchDatasetEventsResponse = + // post /v1/dataset/{dataset_id}/fetch + withRawResponse().fetchPost(params, requestOptions).parse() + + override fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions, + ): InsertEventsResponse = + // post /v1/dataset/{dataset_id}/insert + withRawResponse().insert(params, requestOptions).parse() + + override fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions, + ): SummarizeDatasetResponse = + // get /v1/dataset/{dataset_id}/summarize + withRawResponse().summarize(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + DatasetService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): DatasetService.WithRawResponse = + DatasetServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: DatasetCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get a dataset object by its id */ - override fun retrieve(params: DatasetRetrieveParams, requestOptions: RequestOptions): Dataset { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { retrieveHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: DatasetRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Partially update a dataset object. Specify the fields to update in the payload. Any - * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /dataset/{id}` and then replace it with `PUT /dataset`. - */ - override fun update(params: DatasetUpdateParams, requestOptions: RequestOptions): Dataset { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "dataset", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { updateHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: DatasetUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * List out all datasets. The datasets are sorted by creation date, with the most - * recently-created datasets coming first - */ - override fun list(params: DatasetListParams, requestOptions: RequestOptions): DatasetListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "dataset") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { listHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: DatasetListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + DatasetListPage.builder() + .service(DatasetServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() } - } - .let { DatasetListPage.of(this, params, it) } + } } - } - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Delete a dataset object by its id */ - override fun delete(params: DatasetDeleteParams, requestOptions: RequestOptions): Dataset { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "dataset", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { deleteHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: DatasetDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val feedbackHandler: Handler = emptyHandler().withErrorHandler(errorHandler) - - /** Log feedback for a set of dataset events */ - override fun feedback(params: DatasetFeedbackParams, requestOptions: RequestOptions) { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "feedback") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - clientOptions.httpClient.execute(request, requestOptions).let { response -> - response.use { feedbackHandler.handle(it) } + private val feedbackHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun feedback( + params: DatasetFeedbackParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "feedback") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { feedbackHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } } - } - private val fetchHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val fetchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in a dataset. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body - */ - override fun fetch( - params: DatasetFetchParams, - requestOptions: RequestOptions - ): DatasetFetchResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { fetchHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetch( + params: DatasetFetchParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { fetchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val fetchPostHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val fetchPostHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in a dataset. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - override fun fetchPost( - params: DatasetFetchPostParams, - requestOptions: RequestOptions - ): DatasetFetchPostResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { fetchPostHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetchPost( + params: DatasetFetchPostParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "fetch") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { fetchPostHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val insertHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val insertHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Insert a set of events into the dataset */ - override fun insert( - params: DatasetInsertParams, - requestOptions: RequestOptions - ): DatasetInsertResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "dataset", params.getPathParam(0), "insert") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { insertHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun insert( + params: DatasetInsertParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "insert") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { insertHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val replaceHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create or replace a new dataset. If there is an existing dataset in the project with the same - * name as the one specified in the request, will replace the existing dataset with the provided - * fields - */ - override fun replace(params: DatasetReplaceParams, requestOptions: RequestOptions): Dataset { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("v1", "dataset") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { replaceHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val summarizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun summarize( + params: DatasetSummarizeParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("datasetId", params.datasetId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "dataset", params._pathParam(0), "summarize") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { summarizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarService.kt new file mode 100644 index 00000000..89e7ecbe --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarService.kt @@ -0,0 +1,333 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.EnvVar +import com.braintrustdata.api.models.EnvVarCreateParams +import com.braintrustdata.api.models.EnvVarDeleteParams +import com.braintrustdata.api.models.EnvVarListParams +import com.braintrustdata.api.models.EnvVarListResponse +import com.braintrustdata.api.models.EnvVarReplaceParams +import com.braintrustdata.api.models.EnvVarRetrieveParams +import com.braintrustdata.api.models.EnvVarUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface EnvVarService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): EnvVarService + + /** + * Create a new env_var. If there is an existing env_var with the same name as the one specified + * in the request, will return the existing env_var unmodified + */ + fun create(params: EnvVarCreateParams): EnvVar = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: EnvVarCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar + + /** Get an env_var object by its id */ + fun retrieve(envVarId: String): EnvVar = retrieve(envVarId, EnvVarRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar = retrieve(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + ): EnvVar = retrieve(envVarId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: EnvVarRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar + + /** @see retrieve */ + fun retrieve(params: EnvVarRetrieveParams): EnvVar = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(envVarId: String, requestOptions: RequestOptions): EnvVar = + retrieve(envVarId, EnvVarRetrieveParams.none(), requestOptions) + + /** + * Partially update an env_var object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(envVarId: String, params: EnvVarUpdateParams): EnvVar = + update(envVarId, params, RequestOptions.none()) + + /** @see update */ + fun update( + envVarId: String, + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar = update(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see update */ + fun update(params: EnvVarUpdateParams): EnvVar = update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar + + /** + * List out all env_vars. The env_vars are sorted by creation date, with the most + * recently-created env_vars coming first + */ + fun list(): EnvVarListResponse = list(EnvVarListParams.none()) + + /** @see list */ + fun list( + params: EnvVarListParams = EnvVarListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVarListResponse + + /** @see list */ + fun list(params: EnvVarListParams = EnvVarListParams.none()): EnvVarListResponse = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): EnvVarListResponse = + list(EnvVarListParams.none(), requestOptions) + + /** Delete an env_var object by its id */ + fun delete(envVarId: String): EnvVar = delete(envVarId, EnvVarDeleteParams.none()) + + /** @see delete */ + fun delete( + envVarId: String, + params: EnvVarDeleteParams = EnvVarDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar = delete(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see delete */ + fun delete(envVarId: String, params: EnvVarDeleteParams = EnvVarDeleteParams.none()): EnvVar = + delete(envVarId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: EnvVarDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar + + /** @see delete */ + fun delete(params: EnvVarDeleteParams): EnvVar = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(envVarId: String, requestOptions: RequestOptions): EnvVar = + delete(envVarId, EnvVarDeleteParams.none(), requestOptions) + + /** + * Create or replace env_var. If there is an existing env_var with the same name as the one + * specified in the request, will replace the existing env_var with the provided fields + */ + fun replace(params: EnvVarReplaceParams): EnvVar = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: EnvVarReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): EnvVar + + /** A view of [EnvVarService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): EnvVarService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/env_var`, but is otherwise the same as + * [EnvVarService.create]. + */ + @MustBeClosed + fun create(params: EnvVarCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: EnvVarCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/env_var/{env_var_id}`, but is otherwise the same + * as [EnvVarService.retrieve]. + */ + @MustBeClosed + fun retrieve(envVarId: String): HttpResponseFor = + retrieve(envVarId, EnvVarRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + envVarId: String, + params: EnvVarRetrieveParams = EnvVarRetrieveParams.none(), + ): HttpResponseFor = retrieve(envVarId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: EnvVarRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: EnvVarRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(envVarId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(envVarId, EnvVarRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/env_var/{env_var_id}`, but is otherwise the + * same as [EnvVarService.update]. + */ + @MustBeClosed + fun update(envVarId: String, params: EnvVarUpdateParams): HttpResponseFor = + update(envVarId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + envVarId: String, + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update(params: EnvVarUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: EnvVarUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/env_var`, but is otherwise the same as + * [EnvVarService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(EnvVarListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: EnvVarListParams = EnvVarListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: EnvVarListParams = EnvVarListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(EnvVarListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/env_var/{env_var_id}`, but is otherwise the + * same as [EnvVarService.delete]. + */ + @MustBeClosed + fun delete(envVarId: String): HttpResponseFor = + delete(envVarId, EnvVarDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + envVarId: String, + params: EnvVarDeleteParams = EnvVarDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().envVarId(envVarId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + envVarId: String, + params: EnvVarDeleteParams = EnvVarDeleteParams.none(), + ): HttpResponseFor = delete(envVarId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: EnvVarDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: EnvVarDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(envVarId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(envVarId, EnvVarDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/env_var`, but is otherwise the same as + * [EnvVarService.replace]. + */ + @MustBeClosed + fun replace(params: EnvVarReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: EnvVarReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100644 index 00000000..87948806 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceImpl.kt @@ -0,0 +1,252 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.EnvVar +import com.braintrustdata.api.models.EnvVarCreateParams +import com.braintrustdata.api.models.EnvVarDeleteParams +import com.braintrustdata.api.models.EnvVarListParams +import com.braintrustdata.api.models.EnvVarListResponse +import com.braintrustdata.api.models.EnvVarReplaceParams +import com.braintrustdata.api.models.EnvVarRetrieveParams +import com.braintrustdata.api.models.EnvVarUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class EnvVarServiceImpl internal constructor(private val clientOptions: ClientOptions) : + EnvVarService { + + private val withRawResponse: EnvVarService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): EnvVarService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): EnvVarService = + EnvVarServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: EnvVarCreateParams, requestOptions: RequestOptions): EnvVar = + // post /v1/env_var + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: EnvVarRetrieveParams, requestOptions: RequestOptions): EnvVar = + // get /v1/env_var/{env_var_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: EnvVarUpdateParams, requestOptions: RequestOptions): EnvVar = + // patch /v1/env_var/{env_var_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: EnvVarListParams, + requestOptions: RequestOptions, + ): EnvVarListResponse = + // get /v1/env_var + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: EnvVarDeleteParams, requestOptions: RequestOptions): EnvVar = + // delete /v1/env_var/{env_var_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace(params: EnvVarReplaceParams, requestOptions: RequestOptions): EnvVar = + // put /v1/env_var + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EnvVarService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): EnvVarService.WithRawResponse = + EnvVarServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: EnvVarCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: EnvVarRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("envVarId", params.envVarId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: EnvVarUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("envVarId", params.envVarId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: EnvVarListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: EnvVarDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("envVarId", params.envVarId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: EnvVarReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "env_var") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalService.kt new file mode 100644 index 00000000..3b96070c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalService.kt @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.EvalCreateParams +import com.braintrustdata.api.models.SummarizeExperimentResponse +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface EvalService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): EvalService + + /** + * Launch an evaluation. This is the API-equivalent of the `Eval` function that is built into + * the Braintrust SDK. In the Eval API, you provide pointers to a dataset, task function, and + * scoring functions. The API will then run the evaluation, create an experiment, and return the + * results along with a link to the experiment. To learn more about evals, see the + * [Evals guide](https://www.braintrust.dev/docs/guides/evals). + */ + fun create(params: EvalCreateParams): SummarizeExperimentResponse = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: EvalCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SummarizeExperimentResponse + + /** A view of [EvalService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): EvalService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/eval`, but is otherwise the same as + * [EvalService.create]. + */ + @MustBeClosed + fun create(params: EvalCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: EvalCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100644 index 00000000..6fe04f25 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/EvalServiceImpl.kt @@ -0,0 +1,81 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.EvalCreateParams +import com.braintrustdata.api.models.SummarizeExperimentResponse +import java.util.function.Consumer + +class EvalServiceImpl internal constructor(private val clientOptions: ClientOptions) : EvalService { + + private val withRawResponse: EvalService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): EvalService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): EvalService = + EvalServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: EvalCreateParams, + requestOptions: RequestOptions, + ): SummarizeExperimentResponse = + // post /v1/eval + withRawResponse().create(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + EvalService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): EvalService.WithRawResponse = + EvalServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: EvalCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "eval") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentService.kt old mode 100644 new mode 100755 index c7868a6a..a71044d7 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentService.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ExperimentService.kt @@ -1,117 +1,707 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.blocking +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.models.Experiment import com.braintrustdata.api.models.ExperimentCreateParams import com.braintrustdata.api.models.ExperimentDeleteParams import com.braintrustdata.api.models.ExperimentFeedbackParams import com.braintrustdata.api.models.ExperimentFetchParams import com.braintrustdata.api.models.ExperimentFetchPostParams -import com.braintrustdata.api.models.ExperimentFetchPostResponse -import com.braintrustdata.api.models.ExperimentFetchResponse import com.braintrustdata.api.models.ExperimentInsertParams -import com.braintrustdata.api.models.ExperimentInsertResponse import com.braintrustdata.api.models.ExperimentListPage import com.braintrustdata.api.models.ExperimentListParams -import com.braintrustdata.api.models.ExperimentReplaceParams import com.braintrustdata.api.models.ExperimentRetrieveParams +import com.braintrustdata.api.models.ExperimentSummarizeParams import com.braintrustdata.api.models.ExperimentUpdateParams +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchExperimentEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeExperimentResponse +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer interface ExperimentService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ExperimentService + /** * Create a new experiment. If there is an existing experiment in the project with the same name - * as the one specified in the request, will create a new experiment from `name`, suffixed with - * a unique identifier + * as the one specified in the request, will return the existing experiment unmodified */ - @JvmOverloads + fun create(params: ExperimentCreateParams): Experiment = create(params, RequestOptions.none()) + + /** @see create */ fun create( params: ExperimentCreateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Experiment /** Get an experiment object by its id */ - @JvmOverloads + fun retrieve(experimentId: String): Experiment = + retrieve(experimentId, ExperimentRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Experiment = retrieve(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + ): Experiment = retrieve(experimentId, params, RequestOptions.none()) + + /** @see retrieve */ fun retrieve( params: ExperimentRetrieveParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Experiment + /** @see retrieve */ + fun retrieve(params: ExperimentRetrieveParams): Experiment = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(experimentId: String, requestOptions: RequestOptions): Experiment = + retrieve(experimentId, ExperimentRetrieveParams.none(), requestOptions) + /** * Partially update an experiment object. Specify the fields to update in the payload. Any * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /experiment/{id}` and then replace it with `PUT /experiment`. + * removing fields or setting them to null. */ - @JvmOverloads + fun update(experimentId: String): Experiment = + update(experimentId, ExperimentUpdateParams.none()) + + /** @see update */ + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Experiment = update(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see update */ + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + ): Experiment = update(experimentId, params, RequestOptions.none()) + + /** @see update */ fun update( params: ExperimentUpdateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Experiment + /** @see update */ + fun update(params: ExperimentUpdateParams): Experiment = update(params, RequestOptions.none()) + + /** @see update */ + fun update(experimentId: String, requestOptions: RequestOptions): Experiment = + update(experimentId, ExperimentUpdateParams.none(), requestOptions) + /** * List out all experiments. The experiments are sorted by creation date, with the most * recently-created experiments coming first */ - @JvmOverloads + fun list(): ExperimentListPage = list(ExperimentListParams.none()) + + /** @see list */ fun list( - params: ExperimentListParams, - requestOptions: RequestOptions = RequestOptions.none() + params: ExperimentListParams = ExperimentListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): ExperimentListPage + /** @see list */ + fun list(params: ExperimentListParams = ExperimentListParams.none()): ExperimentListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): ExperimentListPage = + list(ExperimentListParams.none(), requestOptions) + /** Delete an experiment object by its id */ - @JvmOverloads + fun delete(experimentId: String): Experiment = + delete(experimentId, ExperimentDeleteParams.none()) + + /** @see delete */ + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Experiment = delete(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see delete */ + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + ): Experiment = delete(experimentId, params, RequestOptions.none()) + + /** @see delete */ fun delete( params: ExperimentDeleteParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Experiment + /** @see delete */ + fun delete(params: ExperimentDeleteParams): Experiment = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(experimentId: String, requestOptions: RequestOptions): Experiment = + delete(experimentId, ExperimentDeleteParams.none(), requestOptions) + /** Log feedback for a set of experiment events */ - @JvmOverloads + fun feedback(experimentId: String, params: ExperimentFeedbackParams): FeedbackResponseSchema = + feedback(experimentId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + experimentId: String, + params: ExperimentFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FeedbackResponseSchema = + feedback(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see feedback */ + fun feedback(params: ExperimentFeedbackParams): FeedbackResponseSchema = + feedback(params, RequestOptions.none()) + + /** @see feedback */ fun feedback( params: ExperimentFeedbackParams, - requestOptions: RequestOptions = RequestOptions.none() - ) + requestOptions: RequestOptions = RequestOptions.none(), + ): FeedbackResponseSchema /** * Fetch the events in an experiment. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body + * parameters in the URL query rather than in the request body. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetch(experimentId: String): FetchExperimentEventsResponse = + fetch(experimentId, ExperimentFetchParams.none()) + + /** @see fetch */ + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchExperimentEventsResponse = + fetch(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + ): FetchExperimentEventsResponse = fetch(experimentId, params, RequestOptions.none()) + + /** @see fetch */ fun fetch( params: ExperimentFetchParams, - requestOptions: RequestOptions = RequestOptions.none() - ): ExperimentFetchResponse + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchExperimentEventsResponse + + /** @see fetch */ + fun fetch(params: ExperimentFetchParams): FetchExperimentEventsResponse = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch(experimentId: String, requestOptions: RequestOptions): FetchExperimentEventsResponse = + fetch(experimentId, ExperimentFetchParams.none(), requestOptions) /** * Fetch the events in an experiment. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query + * parameters in the request body rather than in the URL query. For more complex queries, use + * the `POST /btql` endpoint. */ - @JvmOverloads + fun fetchPost(experimentId: String): FetchExperimentEventsResponse = + fetchPost(experimentId, ExperimentFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchExperimentEventsResponse = + fetchPost(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + ): FetchExperimentEventsResponse = fetchPost(experimentId, params, RequestOptions.none()) + + /** @see fetchPost */ fun fetchPost( params: ExperimentFetchPostParams, - requestOptions: RequestOptions = RequestOptions.none() - ): ExperimentFetchPostResponse + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchExperimentEventsResponse + + /** @see fetchPost */ + fun fetchPost(params: ExperimentFetchPostParams): FetchExperimentEventsResponse = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + experimentId: String, + requestOptions: RequestOptions, + ): FetchExperimentEventsResponse = + fetchPost(experimentId, ExperimentFetchPostParams.none(), requestOptions) /** Insert a set of events into the experiment */ - @JvmOverloads + fun insert(experimentId: String, params: ExperimentInsertParams): InsertEventsResponse = + insert(experimentId, params, RequestOptions.none()) + + /** @see insert */ fun insert( + experimentId: String, params: ExperimentInsertParams, - requestOptions: RequestOptions = RequestOptions.none() - ): ExperimentInsertResponse + requestOptions: RequestOptions = RequestOptions.none(), + ): InsertEventsResponse = + insert(params.toBuilder().experimentId(experimentId).build(), requestOptions) - /** - * Create or replace a new experiment. If there is an existing experiment in the project with - * the same name as the one specified in the request, will replace the existing experiment with - * the provided fields - */ - @JvmOverloads - fun replace( - params: ExperimentReplaceParams, - requestOptions: RequestOptions = RequestOptions.none() - ): Experiment + /** @see insert */ + fun insert(params: ExperimentInsertParams): InsertEventsResponse = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): InsertEventsResponse + + /** Summarize experiment */ + fun summarize(experimentId: String): SummarizeExperimentResponse = + summarize(experimentId, ExperimentSummarizeParams.none()) + + /** @see summarize */ + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): SummarizeExperimentResponse = + summarize(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see summarize */ + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + ): SummarizeExperimentResponse = summarize(experimentId, params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SummarizeExperimentResponse + + /** @see summarize */ + fun summarize(params: ExperimentSummarizeParams): SummarizeExperimentResponse = + summarize(params, RequestOptions.none()) + + /** @see summarize */ + fun summarize( + experimentId: String, + requestOptions: RequestOptions, + ): SummarizeExperimentResponse = + summarize(experimentId, ExperimentSummarizeParams.none(), requestOptions) + + /** A view of [ExperimentService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ExperimentService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/experiment`, but is otherwise the same as + * [ExperimentService.create]. + */ + @MustBeClosed + fun create(params: ExperimentCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: ExperimentCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/experiment/{experiment_id}`, but is otherwise + * the same as [ExperimentService.retrieve]. + */ + @MustBeClosed + fun retrieve(experimentId: String): HttpResponseFor = + retrieve(experimentId, ExperimentRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + experimentId: String, + params: ExperimentRetrieveParams = ExperimentRetrieveParams.none(), + ): HttpResponseFor = retrieve(experimentId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: ExperimentRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: ExperimentRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + experimentId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + retrieve(experimentId, ExperimentRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/experiment/{experiment_id}`, but is otherwise + * the same as [ExperimentService.update]. + */ + @MustBeClosed + fun update(experimentId: String): HttpResponseFor = + update(experimentId, ExperimentUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + experimentId: String, + params: ExperimentUpdateParams = ExperimentUpdateParams.none(), + ): HttpResponseFor = update(experimentId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: ExperimentUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: ExperimentUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + experimentId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + update(experimentId, ExperimentUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/experiment`, but is otherwise the same as + * [ExperimentService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(ExperimentListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ExperimentListParams = ExperimentListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: ExperimentListParams = ExperimentListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ExperimentListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/experiment/{experiment_id}`, but is otherwise + * the same as [ExperimentService.delete]. + */ + @MustBeClosed + fun delete(experimentId: String): HttpResponseFor = + delete(experimentId, ExperimentDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + experimentId: String, + params: ExperimentDeleteParams = ExperimentDeleteParams.none(), + ): HttpResponseFor = delete(experimentId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: ExperimentDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: ExperimentDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + experimentId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + delete(experimentId, ExperimentDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/experiment/{experiment_id}/feedback`, but is + * otherwise the same as [ExperimentService.feedback]. + */ + @MustBeClosed + fun feedback( + experimentId: String, + params: ExperimentFeedbackParams, + ): HttpResponseFor = + feedback(experimentId, params, RequestOptions.none()) + + /** @see feedback */ + @MustBeClosed + fun feedback( + experimentId: String, + params: ExperimentFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + feedback(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see feedback */ + @MustBeClosed + fun feedback(params: ExperimentFeedbackParams): HttpResponseFor = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + @MustBeClosed + fun feedback( + params: ExperimentFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/experiment/{experiment_id}/fetch`, but is + * otherwise the same as [ExperimentService.fetch]. + */ + @MustBeClosed + fun fetch(experimentId: String): HttpResponseFor = + fetch(experimentId, ExperimentFetchParams.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + fetch(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetch */ + @MustBeClosed + fun fetch( + experimentId: String, + params: ExperimentFetchParams = ExperimentFetchParams.none(), + ): HttpResponseFor = + fetch(experimentId, params, RequestOptions.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + params: ExperimentFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see fetch */ + @MustBeClosed + fun fetch(params: ExperimentFetchParams): HttpResponseFor = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + experimentId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + fetch(experimentId, ExperimentFetchParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/experiment/{experiment_id}/fetch`, but is + * otherwise the same as [ExperimentService.fetchPost]. + */ + @MustBeClosed + fun fetchPost(experimentId: String): HttpResponseFor = + fetchPost(experimentId, ExperimentFetchPostParams.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + fetchPost(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + experimentId: String, + params: ExperimentFetchPostParams = ExperimentFetchPostParams.none(), + ): HttpResponseFor = + fetchPost(experimentId, params, RequestOptions.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + params: ExperimentFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + params: ExperimentFetchPostParams + ): HttpResponseFor = fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + experimentId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + fetchPost(experimentId, ExperimentFetchPostParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/experiment/{experiment_id}/insert`, but is + * otherwise the same as [ExperimentService.insert]. + */ + @MustBeClosed + fun insert( + experimentId: String, + params: ExperimentInsertParams, + ): HttpResponseFor = + insert(experimentId, params, RequestOptions.none()) + + /** @see insert */ + @MustBeClosed + fun insert( + experimentId: String, + params: ExperimentInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + insert(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see insert */ + @MustBeClosed + fun insert(params: ExperimentInsertParams): HttpResponseFor = + insert(params, RequestOptions.none()) + + /** @see insert */ + @MustBeClosed + fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/experiment/{experiment_id}/summarize`, but is + * otherwise the same as [ExperimentService.summarize]. + */ + @MustBeClosed + fun summarize(experimentId: String): HttpResponseFor = + summarize(experimentId, ExperimentSummarizeParams.none()) + + /** @see summarize */ + @MustBeClosed + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + summarize(params.toBuilder().experimentId(experimentId).build(), requestOptions) + + /** @see summarize */ + @MustBeClosed + fun summarize( + experimentId: String, + params: ExperimentSummarizeParams = ExperimentSummarizeParams.none(), + ): HttpResponseFor = + summarize(experimentId, params, RequestOptions.none()) + + /** @see summarize */ + @MustBeClosed + fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see summarize */ + @MustBeClosed + fun summarize( + params: ExperimentSummarizeParams + ): HttpResponseFor = summarize(params, RequestOptions.none()) + + /** @see summarize */ + @MustBeClosed + fun summarize( + experimentId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + summarize(experimentId, ExperimentSummarizeParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index 814a4e48..81a4d350 --- 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 @@ -4,329 +4,438 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +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.models.Experiment import com.braintrustdata.api.models.ExperimentCreateParams import com.braintrustdata.api.models.ExperimentDeleteParams import com.braintrustdata.api.models.ExperimentFeedbackParams import com.braintrustdata.api.models.ExperimentFetchParams import com.braintrustdata.api.models.ExperimentFetchPostParams -import com.braintrustdata.api.models.ExperimentFetchPostResponse -import com.braintrustdata.api.models.ExperimentFetchResponse import com.braintrustdata.api.models.ExperimentInsertParams -import com.braintrustdata.api.models.ExperimentInsertResponse import com.braintrustdata.api.models.ExperimentListPage +import com.braintrustdata.api.models.ExperimentListPageResponse import com.braintrustdata.api.models.ExperimentListParams -import com.braintrustdata.api.models.ExperimentReplaceParams import com.braintrustdata.api.models.ExperimentRetrieveParams +import com.braintrustdata.api.models.ExperimentSummarizeParams import com.braintrustdata.api.models.ExperimentUpdateParams -import com.braintrustdata.api.services.emptyHandler -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler - -class ExperimentServiceImpl -constructor( - private val clientOptions: ClientOptions, -) : ExperimentService { - - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create a new experiment. If there is an existing experiment in the project with the same name - * as the one specified in the request, will create a new experiment from `name`, suffixed with - * a unique identifier - */ +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchExperimentEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.SummarizeExperimentResponse +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ExperimentServiceImpl internal constructor(private val clientOptions: ClientOptions) : + ExperimentService { + + private val withRawResponse: ExperimentService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ExperimentService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ExperimentService = + ExperimentServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun create( params: ExperimentCreateParams, - requestOptions: RequestOptions - ): Experiment { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + requestOptions: RequestOptions, + ): Experiment = + // post /v1/experiment + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve( + params: ExperimentRetrieveParams, + requestOptions: RequestOptions, + ): Experiment = + // get /v1/experiment/{experiment_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update( + params: ExperimentUpdateParams, + requestOptions: RequestOptions, + ): Experiment = + // patch /v1/experiment/{experiment_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: ExperimentListParams, + requestOptions: RequestOptions, + ): ExperimentListPage = + // get /v1/experiment + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: ExperimentDeleteParams, + requestOptions: RequestOptions, + ): Experiment = + // delete /v1/experiment/{experiment_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun feedback( + params: ExperimentFeedbackParams, + requestOptions: RequestOptions, + ): FeedbackResponseSchema = + // post /v1/experiment/{experiment_id}/feedback + withRawResponse().feedback(params, requestOptions).parse() + + override fun fetch( + params: ExperimentFetchParams, + requestOptions: RequestOptions, + ): FetchExperimentEventsResponse = + // get /v1/experiment/{experiment_id}/fetch + withRawResponse().fetch(params, requestOptions).parse() + + override fun fetchPost( + params: ExperimentFetchPostParams, + requestOptions: RequestOptions, + ): FetchExperimentEventsResponse = + // post /v1/experiment/{experiment_id}/fetch + withRawResponse().fetchPost(params, requestOptions).parse() + + override fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions, + ): InsertEventsResponse = + // post /v1/experiment/{experiment_id}/insert + withRawResponse().insert(params, requestOptions).parse() + + override fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions, + ): SummarizeExperimentResponse = + // get /v1/experiment/{experiment_id}/summarize + withRawResponse().summarize(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ExperimentService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ExperimentService.WithRawResponse = + ExperimentServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ExperimentCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Get an experiment object by its id */ - override fun retrieve( - params: ExperimentRetrieveParams, - requestOptions: RequestOptions - ): Experiment { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { retrieveHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun retrieve( + params: ExperimentRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Partially update an experiment object. Specify the fields to update in the payload. Any - * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /experiment/{id}` and then replace it with `PUT /experiment`. - */ - override fun update( - params: ExperimentUpdateParams, - requestOptions: RequestOptions - ): Experiment { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "experiment", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { updateHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun update( + params: ExperimentUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * List out all experiments. The experiments are sorted by creation date, with the most - * recently-created experiments coming first - */ - override fun list( - params: ExperimentListParams, - requestOptions: RequestOptions - ): ExperimentListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "experiment") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { listHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun list( + params: ExperimentListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } - .let { ExperimentListPage.of(this, params, it) } + .let { + ExperimentListPage.builder() + .service(ExperimentServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } } - } - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Delete an experiment object by its id */ - override fun delete( - params: ExperimentDeleteParams, - requestOptions: RequestOptions - ): Experiment { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "experiment", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { deleteHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun delete( + params: ExperimentDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val feedbackHandler: Handler = emptyHandler().withErrorHandler(errorHandler) - - /** Log feedback for a set of experiment events */ - override fun feedback(params: ExperimentFeedbackParams, requestOptions: RequestOptions) { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "feedback") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - clientOptions.httpClient.execute(request, requestOptions).let { response -> - response.use { feedbackHandler.handle(it) } + private val feedbackHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun feedback( + params: ExperimentFeedbackParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "feedback") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { feedbackHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } } - } - private val fetchHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val fetchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in an experiment. Equivalent to the POST form of the same path, but with the - * parameters in the URL query rather than in the request body - */ - override fun fetch( - params: ExperimentFetchParams, - requestOptions: RequestOptions - ): ExperimentFetchResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { fetchHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetch( + params: ExperimentFetchParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { fetchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val fetchPostHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val fetchPostHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** - * Fetch the events in an experiment. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - override fun fetchPost( - params: ExperimentFetchPostParams, - requestOptions: RequestOptions - ): ExperimentFetchPostResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { fetchPostHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun fetchPost( + params: ExperimentFetchPostParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "fetch") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { fetchPostHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val insertHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) + private val insertHandler: Handler = + jsonHandler(clientOptions.jsonMapper) - /** Insert a set of events into the experiment */ - override fun insert( - params: ExperimentInsertParams, - requestOptions: RequestOptions - ): ExperimentInsertResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "experiment", params.getPathParam(0), "insert") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { insertHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun insert( + params: ExperimentInsertParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "insert") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { insertHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val replaceHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create or replace a new experiment. If there is an existing experiment in the project with - * the same name as the one specified in the request, will replace the existing experiment with - * the provided fields - */ - override fun replace( - params: ExperimentReplaceParams, - requestOptions: RequestOptions - ): Experiment { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("v1", "experiment") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { replaceHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val summarizeHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun summarize( + params: ExperimentSummarizeParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("experimentId", params.experimentId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "experiment", params._pathParam(0), "summarize") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { summarizeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionService.kt new file mode 100755 index 00000000..21f834fe --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionService.kt @@ -0,0 +1,444 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.FunctionListParams +import com.braintrustdata.api.models.FunctionReplaceParams +import com.braintrustdata.api.models.FunctionRetrieveParams +import com.braintrustdata.api.models.FunctionUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.Optional +import java.util.function.Consumer + +interface FunctionService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FunctionService + + /** + * Create a new function. If there is an existing function in the project with the same slug as + * the one specified in the request, will return the existing function unmodified + */ + fun create(params: FunctionCreateParams): Function = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: FunctionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Function + + /** Get a function object by its id */ + fun retrieve(functionId: String): Function = retrieve(functionId, FunctionRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Function = retrieve(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + ): Function = retrieve(functionId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Function + + /** @see retrieve */ + fun retrieve(params: FunctionRetrieveParams): Function = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(functionId: String, requestOptions: RequestOptions): Function = + retrieve(functionId, FunctionRetrieveParams.none(), requestOptions) + + /** + * Partially update a function object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(functionId: String): Function = update(functionId, FunctionUpdateParams.none()) + + /** @see update */ + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Function = update(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see update */ + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + ): Function = update(functionId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: FunctionUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Function + + /** @see update */ + fun update(params: FunctionUpdateParams): Function = update(params, RequestOptions.none()) + + /** @see update */ + fun update(functionId: String, requestOptions: RequestOptions): Function = + update(functionId, FunctionUpdateParams.none(), requestOptions) + + /** + * List out all functions. The functions are sorted by creation date, with the most + * recently-created functions coming first + */ + fun list(): FunctionListPage = list(FunctionListParams.none()) + + /** @see list */ + fun list( + params: FunctionListParams = FunctionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FunctionListPage + + /** @see list */ + fun list(params: FunctionListParams = FunctionListParams.none()): FunctionListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): FunctionListPage = + list(FunctionListParams.none(), requestOptions) + + /** Delete a function object by its id */ + fun delete(functionId: String): Function = delete(functionId, FunctionDeleteParams.none()) + + /** @see delete */ + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Function = delete(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see delete */ + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + ): Function = delete(functionId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: FunctionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Function + + /** @see delete */ + fun delete(params: FunctionDeleteParams): Function = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(functionId: String, requestOptions: RequestOptions): Function = + delete(functionId, FunctionDeleteParams.none(), requestOptions) + + /** Invoke a function. */ + fun invoke(functionId: String): Optional = + invoke(functionId, FunctionInvokeParams.none()) + + /** @see invoke */ + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Optional = + invoke(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see invoke */ + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + ): Optional = invoke(functionId, params, RequestOptions.none()) + + /** @see invoke */ + fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Optional + + /** @see invoke */ + fun invoke(params: FunctionInvokeParams): Optional = + invoke(params, RequestOptions.none()) + + /** @see invoke */ + fun invoke( + functionId: String, + requestOptions: RequestOptions, + ): Optional = + invoke(functionId, FunctionInvokeParams.none(), requestOptions) + + /** + * Create or replace function. If there is an existing function in the project with the same + * slug as the one specified in the request, will replace the existing function with the + * provided fields + */ + fun replace(params: FunctionReplaceParams): Function = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: FunctionReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Function + + /** A view of [FunctionService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): FunctionService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/function`, but is otherwise the same as + * [FunctionService.create]. + */ + @MustBeClosed + fun create(params: FunctionCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: FunctionCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/function/{function_id}`, but is otherwise the + * same as [FunctionService.retrieve]. + */ + @MustBeClosed + fun retrieve(functionId: String): HttpResponseFor = + retrieve(functionId, FunctionRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + functionId: String, + params: FunctionRetrieveParams = FunctionRetrieveParams.none(), + ): HttpResponseFor = retrieve(functionId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: FunctionRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + functionId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + retrieve(functionId, FunctionRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/function/{function_id}`, but is otherwise the + * same as [FunctionService.update]. + */ + @MustBeClosed + fun update(functionId: String): HttpResponseFor = + update(functionId, FunctionUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + functionId: String, + params: FunctionUpdateParams = FunctionUpdateParams.none(), + ): HttpResponseFor = update(functionId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: FunctionUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: FunctionUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update(functionId: String, requestOptions: RequestOptions): HttpResponseFor = + update(functionId, FunctionUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/function`, but is otherwise the same as + * [FunctionService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(FunctionListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: FunctionListParams = FunctionListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: FunctionListParams = FunctionListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(FunctionListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/function/{function_id}`, but is otherwise the + * same as [FunctionService.delete]. + */ + @MustBeClosed + fun delete(functionId: String): HttpResponseFor = + delete(functionId, FunctionDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + functionId: String, + params: FunctionDeleteParams = FunctionDeleteParams.none(), + ): HttpResponseFor = delete(functionId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: FunctionDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: FunctionDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(functionId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(functionId, FunctionDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/function/{function_id}/invoke`, but is + * otherwise the same as [FunctionService.invoke]. + */ + @MustBeClosed + fun invoke(functionId: String): HttpResponseFor> = + invoke(functionId, FunctionInvokeParams.none()) + + /** @see invoke */ + @MustBeClosed + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> = + invoke(params.toBuilder().functionId(functionId).build(), requestOptions) + + /** @see invoke */ + @MustBeClosed + fun invoke( + functionId: String, + params: FunctionInvokeParams = FunctionInvokeParams.none(), + ): HttpResponseFor> = + invoke(functionId, params, RequestOptions.none()) + + /** @see invoke */ + @MustBeClosed + fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor> + + /** @see invoke */ + @MustBeClosed + fun invoke( + params: FunctionInvokeParams + ): HttpResponseFor> = invoke(params, RequestOptions.none()) + + /** @see invoke */ + @MustBeClosed + fun invoke( + functionId: String, + requestOptions: RequestOptions, + ): HttpResponseFor> = + invoke(functionId, FunctionInvokeParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/function`, but is otherwise the same as + * [FunctionService.replace]. + */ + @MustBeClosed + fun replace(params: FunctionReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: FunctionReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..85edcaca --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceImpl.kt @@ -0,0 +1,309 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.FunctionUpdateParams +import java.util.Optional +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class FunctionServiceImpl internal constructor(private val clientOptions: ClientOptions) : + FunctionService { + + private val withRawResponse: FunctionService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): FunctionService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): FunctionService = + FunctionServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: FunctionCreateParams, requestOptions: RequestOptions): Function = + // post /v1/function + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions, + ): Function = + // get /v1/function/{function_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: FunctionUpdateParams, requestOptions: RequestOptions): Function = + // patch /v1/function/{function_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: FunctionListParams, + requestOptions: RequestOptions, + ): FunctionListPage = + // get /v1/function + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: FunctionDeleteParams, requestOptions: RequestOptions): Function = + // delete /v1/function/{function_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions, + ): Optional = + // post /v1/function/{function_id}/invoke + withRawResponse().invoke(params, requestOptions).parse() + + override fun replace(params: FunctionReplaceParams, requestOptions: RequestOptions): Function = + // put /v1/function + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + FunctionService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): FunctionService.WithRawResponse = + FunctionServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: FunctionCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: FunctionRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: FunctionUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: FunctionListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + FunctionListPage.builder() + .service(FunctionServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: FunctionDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val invokeHandler: Handler> = + jsonHandler>(clientOptions.jsonMapper) + + override fun invoke( + params: FunctionInvokeParams, + requestOptions: RequestOptions, + ): HttpResponseFor> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("functionId", params.functionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function", params._pathParam(0), "invoke") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { invokeHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.ifPresent { it.validate() } + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: FunctionReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "function") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupService.kt new file mode 100755 index 00000000..f045afc6 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupService.kt @@ -0,0 +1,348 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.GroupListParams +import com.braintrustdata.api.models.GroupReplaceParams +import com.braintrustdata.api.models.GroupRetrieveParams +import com.braintrustdata.api.models.GroupUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface GroupService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): GroupService + + /** + * Create a new group. If there is an existing group with the same name as the one specified in + * the request, will return the existing group unmodified + */ + fun create(params: GroupCreateParams): Group = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: GroupCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Group + + /** Get a group object by its id */ + fun retrieve(groupId: String): Group = retrieve(groupId, GroupRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + groupId: String, + params: GroupRetrieveParams = GroupRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Group = retrieve(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve(groupId: String, params: GroupRetrieveParams = GroupRetrieveParams.none()): Group = + retrieve(groupId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: GroupRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Group + + /** @see retrieve */ + fun retrieve(params: GroupRetrieveParams): Group = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(groupId: String, requestOptions: RequestOptions): Group = + retrieve(groupId, GroupRetrieveParams.none(), requestOptions) + + /** + * Partially update a group object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields + * or setting them to null. + */ + fun update(groupId: String): Group = update(groupId, GroupUpdateParams.none()) + + /** @see update */ + fun update( + groupId: String, + params: GroupUpdateParams = GroupUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Group = update(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see update */ + fun update(groupId: String, params: GroupUpdateParams = GroupUpdateParams.none()): Group = + update(groupId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: GroupUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Group + + /** @see update */ + fun update(params: GroupUpdateParams): Group = update(params, RequestOptions.none()) + + /** @see update */ + fun update(groupId: String, requestOptions: RequestOptions): Group = + update(groupId, GroupUpdateParams.none(), requestOptions) + + /** + * List out all groups. The groups are sorted by creation date, with the most recently-created + * groups coming first + */ + fun list(): GroupListPage = list(GroupListParams.none()) + + /** @see list */ + fun list( + params: GroupListParams = GroupListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): GroupListPage + + /** @see list */ + fun list(params: GroupListParams = GroupListParams.none()): GroupListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): GroupListPage = + list(GroupListParams.none(), requestOptions) + + /** Delete a group object by its id */ + fun delete(groupId: String): Group = delete(groupId, GroupDeleteParams.none()) + + /** @see delete */ + fun delete( + groupId: String, + params: GroupDeleteParams = GroupDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Group = delete(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see delete */ + fun delete(groupId: String, params: GroupDeleteParams = GroupDeleteParams.none()): Group = + delete(groupId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: GroupDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Group + + /** @see delete */ + fun delete(params: GroupDeleteParams): Group = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(groupId: String, requestOptions: RequestOptions): Group = + delete(groupId, GroupDeleteParams.none(), requestOptions) + + /** + * Create or replace group. If there is an existing group with the same name as the one + * specified in the request, will replace the existing group with the provided fields + */ + fun replace(params: GroupReplaceParams): Group = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: GroupReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Group + + /** A view of [GroupService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): GroupService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/group`, but is otherwise the same as + * [GroupService.create]. + */ + @MustBeClosed + fun create(params: GroupCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: GroupCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/group/{group_id}`, but is otherwise the same as + * [GroupService.retrieve]. + */ + @MustBeClosed + fun retrieve(groupId: String): HttpResponseFor = + retrieve(groupId, GroupRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + groupId: String, + params: GroupRetrieveParams = GroupRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + groupId: String, + params: GroupRetrieveParams = GroupRetrieveParams.none(), + ): HttpResponseFor = retrieve(groupId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: GroupRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: GroupRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(groupId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(groupId, GroupRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/group/{group_id}`, but is otherwise the same + * as [GroupService.update]. + */ + @MustBeClosed + fun update(groupId: String): HttpResponseFor = + update(groupId, GroupUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + groupId: String, + params: GroupUpdateParams = GroupUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + groupId: String, + params: GroupUpdateParams = GroupUpdateParams.none(), + ): HttpResponseFor = update(groupId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: GroupUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: GroupUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update(groupId: String, requestOptions: RequestOptions): HttpResponseFor = + update(groupId, GroupUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/group`, but is otherwise the same as + * [GroupService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(GroupListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: GroupListParams = GroupListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list(params: GroupListParams = GroupListParams.none()): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(GroupListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/group/{group_id}`, but is otherwise the same + * as [GroupService.delete]. + */ + @MustBeClosed + fun delete(groupId: String): HttpResponseFor = + delete(groupId, GroupDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + groupId: String, + params: GroupDeleteParams = GroupDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().groupId(groupId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + groupId: String, + params: GroupDeleteParams = GroupDeleteParams.none(), + ): HttpResponseFor = delete(groupId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: GroupDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: GroupDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(groupId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(groupId, GroupDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/group`, but is otherwise the same as + * [GroupService.replace]. + */ + @MustBeClosed + fun replace(params: GroupReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: GroupReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..074c5d95 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/GroupServiceImpl.kt @@ -0,0 +1,257 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.GroupUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class GroupServiceImpl internal constructor(private val clientOptions: ClientOptions) : + GroupService { + + private val withRawResponse: GroupService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): GroupService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): GroupService = + GroupServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: GroupCreateParams, requestOptions: RequestOptions): Group = + // post /v1/group + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: GroupRetrieveParams, requestOptions: RequestOptions): Group = + // get /v1/group/{group_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: GroupUpdateParams, requestOptions: RequestOptions): Group = + // patch /v1/group/{group_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list(params: GroupListParams, requestOptions: RequestOptions): GroupListPage = + // get /v1/group + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: GroupDeleteParams, requestOptions: RequestOptions): Group = + // delete /v1/group/{group_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace(params: GroupReplaceParams, requestOptions: RequestOptions): Group = + // put /v1/group + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + GroupService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): GroupService.WithRawResponse = + GroupServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: GroupCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: GroupRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("groupId", params.groupId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: GroupUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("groupId", params.groupId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: GroupListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + GroupListPage.builder() + .service(GroupServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: GroupDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("groupId", params.groupId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: GroupReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "group") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationService.kt new file mode 100755 index 00000000..b2ddd297 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationService.kt @@ -0,0 +1,327 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.Organization +import com.braintrustdata.api.models.OrganizationDeleteParams +import com.braintrustdata.api.models.OrganizationListPage +import com.braintrustdata.api.models.OrganizationListParams +import com.braintrustdata.api.models.OrganizationRetrieveParams +import com.braintrustdata.api.models.OrganizationUpdateParams +import com.braintrustdata.api.services.blocking.organizations.MemberService +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface OrganizationService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): OrganizationService + + fun members(): MemberService + + /** Get an organization object by its id */ + fun retrieve(organizationId: String): Organization = + retrieve(organizationId, OrganizationRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Organization = + retrieve(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + ): Organization = retrieve(organizationId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Organization + + /** @see retrieve */ + fun retrieve(params: OrganizationRetrieveParams): Organization = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(organizationId: String, requestOptions: RequestOptions): Organization = + retrieve(organizationId, OrganizationRetrieveParams.none(), requestOptions) + + /** + * Partially update an organization object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(organizationId: String): Organization = + update(organizationId, OrganizationUpdateParams.none()) + + /** @see update */ + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Organization = + update(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see update */ + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + ): Organization = update(organizationId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Organization + + /** @see update */ + fun update(params: OrganizationUpdateParams): Organization = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(organizationId: String, requestOptions: RequestOptions): Organization = + update(organizationId, OrganizationUpdateParams.none(), requestOptions) + + /** + * List out all organizations. The organizations are sorted by creation date, with the most + * recently-created organizations coming first + */ + fun list(): OrganizationListPage = list(OrganizationListParams.none()) + + /** @see list */ + fun list( + params: OrganizationListParams = OrganizationListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): OrganizationListPage + + /** @see list */ + fun list(params: OrganizationListParams = OrganizationListParams.none()): OrganizationListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): OrganizationListPage = + list(OrganizationListParams.none(), requestOptions) + + /** Delete an organization object by its id */ + fun delete(organizationId: String): Organization = + delete(organizationId, OrganizationDeleteParams.none()) + + /** @see delete */ + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Organization = + delete(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see delete */ + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + ): Organization = delete(organizationId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Organization + + /** @see delete */ + fun delete(params: OrganizationDeleteParams): Organization = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(organizationId: String, requestOptions: RequestOptions): Organization = + delete(organizationId, OrganizationDeleteParams.none(), requestOptions) + + /** + * A view of [OrganizationService] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): OrganizationService.WithRawResponse + + fun members(): MemberService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/organization/{organization_id}`, but is + * otherwise the same as [OrganizationService.retrieve]. + */ + @MustBeClosed + fun retrieve(organizationId: String): HttpResponseFor = + retrieve(organizationId, OrganizationRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + organizationId: String, + params: OrganizationRetrieveParams = OrganizationRetrieveParams.none(), + ): HttpResponseFor = retrieve(organizationId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: OrganizationRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + organizationId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + retrieve(organizationId, OrganizationRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/organization/{organization_id}`, but is + * otherwise the same as [OrganizationService.update]. + */ + @MustBeClosed + fun update(organizationId: String): HttpResponseFor = + update(organizationId, OrganizationUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + organizationId: String, + params: OrganizationUpdateParams = OrganizationUpdateParams.none(), + ): HttpResponseFor = update(organizationId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: OrganizationUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + organizationId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + update(organizationId, OrganizationUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/organization`, but is otherwise the same as + * [OrganizationService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(OrganizationListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: OrganizationListParams = OrganizationListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: OrganizationListParams = OrganizationListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(OrganizationListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/organization/{organization_id}`, but is + * otherwise the same as [OrganizationService.delete]. + */ + @MustBeClosed + fun delete(organizationId: String): HttpResponseFor = + delete(organizationId, OrganizationDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().organizationId(organizationId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + organizationId: String, + params: OrganizationDeleteParams = OrganizationDeleteParams.none(), + ): HttpResponseFor = delete(organizationId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: OrganizationDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + organizationId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + delete(organizationId, OrganizationDeleteParams.none(), requestOptions) + } +} 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 new file mode 100755 index 00000000..a12cd028 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceImpl.kt @@ -0,0 +1,220 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.services.blocking.organizations.MemberService +import com.braintrustdata.api.services.blocking.organizations.MemberServiceImpl +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class OrganizationServiceImpl internal constructor(private val clientOptions: ClientOptions) : + OrganizationService { + + private val withRawResponse: OrganizationService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + private val members: MemberService by lazy { MemberServiceImpl(clientOptions) } + + override fun withRawResponse(): OrganizationService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): OrganizationService = + OrganizationServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun members(): MemberService = members + + override fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions, + ): Organization = + // get /v1/organization/{organization_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions, + ): Organization = + // patch /v1/organization/{organization_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: OrganizationListParams, + requestOptions: RequestOptions, + ): OrganizationListPage = + // get /v1/organization + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions, + ): Organization = + // delete /v1/organization/{organization_id} + withRawResponse().delete(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + OrganizationService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val members: MemberService.WithRawResponse by lazy { + MemberServiceImpl.WithRawResponseImpl(clientOptions) + } + + override fun withOptions( + modifier: Consumer + ): OrganizationService.WithRawResponse = + OrganizationServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun members(): MemberService.WithRawResponse = members + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: OrganizationRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("organizationId", params.organizationId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: OrganizationUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("organizationId", params.organizationId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: OrganizationListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + OrganizationListPage.builder() + .service(OrganizationServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: OrganizationDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("organizationId", params.organizationId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreService.kt new file mode 100755 index 00000000..5422601c --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreService.kt @@ -0,0 +1,382 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ProjectScoreListParams +import com.braintrustdata.api.models.ProjectScoreReplaceParams +import com.braintrustdata.api.models.ProjectScoreRetrieveParams +import com.braintrustdata.api.models.ProjectScoreUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface ProjectScoreService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ProjectScoreService + + /** + * Create a new project_score. If there is an existing project_score in the project with the + * same name as the one specified in the request, will return the existing project_score + * unmodified + */ + fun create(params: ProjectScoreCreateParams): ProjectScore = + create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore + + /** Get a project_score object by its id */ + fun retrieve(projectScoreId: String): ProjectScore = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore = + retrieve(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + ): ProjectScore = retrieve(projectScoreId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore + + /** @see retrieve */ + fun retrieve(params: ProjectScoreRetrieveParams): ProjectScore = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(projectScoreId: String, requestOptions: RequestOptions): ProjectScore = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none(), requestOptions) + + /** + * Partially update a project_score object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(projectScoreId: String): ProjectScore = + update(projectScoreId, ProjectScoreUpdateParams.none()) + + /** @see update */ + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore = + update(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see update */ + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + ): ProjectScore = update(projectScoreId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore + + /** @see update */ + fun update(params: ProjectScoreUpdateParams): ProjectScore = + update(params, RequestOptions.none()) + + /** @see update */ + fun update(projectScoreId: String, requestOptions: RequestOptions): ProjectScore = + update(projectScoreId, ProjectScoreUpdateParams.none(), requestOptions) + + /** + * List out all project_scores. The project_scores are sorted by creation date, with the most + * recently-created project_scores coming first + */ + fun list(): ProjectScoreListPage = list(ProjectScoreListParams.none()) + + /** @see list */ + fun list( + params: ProjectScoreListParams = ProjectScoreListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScoreListPage + + /** @see list */ + fun list(params: ProjectScoreListParams = ProjectScoreListParams.none()): ProjectScoreListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): ProjectScoreListPage = + list(ProjectScoreListParams.none(), requestOptions) + + /** Delete a project_score object by its id */ + fun delete(projectScoreId: String): ProjectScore = + delete(projectScoreId, ProjectScoreDeleteParams.none()) + + /** @see delete */ + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore = + delete(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + ): ProjectScore = delete(projectScoreId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore + + /** @see delete */ + fun delete(params: ProjectScoreDeleteParams): ProjectScore = + delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(projectScoreId: String, requestOptions: RequestOptions): ProjectScore = + delete(projectScoreId, ProjectScoreDeleteParams.none(), requestOptions) + + /** + * Create or replace project_score. If there is an existing project_score in the project with + * the same name as the one specified in the request, will replace the existing project_score + * with the provided fields + */ + fun replace(params: ProjectScoreReplaceParams): ProjectScore = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectScore + + /** + * A view of [ProjectScoreService] that provides access to raw HTTP responses for each method. + */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ProjectScoreService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project_score`, but is otherwise the same as + * [ProjectScoreService.create]. + */ + @MustBeClosed + fun create(params: ProjectScoreCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/project_score/{project_score_id}`, but is + * otherwise the same as [ProjectScoreService.retrieve]. + */ + @MustBeClosed + fun retrieve(projectScoreId: String): HttpResponseFor = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectScoreId: String, + params: ProjectScoreRetrieveParams = ProjectScoreRetrieveParams.none(), + ): HttpResponseFor = retrieve(projectScoreId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: ProjectScoreRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectScoreId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + retrieve(projectScoreId, ProjectScoreRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/project_score/{project_score_id}`, but is + * otherwise the same as [ProjectScoreService.update]. + */ + @MustBeClosed + fun update(projectScoreId: String): HttpResponseFor = + update(projectScoreId, ProjectScoreUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + projectScoreId: String, + params: ProjectScoreUpdateParams = ProjectScoreUpdateParams.none(), + ): HttpResponseFor = update(projectScoreId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: ProjectScoreUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + projectScoreId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + update(projectScoreId, ProjectScoreUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/project_score`, but is otherwise the same as + * [ProjectScoreService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(ProjectScoreListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ProjectScoreListParams = ProjectScoreListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: ProjectScoreListParams = ProjectScoreListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ProjectScoreListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/project_score/{project_score_id}`, but is + * otherwise the same as [ProjectScoreService.delete]. + */ + @MustBeClosed + fun delete(projectScoreId: String): HttpResponseFor = + delete(projectScoreId, ProjectScoreDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().projectScoreId(projectScoreId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + projectScoreId: String, + params: ProjectScoreDeleteParams = ProjectScoreDeleteParams.none(), + ): HttpResponseFor = delete(projectScoreId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: ProjectScoreDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + projectScoreId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + delete(projectScoreId, ProjectScoreDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/project_score`, but is otherwise the same as + * [ProjectScoreService.replace]. + */ + @MustBeClosed + fun replace(params: ProjectScoreReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..b6f4f8ec --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceImpl.kt @@ -0,0 +1,280 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.ProjectScoreUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ProjectScoreServiceImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectScoreService { + + private val withRawResponse: ProjectScoreService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ProjectScoreService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ProjectScoreService = + ProjectScoreServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions, + ): ProjectScore = + // post /v1/project_score + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions, + ): ProjectScore = + // get /v1/project_score/{project_score_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions, + ): ProjectScore = + // patch /v1/project_score/{project_score_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: ProjectScoreListParams, + requestOptions: RequestOptions, + ): ProjectScoreListPage = + // get /v1/project_score + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions, + ): ProjectScore = + // delete /v1/project_score/{project_score_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions, + ): ProjectScore = + // put /v1/project_score + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectScoreService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ProjectScoreService.WithRawResponse = + ProjectScoreServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ProjectScoreCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ProjectScoreRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectScoreId", params.projectScoreId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: ProjectScoreUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectScoreId", params.projectScoreId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ProjectScoreListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ProjectScoreListPage.builder() + .service(ProjectScoreServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ProjectScoreDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectScoreId", params.projectScoreId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: ProjectScoreReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_score") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectService.kt old mode 100644 new mode 100755 index 5c9a3be9..c79cab6b --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectService.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectService.kt @@ -1,77 +1,332 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.blocking +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor 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.ProjectListParams -import com.braintrustdata.api.models.ProjectReplaceParams import com.braintrustdata.api.models.ProjectRetrieveParams import com.braintrustdata.api.models.ProjectUpdateParams -import com.braintrustdata.api.services.blocking.project.LogService +import com.braintrustdata.api.services.blocking.projects.LogService +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer interface ProjectService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ProjectService + fun logs(): LogService /** * Create a new project. If there is an existing project with the same name as the one specified * in the request, will return the existing project unmodified */ - @JvmOverloads + fun create(params: ProjectCreateParams): Project = create(params, RequestOptions.none()) + + /** @see create */ fun create( params: ProjectCreateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Project /** Get a project object by its id */ - @JvmOverloads + fun retrieve(projectId: String): Project = retrieve(projectId, ProjectRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Project = retrieve(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + ): Project = retrieve(projectId, params, RequestOptions.none()) + + /** @see retrieve */ fun retrieve( params: ProjectRetrieveParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Project + /** @see retrieve */ + fun retrieve(params: ProjectRetrieveParams): Project = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(projectId: String, requestOptions: RequestOptions): Project = + retrieve(projectId, ProjectRetrieveParams.none(), requestOptions) + /** * Partially update a project object. Specify the fields to update in the payload. Any * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /project/{id}` and then replace it with `PUT /project`. + * removing fields or setting them to null. */ - @JvmOverloads + fun update(projectId: String): Project = update(projectId, ProjectUpdateParams.none()) + + /** @see update */ + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Project = update(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see update */ + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + ): Project = update(projectId, params, RequestOptions.none()) + + /** @see update */ fun update( params: ProjectUpdateParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Project + /** @see update */ + fun update(params: ProjectUpdateParams): Project = update(params, RequestOptions.none()) + + /** @see update */ + fun update(projectId: String, requestOptions: RequestOptions): Project = + update(projectId, ProjectUpdateParams.none(), requestOptions) + /** * List out all projects. The projects are sorted by creation date, with the most * recently-created projects coming first */ - @JvmOverloads + fun list(): ProjectListPage = list(ProjectListParams.none()) + + /** @see list */ fun list( - params: ProjectListParams, - requestOptions: RequestOptions = RequestOptions.none() + params: ProjectListParams = ProjectListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): ProjectListPage + /** @see list */ + fun list(params: ProjectListParams = ProjectListParams.none()): ProjectListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): ProjectListPage = + list(ProjectListParams.none(), requestOptions) + /** Delete a project object by its id */ - @JvmOverloads + fun delete(projectId: String): Project = delete(projectId, ProjectDeleteParams.none()) + + /** @see delete */ + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Project = delete(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + ): Project = delete(projectId, params, RequestOptions.none()) + + /** @see delete */ fun delete( params: ProjectDeleteParams, - requestOptions: RequestOptions = RequestOptions.none() + requestOptions: RequestOptions = RequestOptions.none(), ): Project - /** - * Create or replace a new project. If there is an existing project with the same name as the - * one specified in the request, will replace the existing project with the provided fields - */ - @JvmOverloads - fun replace( - params: ProjectReplaceParams, - requestOptions: RequestOptions = RequestOptions.none() - ): Project + /** @see delete */ + fun delete(params: ProjectDeleteParams): Project = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(projectId: String, requestOptions: RequestOptions): Project = + delete(projectId, ProjectDeleteParams.none(), requestOptions) + + /** A view of [ProjectService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ProjectService.WithRawResponse + + fun logs(): LogService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project`, but is otherwise the same as + * [ProjectService.create]. + */ + @MustBeClosed + fun create(params: ProjectCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: ProjectCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/project/{project_id}`, but is otherwise the same + * as [ProjectService.retrieve]. + */ + @MustBeClosed + fun retrieve(projectId: String): HttpResponseFor = + retrieve(projectId, ProjectRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectId: String, + params: ProjectRetrieveParams = ProjectRetrieveParams.none(), + ): HttpResponseFor = retrieve(projectId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: ProjectRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: ProjectRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(projectId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(projectId, ProjectRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/project/{project_id}`, but is otherwise the + * same as [ProjectService.update]. + */ + @MustBeClosed + fun update(projectId: String): HttpResponseFor = + update(projectId, ProjectUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + projectId: String, + params: ProjectUpdateParams = ProjectUpdateParams.none(), + ): HttpResponseFor = update(projectId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: ProjectUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: ProjectUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update(projectId: String, requestOptions: RequestOptions): HttpResponseFor = + update(projectId, ProjectUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/project`, but is otherwise the same as + * [ProjectService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(ProjectListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ProjectListParams = ProjectListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: ProjectListParams = ProjectListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ProjectListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/project/{project_id}`, but is otherwise the + * same as [ProjectService.delete]. + */ + @MustBeClosed + fun delete(projectId: String): HttpResponseFor = + delete(projectId, ProjectDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + projectId: String, + params: ProjectDeleteParams = ProjectDeleteParams.none(), + ): HttpResponseFor = delete(projectId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: ProjectDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: ProjectDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(projectId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(projectId, ProjectDeleteParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index 529ffda0..ec8c29d3 --- 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 @@ -4,197 +4,235 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +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.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.ProjectReplaceParams import com.braintrustdata.api.models.ProjectRetrieveParams import com.braintrustdata.api.models.ProjectUpdateParams -import com.braintrustdata.api.services.blocking.project.LogService -import com.braintrustdata.api.services.blocking.project.LogServiceImpl -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler +import com.braintrustdata.api.services.blocking.projects.LogService +import com.braintrustdata.api.services.blocking.projects.LogServiceImpl +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull -class ProjectServiceImpl -constructor( - private val clientOptions: ClientOptions, -) : ProjectService { +class ProjectServiceImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: ProjectService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } private val logs: LogService by lazy { LogServiceImpl(clientOptions) } + override fun withRawResponse(): ProjectService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ProjectService = + ProjectServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + override fun logs(): LogService = logs - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create a new project. If there is an existing project with the same name as the one specified - * in the request, will return the existing project unmodified - */ - override fun create(params: ProjectCreateParams, requestOptions: RequestOptions): Project { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } + override fun create(params: ProjectCreateParams, requestOptions: RequestOptions): Project = + // post /v1/project + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: ProjectRetrieveParams, requestOptions: RequestOptions): Project = + // get /v1/project/{project_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: ProjectUpdateParams, requestOptions: RequestOptions): Project = + // patch /v1/project/{project_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list(params: ProjectListParams, requestOptions: RequestOptions): ProjectListPage = + // get /v1/project + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: ProjectDeleteParams, requestOptions: RequestOptions): Project = + // delete /v1/project/{project_id} + withRawResponse().delete(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + private val logs: LogService.WithRawResponse by lazy { + LogServiceImpl.WithRawResponseImpl(clientOptions) } - } - private val retrieveHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Get a project object by its id */ - override fun retrieve(params: ProjectRetrieveParams, requestOptions: RequestOptions): Project { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "project", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { retrieveHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + override fun withOptions( + modifier: Consumer + ): ProjectService.WithRawResponse = + ProjectServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + override fun logs(): LogService.WithRawResponse = logs + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ProjectCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val updateHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Partially update a project object. Specify the fields to update in the payload. Any - * object-type fields will be deep-merged with existing content. Currently we do not support - * removing fields or setting them to null. As a workaround, you may retrieve the full object - * with `GET /project/{id}` and then replace it with `PUT /project`. - */ - override fun update(params: ProjectUpdateParams, requestOptions: RequestOptions): Project { - val request = - HttpRequest.builder() - .method(HttpMethod.PATCH) - .addPathSegments("v1", "project", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { updateHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ProjectRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } - } - private val listHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * List out all projects. The projects are sorted by creation date, with the most - * recently-created projects coming first - */ - override fun list(params: ProjectListParams, requestOptions: RequestOptions): ProjectListPage { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "project") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { listHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: ProjectUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } - .let { ProjectListPage.of(this, params, it) } + } } - } - private val deleteHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** Delete a project object by its id */ - override fun delete(params: ProjectDeleteParams, requestOptions: RequestOptions): Project { - val request = - HttpRequest.builder() - .method(HttpMethod.DELETE) - .addPathSegments("v1", "project", params.getPathParam(0)) - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { deleteHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ProjectListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + .let { + ProjectListPage.builder() + .service(ProjectServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } } - } - private val replaceHandler: Handler = - jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) - - /** - * Create or replace a new project. If there is an existing project with the same name as the - * one specified in the request, will replace the existing project with the provided fields - */ - override fun replace(params: ProjectReplaceParams, requestOptions: RequestOptions): Project { - val request = - HttpRequest.builder() - .method(HttpMethod.PUT) - .addPathSegments("v1", "project") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { replaceHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ProjectDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } } - } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagService.kt new file mode 100755 index 00000000..c6188d4d --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagService.kt @@ -0,0 +1,373 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ProjectTagListParams +import com.braintrustdata.api.models.ProjectTagReplaceParams +import com.braintrustdata.api.models.ProjectTagRetrieveParams +import com.braintrustdata.api.models.ProjectTagUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface ProjectTagService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ProjectTagService + + /** + * Create a new project_tag. If there is an existing project_tag in the project with the same + * name as the one specified in the request, will return the existing project_tag unmodified + */ + fun create(params: ProjectTagCreateParams): ProjectTag = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag + + /** Get a project_tag object by its id */ + fun retrieve(projectTagId: String): ProjectTag = + retrieve(projectTagId, ProjectTagRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag = retrieve(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + ): ProjectTag = retrieve(projectTagId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag + + /** @see retrieve */ + fun retrieve(params: ProjectTagRetrieveParams): ProjectTag = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(projectTagId: String, requestOptions: RequestOptions): ProjectTag = + retrieve(projectTagId, ProjectTagRetrieveParams.none(), requestOptions) + + /** + * Partially update a project_tag object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(projectTagId: String): ProjectTag = + update(projectTagId, ProjectTagUpdateParams.none()) + + /** @see update */ + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag = update(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see update */ + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + ): ProjectTag = update(projectTagId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag + + /** @see update */ + fun update(params: ProjectTagUpdateParams): ProjectTag = update(params, RequestOptions.none()) + + /** @see update */ + fun update(projectTagId: String, requestOptions: RequestOptions): ProjectTag = + update(projectTagId, ProjectTagUpdateParams.none(), requestOptions) + + /** + * List out all project_tags. The project_tags are sorted by creation date, with the most + * recently-created project_tags coming first + */ + fun list(): ProjectTagListPage = list(ProjectTagListParams.none()) + + /** @see list */ + fun list( + params: ProjectTagListParams = ProjectTagListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTagListPage + + /** @see list */ + fun list(params: ProjectTagListParams = ProjectTagListParams.none()): ProjectTagListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): ProjectTagListPage = + list(ProjectTagListParams.none(), requestOptions) + + /** Delete a project_tag object by its id */ + fun delete(projectTagId: String): ProjectTag = + delete(projectTagId, ProjectTagDeleteParams.none()) + + /** @see delete */ + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag = delete(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see delete */ + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + ): ProjectTag = delete(projectTagId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag + + /** @see delete */ + fun delete(params: ProjectTagDeleteParams): ProjectTag = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(projectTagId: String, requestOptions: RequestOptions): ProjectTag = + delete(projectTagId, ProjectTagDeleteParams.none(), requestOptions) + + /** + * Create or replace project_tag. If there is an existing project_tag in the project with the + * same name as the one specified in the request, will replace the existing project_tag with the + * provided fields + */ + fun replace(params: ProjectTagReplaceParams): ProjectTag = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ProjectTag + + /** A view of [ProjectTagService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): ProjectTagService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project_tag`, but is otherwise the same as + * [ProjectTagService.create]. + */ + @MustBeClosed + fun create(params: ProjectTagCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/project_tag/{project_tag_id}`, but is otherwise + * the same as [ProjectTagService.retrieve]. + */ + @MustBeClosed + fun retrieve(projectTagId: String): HttpResponseFor = + retrieve(projectTagId, ProjectTagRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectTagId: String, + params: ProjectTagRetrieveParams = ProjectTagRetrieveParams.none(), + ): HttpResponseFor = retrieve(projectTagId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: ProjectTagRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + projectTagId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + retrieve(projectTagId, ProjectTagRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/project_tag/{project_tag_id}`, but is + * otherwise the same as [ProjectTagService.update]. + */ + @MustBeClosed + fun update(projectTagId: String): HttpResponseFor = + update(projectTagId, ProjectTagUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + projectTagId: String, + params: ProjectTagUpdateParams = ProjectTagUpdateParams.none(), + ): HttpResponseFor = update(projectTagId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: ProjectTagUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + projectTagId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + update(projectTagId, ProjectTagUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/project_tag`, but is otherwise the same as + * [ProjectTagService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(ProjectTagListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ProjectTagListParams = ProjectTagListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: ProjectTagListParams = ProjectTagListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(ProjectTagListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/project_tag/{project_tag_id}`, but is + * otherwise the same as [ProjectTagService.delete]. + */ + @MustBeClosed + fun delete(projectTagId: String): HttpResponseFor = + delete(projectTagId, ProjectTagDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().projectTagId(projectTagId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + projectTagId: String, + params: ProjectTagDeleteParams = ProjectTagDeleteParams.none(), + ): HttpResponseFor = delete(projectTagId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: ProjectTagDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + projectTagId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + delete(projectTagId, ProjectTagDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/project_tag`, but is otherwise the same as + * [ProjectTagService.replace]. + */ + @MustBeClosed + fun replace(params: ProjectTagReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..cae57310 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceImpl.kt @@ -0,0 +1,280 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.ProjectTagUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ProjectTagServiceImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectTagService { + + private val withRawResponse: ProjectTagService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ProjectTagService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ProjectTagService = + ProjectTagServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions, + ): ProjectTag = + // post /v1/project_tag + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions, + ): ProjectTag = + // get /v1/project_tag/{project_tag_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions, + ): ProjectTag = + // patch /v1/project_tag/{project_tag_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: ProjectTagListParams, + requestOptions: RequestOptions, + ): ProjectTagListPage = + // get /v1/project_tag + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions, + ): ProjectTag = + // delete /v1/project_tag/{project_tag_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions, + ): ProjectTag = + // put /v1/project_tag + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ProjectTagService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ProjectTagService.WithRawResponse = + ProjectTagServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ProjectTagCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ProjectTagRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectTagId", params.projectTagId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: ProjectTagUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectTagId", params.projectTagId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ProjectTagListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ProjectTagListPage.builder() + .service(ProjectTagServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ProjectTagDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectTagId", params.projectTagId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: ProjectTagReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_tag") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptService.kt new file mode 100755 index 00000000..46f50a11 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptService.kt @@ -0,0 +1,351 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.PromptListParams +import com.braintrustdata.api.models.PromptReplaceParams +import com.braintrustdata.api.models.PromptRetrieveParams +import com.braintrustdata.api.models.PromptUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface PromptService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): PromptService + + /** + * Create a new prompt. If there is an existing prompt in the project with the same slug as the + * one specified in the request, will return the existing prompt unmodified + */ + fun create(params: PromptCreateParams): Prompt = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: PromptCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt + + /** Get a prompt object by its id */ + fun retrieve(promptId: String): Prompt = retrieve(promptId, PromptRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt = retrieve(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + ): Prompt = retrieve(promptId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: PromptRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt + + /** @see retrieve */ + fun retrieve(params: PromptRetrieveParams): Prompt = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(promptId: String, requestOptions: RequestOptions): Prompt = + retrieve(promptId, PromptRetrieveParams.none(), requestOptions) + + /** + * Partially update a prompt object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(promptId: String): Prompt = update(promptId, PromptUpdateParams.none()) + + /** @see update */ + fun update( + promptId: String, + params: PromptUpdateParams = PromptUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt = update(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see update */ + fun update(promptId: String, params: PromptUpdateParams = PromptUpdateParams.none()): Prompt = + update(promptId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: PromptUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt + + /** @see update */ + fun update(params: PromptUpdateParams): Prompt = update(params, RequestOptions.none()) + + /** @see update */ + fun update(promptId: String, requestOptions: RequestOptions): Prompt = + update(promptId, PromptUpdateParams.none(), requestOptions) + + /** + * List out all prompts. The prompts are sorted by creation date, with the most recently-created + * prompts coming first + */ + fun list(): PromptListPage = list(PromptListParams.none()) + + /** @see list */ + fun list( + params: PromptListParams = PromptListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): PromptListPage + + /** @see list */ + fun list(params: PromptListParams = PromptListParams.none()): PromptListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): PromptListPage = + list(PromptListParams.none(), requestOptions) + + /** Delete a prompt object by its id */ + fun delete(promptId: String): Prompt = delete(promptId, PromptDeleteParams.none()) + + /** @see delete */ + fun delete( + promptId: String, + params: PromptDeleteParams = PromptDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt = delete(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see delete */ + fun delete(promptId: String, params: PromptDeleteParams = PromptDeleteParams.none()): Prompt = + delete(promptId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: PromptDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt + + /** @see delete */ + fun delete(params: PromptDeleteParams): Prompt = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(promptId: String, requestOptions: RequestOptions): Prompt = + delete(promptId, PromptDeleteParams.none(), requestOptions) + + /** + * Create or replace prompt. If there is an existing prompt in the project with the same slug as + * the one specified in the request, will replace the existing prompt with the provided fields + */ + fun replace(params: PromptReplaceParams): Prompt = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: PromptReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Prompt + + /** A view of [PromptService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): PromptService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/prompt`, but is otherwise the same as + * [PromptService.create]. + */ + @MustBeClosed + fun create(params: PromptCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: PromptCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/prompt/{prompt_id}`, but is otherwise the same + * as [PromptService.retrieve]. + */ + @MustBeClosed + fun retrieve(promptId: String): HttpResponseFor = + retrieve(promptId, PromptRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + promptId: String, + params: PromptRetrieveParams = PromptRetrieveParams.none(), + ): HttpResponseFor = retrieve(promptId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: PromptRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: PromptRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(promptId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(promptId, PromptRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/prompt/{prompt_id}`, but is otherwise the same + * as [PromptService.update]. + */ + @MustBeClosed + fun update(promptId: String): HttpResponseFor = + update(promptId, PromptUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + promptId: String, + params: PromptUpdateParams = PromptUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + promptId: String, + params: PromptUpdateParams = PromptUpdateParams.none(), + ): HttpResponseFor = update(promptId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: PromptUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: PromptUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update(promptId: String, requestOptions: RequestOptions): HttpResponseFor = + update(promptId, PromptUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/prompt`, but is otherwise the same as + * [PromptService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(PromptListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: PromptListParams = PromptListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: PromptListParams = PromptListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(PromptListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/prompt/{prompt_id}`, but is otherwise the + * same as [PromptService.delete]. + */ + @MustBeClosed + fun delete(promptId: String): HttpResponseFor = + delete(promptId, PromptDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + promptId: String, + params: PromptDeleteParams = PromptDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().promptId(promptId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + promptId: String, + params: PromptDeleteParams = PromptDeleteParams.none(), + ): HttpResponseFor = delete(promptId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: PromptDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: PromptDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(promptId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(promptId, PromptDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/prompt`, but is otherwise the same as + * [PromptService.replace]. + */ + @MustBeClosed + fun replace(params: PromptReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: PromptReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..2abf6d64 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/PromptServiceImpl.kt @@ -0,0 +1,257 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.PromptUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class PromptServiceImpl internal constructor(private val clientOptions: ClientOptions) : + PromptService { + + private val withRawResponse: PromptService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): PromptService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): PromptService = + PromptServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: PromptCreateParams, requestOptions: RequestOptions): Prompt = + // post /v1/prompt + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: PromptRetrieveParams, requestOptions: RequestOptions): Prompt = + // get /v1/prompt/{prompt_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: PromptUpdateParams, requestOptions: RequestOptions): Prompt = + // patch /v1/prompt/{prompt_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list(params: PromptListParams, requestOptions: RequestOptions): PromptListPage = + // get /v1/prompt + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: PromptDeleteParams, requestOptions: RequestOptions): Prompt = + // delete /v1/prompt/{prompt_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace(params: PromptReplaceParams, requestOptions: RequestOptions): Prompt = + // put /v1/prompt + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + PromptService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): PromptService.WithRawResponse = + PromptServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: PromptCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: PromptRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("promptId", params.promptId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: PromptUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("promptId", params.promptId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: PromptListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + PromptListPage.builder() + .service(PromptServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: PromptDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("promptId", params.promptId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: PromptReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "prompt") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleService.kt new file mode 100755 index 00000000..a6ba04a2 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleService.kt @@ -0,0 +1,344 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.RoleListParams +import com.braintrustdata.api.models.RoleReplaceParams +import com.braintrustdata.api.models.RoleRetrieveParams +import com.braintrustdata.api.models.RoleUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface RoleService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): RoleService + + /** + * Create a new role. If there is an existing role with the same name as the one specified in + * the request, will return the existing role unmodified + */ + fun create(params: RoleCreateParams): Role = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: RoleCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Role + + /** Get a role object by its id */ + fun retrieve(roleId: String): Role = retrieve(roleId, RoleRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + roleId: String, + params: RoleRetrieveParams = RoleRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Role = retrieve(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve(roleId: String, params: RoleRetrieveParams = RoleRetrieveParams.none()): Role = + retrieve(roleId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: RoleRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Role + + /** @see retrieve */ + fun retrieve(params: RoleRetrieveParams): Role = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(roleId: String, requestOptions: RequestOptions): Role = + retrieve(roleId, RoleRetrieveParams.none(), requestOptions) + + /** + * Partially update a role object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields + * or setting them to null. + */ + fun update(roleId: String): Role = update(roleId, RoleUpdateParams.none()) + + /** @see update */ + fun update( + roleId: String, + params: RoleUpdateParams = RoleUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Role = update(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see update */ + fun update(roleId: String, params: RoleUpdateParams = RoleUpdateParams.none()): Role = + update(roleId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: RoleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Role + + /** @see update */ + fun update(params: RoleUpdateParams): Role = update(params, RequestOptions.none()) + + /** @see update */ + fun update(roleId: String, requestOptions: RequestOptions): Role = + update(roleId, RoleUpdateParams.none(), requestOptions) + + /** + * List out all roles. The roles are sorted by creation date, with the most recently-created + * roles coming first + */ + fun list(): RoleListPage = list(RoleListParams.none()) + + /** @see list */ + fun list( + params: RoleListParams = RoleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): RoleListPage + + /** @see list */ + fun list(params: RoleListParams = RoleListParams.none()): RoleListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): RoleListPage = + list(RoleListParams.none(), requestOptions) + + /** Delete a role object by its id */ + fun delete(roleId: String): Role = delete(roleId, RoleDeleteParams.none()) + + /** @see delete */ + fun delete( + roleId: String, + params: RoleDeleteParams = RoleDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): Role = delete(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see delete */ + fun delete(roleId: String, params: RoleDeleteParams = RoleDeleteParams.none()): Role = + delete(roleId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: RoleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Role + + /** @see delete */ + fun delete(params: RoleDeleteParams): Role = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(roleId: String, requestOptions: RequestOptions): Role = + delete(roleId, RoleDeleteParams.none(), requestOptions) + + /** + * Create or replace role. If there is an existing role with the same name as the one specified + * in the request, will replace the existing role with the provided fields + */ + fun replace(params: RoleReplaceParams): Role = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: RoleReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): Role + + /** A view of [RoleService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): RoleService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/role`, but is otherwise the same as + * [RoleService.create]. + */ + @MustBeClosed + fun create(params: RoleCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: RoleCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/role/{role_id}`, but is otherwise the same as + * [RoleService.retrieve]. + */ + @MustBeClosed + fun retrieve(roleId: String): HttpResponseFor = + retrieve(roleId, RoleRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + roleId: String, + params: RoleRetrieveParams = RoleRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + roleId: String, + params: RoleRetrieveParams = RoleRetrieveParams.none(), + ): HttpResponseFor = retrieve(roleId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: RoleRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: RoleRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(roleId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(roleId, RoleRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/role/{role_id}`, but is otherwise the same as + * [RoleService.update]. + */ + @MustBeClosed + fun update(roleId: String): HttpResponseFor = update(roleId, RoleUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + roleId: String, + params: RoleUpdateParams = RoleUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = update(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + roleId: String, + params: RoleUpdateParams = RoleUpdateParams.none(), + ): HttpResponseFor = update(roleId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: RoleUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: RoleUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update(roleId: String, requestOptions: RequestOptions): HttpResponseFor = + update(roleId, RoleUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/role`, but is otherwise the same as + * [RoleService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(RoleListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: RoleListParams = RoleListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list(params: RoleListParams = RoleListParams.none()): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(RoleListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/role/{role_id}`, but is otherwise the same as + * [RoleService.delete]. + */ + @MustBeClosed + fun delete(roleId: String): HttpResponseFor = delete(roleId, RoleDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + roleId: String, + params: RoleDeleteParams = RoleDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = delete(params.toBuilder().roleId(roleId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + roleId: String, + params: RoleDeleteParams = RoleDeleteParams.none(), + ): HttpResponseFor = delete(roleId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: RoleDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: RoleDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete(roleId: String, requestOptions: RequestOptions): HttpResponseFor = + delete(roleId, RoleDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/role`, but is otherwise the same as + * [RoleService.replace]. + */ + @MustBeClosed + fun replace(params: RoleReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: RoleReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..091c5fcb --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/RoleServiceImpl.kt @@ -0,0 +1,256 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.RoleUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class RoleServiceImpl internal constructor(private val clientOptions: ClientOptions) : RoleService { + + private val withRawResponse: RoleService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): RoleService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): RoleService = + RoleServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: RoleCreateParams, requestOptions: RequestOptions): Role = + // post /v1/role + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: RoleRetrieveParams, requestOptions: RequestOptions): Role = + // get /v1/role/{role_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: RoleUpdateParams, requestOptions: RequestOptions): Role = + // patch /v1/role/{role_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list(params: RoleListParams, requestOptions: RequestOptions): RoleListPage = + // get /v1/role + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: RoleDeleteParams, requestOptions: RequestOptions): Role = + // delete /v1/role/{role_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace(params: RoleReplaceParams, requestOptions: RequestOptions): Role = + // put /v1/role + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + RoleService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): RoleService.WithRawResponse = + RoleServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: RoleCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: RoleRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("roleId", params.roleId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: RoleUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("roleId", params.roleId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: RoleListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + RoleListPage.builder() + .service(RoleServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: RoleDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("roleId", params.roleId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: RoleReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "role") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeService.kt new file mode 100644 index 00000000..d0b65980 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeService.kt @@ -0,0 +1,372 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.SpanIframeListParams +import com.braintrustdata.api.models.SpanIframeReplaceParams +import com.braintrustdata.api.models.SpanIframeRetrieveParams +import com.braintrustdata.api.models.SpanIframeUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface SpanIframeService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): SpanIframeService + + /** + * Create a new span_iframe. If there is an existing span_iframe with the same name as the one + * specified in the request, will return the existing span_iframe unmodified + */ + fun create(params: SpanIframeCreateParams): SpanIFrame = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame + + /** Get a span_iframe object by its id */ + fun retrieve(spanIframeId: String): SpanIFrame = + retrieve(spanIframeId, SpanIframeRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame = retrieve(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + ): SpanIFrame = retrieve(spanIframeId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame + + /** @see retrieve */ + fun retrieve(params: SpanIframeRetrieveParams): SpanIFrame = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(spanIframeId: String, requestOptions: RequestOptions): SpanIFrame = + retrieve(spanIframeId, SpanIframeRetrieveParams.none(), requestOptions) + + /** + * Partially update a span_iframe object. Specify the fields to update in the payload. Any + * object-type fields will be deep-merged with existing content. Currently we do not support + * removing fields or setting them to null. + */ + fun update(spanIframeId: String): SpanIFrame = + update(spanIframeId, SpanIframeUpdateParams.none()) + + /** @see update */ + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame = update(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see update */ + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + ): SpanIFrame = update(spanIframeId, params, RequestOptions.none()) + + /** @see update */ + fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame + + /** @see update */ + fun update(params: SpanIframeUpdateParams): SpanIFrame = update(params, RequestOptions.none()) + + /** @see update */ + fun update(spanIframeId: String, requestOptions: RequestOptions): SpanIFrame = + update(spanIframeId, SpanIframeUpdateParams.none(), requestOptions) + + /** + * List out all span_iframes. The span_iframes are sorted by creation date, with the most + * recently-created span_iframes coming first + */ + fun list(): SpanIframeListPage = list(SpanIframeListParams.none()) + + /** @see list */ + fun list( + params: SpanIframeListParams = SpanIframeListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIframeListPage + + /** @see list */ + fun list(params: SpanIframeListParams = SpanIframeListParams.none()): SpanIframeListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): SpanIframeListPage = + list(SpanIframeListParams.none(), requestOptions) + + /** Delete a span_iframe object by its id */ + fun delete(spanIframeId: String): SpanIFrame = + delete(spanIframeId, SpanIframeDeleteParams.none()) + + /** @see delete */ + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame = delete(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see delete */ + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + ): SpanIFrame = delete(spanIframeId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame + + /** @see delete */ + fun delete(params: SpanIframeDeleteParams): SpanIFrame = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete(spanIframeId: String, requestOptions: RequestOptions): SpanIFrame = + delete(spanIframeId, SpanIframeDeleteParams.none(), requestOptions) + + /** + * Create or replace span_iframe. If there is an existing span_iframe with the same name as the + * one specified in the request, will replace the existing span_iframe with the provided fields + */ + fun replace(params: SpanIframeReplaceParams): SpanIFrame = + replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): SpanIFrame + + /** A view of [SpanIframeService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions( + modifier: Consumer + ): SpanIframeService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/span_iframe`, but is otherwise the same as + * [SpanIframeService.create]. + */ + @MustBeClosed + fun create(params: SpanIframeCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/span_iframe/{span_iframe_id}`, but is otherwise + * the same as [SpanIframeService.retrieve]. + */ + @MustBeClosed + fun retrieve(spanIframeId: String): HttpResponseFor = + retrieve(spanIframeId, SpanIframeRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + spanIframeId: String, + params: SpanIframeRetrieveParams = SpanIframeRetrieveParams.none(), + ): HttpResponseFor = retrieve(spanIframeId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: SpanIframeRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + spanIframeId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + retrieve(spanIframeId, SpanIframeRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `patch /v1/span_iframe/{span_iframe_id}`, but is + * otherwise the same as [SpanIframeService.update]. + */ + @MustBeClosed + fun update(spanIframeId: String): HttpResponseFor = + update(spanIframeId, SpanIframeUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + update(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update( + spanIframeId: String, + params: SpanIframeUpdateParams = SpanIframeUpdateParams.none(), + ): HttpResponseFor = update(spanIframeId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update(params: SpanIframeUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + spanIframeId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + update(spanIframeId, SpanIframeUpdateParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/span_iframe`, but is otherwise the same as + * [SpanIframeService.list]. + */ + @MustBeClosed + fun list(): HttpResponseFor = list(SpanIframeListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: SpanIframeListParams = SpanIframeListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list( + params: SpanIframeListParams = SpanIframeListParams.none() + ): HttpResponseFor = list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(SpanIframeListParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `delete /v1/span_iframe/{span_iframe_id}`, but is + * otherwise the same as [SpanIframeService.delete]. + */ + @MustBeClosed + fun delete(spanIframeId: String): HttpResponseFor = + delete(spanIframeId, SpanIframeDeleteParams.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + delete(params.toBuilder().spanIframeId(spanIframeId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete( + spanIframeId: String, + params: SpanIframeDeleteParams = SpanIframeDeleteParams.none(), + ): HttpResponseFor = delete(spanIframeId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see delete */ + @MustBeClosed + fun delete(params: SpanIframeDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + spanIframeId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + delete(spanIframeId, SpanIframeDeleteParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `put /v1/span_iframe`, but is otherwise the same as + * [SpanIframeService.replace]. + */ + @MustBeClosed + fun replace(params: SpanIframeReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100644 index 00000000..5d1a2af3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceImpl.kt @@ -0,0 +1,280 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.SpanIframeUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class SpanIframeServiceImpl internal constructor(private val clientOptions: ClientOptions) : + SpanIframeService { + + private val withRawResponse: SpanIframeService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): SpanIframeService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): SpanIframeService = + SpanIframeServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions, + ): SpanIFrame = + // post /v1/span_iframe + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions, + ): SpanIFrame = + // get /v1/span_iframe/{span_iframe_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions, + ): SpanIFrame = + // patch /v1/span_iframe/{span_iframe_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list( + params: SpanIframeListParams, + requestOptions: RequestOptions, + ): SpanIframeListPage = + // get /v1/span_iframe + withRawResponse().list(params, requestOptions).parse() + + override fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions, + ): SpanIFrame = + // delete /v1/span_iframe/{span_iframe_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions, + ): SpanIFrame = + // put /v1/span_iframe + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + SpanIframeService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): SpanIframeService.WithRawResponse = + SpanIframeServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: SpanIframeCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: SpanIframeRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("spanIframeId", params.spanIframeId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: SpanIframeUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("spanIframeId", params.spanIframeId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: SpanIframeListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + SpanIframeListPage.builder() + .service(SpanIframeServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: SpanIframeDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("spanIframeId", params.spanIframeId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe", params._pathParam(0)) + .apply { params._body().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: SpanIframeReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "span_iframe") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelService.kt old mode 100644 new mode 100755 index 5aba74fe..ba60b79a --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelService.kt +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/TopLevelService.kt @@ -1,18 +1,78 @@ // File generated from our OpenAPI spec by Stainless. -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - package com.braintrustdata.api.services.blocking +import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor import com.braintrustdata.api.models.TopLevelHelloWorldParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer interface TopLevelService { + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): TopLevelService + /** Default endpoint. Simply replies with 'Hello, World!'. Authorization is not required */ - @JvmOverloads + fun helloWorld(): String = helloWorld(TopLevelHelloWorldParams.none()) + + /** @see helloWorld */ fun helloWorld( - params: TopLevelHelloWorldParams, - requestOptions: RequestOptions = RequestOptions.none() + params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), ): String + + /** @see helloWorld */ + fun helloWorld(params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none()): String = + helloWorld(params, RequestOptions.none()) + + /** @see helloWorld */ + fun helloWorld(requestOptions: RequestOptions): String = + helloWorld(TopLevelHelloWorldParams.none(), requestOptions) + + /** A view of [TopLevelService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): TopLevelService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1`, but is otherwise the same as + * [TopLevelService.helloWorld]. + */ + @MustBeClosed + fun helloWorld(): HttpResponseFor = helloWorld(TopLevelHelloWorldParams.none()) + + /** @see helloWorld */ + @MustBeClosed + fun helloWorld( + params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see helloWorld */ + @MustBeClosed + fun helloWorld( + params: TopLevelHelloWorldParams = TopLevelHelloWorldParams.none() + ): HttpResponseFor = helloWorld(params, RequestOptions.none()) + + /** @see helloWorld */ + @MustBeClosed + fun helloWorld(requestOptions: RequestOptions): HttpResponseFor = + helloWorld(TopLevelHelloWorldParams.none(), requestOptions) + } } 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 old mode 100644 new mode 100755 index be89b30f..a04c4278 --- 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 @@ -4,39 +4,69 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.stringHandler import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.core.http.parseable +import com.braintrustdata.api.core.prepare import com.braintrustdata.api.models.TopLevelHelloWorldParams -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.stringHandler -import com.braintrustdata.api.services.withErrorHandler +import java.util.function.Consumer -class TopLevelServiceImpl -constructor( - private val clientOptions: ClientOptions, -) : TopLevelService { +class TopLevelServiceImpl internal constructor(private val clientOptions: ClientOptions) : + TopLevelService { - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val withRawResponse: TopLevelService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): TopLevelService.WithRawResponse = withRawResponse - private val helloWorldHandler: Handler = stringHandler().withErrorHandler(errorHandler) + override fun withOptions(modifier: Consumer): TopLevelService = + TopLevelServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) - /** Default endpoint. Simply replies with 'Hello, World!'. Authorization is not required */ override fun helloWorld( params: TopLevelHelloWorldParams, - requestOptions: RequestOptions - ): String { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response.use { helloWorldHandler.handle(it) } + requestOptions: RequestOptions, + ): String = + // get /v1 + withRawResponse().helloWorld(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + TopLevelService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): TopLevelService.WithRawResponse = + TopLevelServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val helloWorldHandler: Handler = stringHandler() + + override fun helloWorld( + params: TopLevelHelloWorldParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response.use { helloWorldHandler.handle(it) } + } } } } diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserService.kt new file mode 100755 index 00000000..802878d1 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserService.kt @@ -0,0 +1,150 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.User +import com.braintrustdata.api.models.UserListPage +import com.braintrustdata.api.models.UserListParams +import com.braintrustdata.api.models.UserRetrieveParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface UserService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UserService + + /** Get a user object by its id */ + fun retrieve(userId: String): User = retrieve(userId, UserRetrieveParams.none()) + + /** @see retrieve */ + fun retrieve( + userId: String, + params: UserRetrieveParams = UserRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): User = retrieve(params.toBuilder().userId(userId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve(userId: String, params: UserRetrieveParams = UserRetrieveParams.none()): User = + retrieve(userId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: UserRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): User + + /** @see retrieve */ + fun retrieve(params: UserRetrieveParams): User = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve(userId: String, requestOptions: RequestOptions): User = + retrieve(userId, UserRetrieveParams.none(), requestOptions) + + /** + * List out all users. The users are sorted by creation date, with the most recently-created + * users coming first + */ + fun list(): UserListPage = list(UserListParams.none()) + + /** @see list */ + fun list( + params: UserListParams = UserListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): UserListPage + + /** @see list */ + fun list(params: UserListParams = UserListParams.none()): UserListPage = + list(params, RequestOptions.none()) + + /** @see list */ + fun list(requestOptions: RequestOptions): UserListPage = + list(UserListParams.none(), requestOptions) + + /** A view of [UserService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): UserService.WithRawResponse + + /** + * Returns a raw HTTP response for `get /v1/user/{user_id}`, but is otherwise the same as + * [UserService.retrieve]. + */ + @MustBeClosed + fun retrieve(userId: String): HttpResponseFor = + retrieve(userId, UserRetrieveParams.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + userId: String, + params: UserRetrieveParams = UserRetrieveParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().userId(userId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + userId: String, + params: UserRetrieveParams = UserRetrieveParams.none(), + ): HttpResponseFor = retrieve(userId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: UserRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: UserRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(userId: String, requestOptions: RequestOptions): HttpResponseFor = + retrieve(userId, UserRetrieveParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `get /v1/user`, but is otherwise the same as + * [UserService.list]. + */ + @MustBeClosed fun list(): HttpResponseFor = list(UserListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: UserListParams = UserListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list(params: UserListParams = UserListParams.none()): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list(requestOptions: RequestOptions): HttpResponseFor = + list(UserListParams.none(), requestOptions) + } +} 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 new file mode 100755 index 00000000..3e44a297 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/UserServiceImpl.kt @@ -0,0 +1,121 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +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.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 +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class UserServiceImpl internal constructor(private val clientOptions: ClientOptions) : UserService { + + private val withRawResponse: UserService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): UserService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): UserService = + UserServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun retrieve(params: UserRetrieveParams, requestOptions: RequestOptions): User = + // get /v1/user/{user_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun list(params: UserListParams, requestOptions: RequestOptions): UserListPage = + // get /v1/user + withRawResponse().list(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + UserService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): UserService.WithRawResponse = + UserServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: UserRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("userId", params.userId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "user", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: UserListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "user") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .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/ViewService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ViewService.kt new file mode 100755 index 00000000..ee428b59 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ViewService.kt @@ -0,0 +1,273 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +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.ViewListParams +import com.braintrustdata.api.models.ViewReplaceParams +import com.braintrustdata.api.models.ViewRetrieveParams +import com.braintrustdata.api.models.ViewUpdateParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface ViewService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ViewService + + /** + * Create a new view. If there is an existing view with the same name as the one specified in + * the request, will return the existing view unmodified + */ + fun create(params: ViewCreateParams): View = create(params, RequestOptions.none()) + + /** @see create */ + fun create( + params: ViewCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View + + /** Get a view object by its id */ + fun retrieve(viewId: String, params: ViewRetrieveParams): View = + retrieve(viewId, params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + viewId: String, + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View = retrieve(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see retrieve */ + fun retrieve(params: ViewRetrieveParams): View = retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + fun retrieve( + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View + + /** + * Partially update a view object. Specify the fields to update in the payload. Any object-type + * fields will be deep-merged with existing content. Currently we do not support removing fields + * or setting them to null. + */ + fun update(viewId: String, params: ViewUpdateParams): View = + update(viewId, params, RequestOptions.none()) + + /** @see update */ + fun update( + viewId: String, + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View = update(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see update */ + fun update(params: ViewUpdateParams): View = update(params, RequestOptions.none()) + + /** @see update */ + fun update( + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View + + /** + * List out all views. The views are sorted by creation date, with the most recently-created + * views coming first + */ + fun list(params: ViewListParams): ViewListPage = list(params, RequestOptions.none()) + + /** @see list */ + fun list( + params: ViewListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): ViewListPage + + /** Delete a view object by its id */ + fun delete(viewId: String, params: ViewDeleteParams): View = + delete(viewId, params, RequestOptions.none()) + + /** @see delete */ + fun delete( + viewId: String, + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View = delete(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see delete */ + fun delete(params: ViewDeleteParams): View = delete(params, RequestOptions.none()) + + /** @see delete */ + fun delete( + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View + + /** + * Create or replace view. If there is an existing view with the same name as the one specified + * in the request, will replace the existing view with the provided fields + */ + fun replace(params: ViewReplaceParams): View = replace(params, RequestOptions.none()) + + /** @see replace */ + fun replace( + params: ViewReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): View + + /** A view of [ViewService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): ViewService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/view`, but is otherwise the same as + * [ViewService.create]. + */ + @MustBeClosed + fun create(params: ViewCreateParams): HttpResponseFor = + create(params, RequestOptions.none()) + + /** @see create */ + @MustBeClosed + fun create( + params: ViewCreateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/view/{view_id}`, but is otherwise the same as + * [ViewService.retrieve]. + */ + @MustBeClosed + fun retrieve(viewId: String, params: ViewRetrieveParams): HttpResponseFor = + retrieve(viewId, params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + viewId: String, + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + retrieve(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see retrieve */ + @MustBeClosed + fun retrieve(params: ViewRetrieveParams): HttpResponseFor = + retrieve(params, RequestOptions.none()) + + /** @see retrieve */ + @MustBeClosed + fun retrieve( + params: ViewRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `patch /v1/view/{view_id}`, but is otherwise the same as + * [ViewService.update]. + */ + @MustBeClosed + fun update(viewId: String, params: ViewUpdateParams): HttpResponseFor = + update(viewId, params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + viewId: String, + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = update(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see update */ + @MustBeClosed + fun update(params: ViewUpdateParams): HttpResponseFor = + update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: ViewUpdateParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/view`, but is otherwise the same as + * [ViewService.list]. + */ + @MustBeClosed + fun list(params: ViewListParams): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: ViewListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `delete /v1/view/{view_id}`, but is otherwise the same as + * [ViewService.delete]. + */ + @MustBeClosed + fun delete(viewId: String, params: ViewDeleteParams): HttpResponseFor = + delete(viewId, params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + viewId: String, + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = delete(params.toBuilder().viewId(viewId).build(), requestOptions) + + /** @see delete */ + @MustBeClosed + fun delete(params: ViewDeleteParams): HttpResponseFor = + delete(params, RequestOptions.none()) + + /** @see delete */ + @MustBeClosed + fun delete( + params: ViewDeleteParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `put /v1/view`, but is otherwise the same as + * [ViewService.replace]. + */ + @MustBeClosed + fun replace(params: ViewReplaceParams): HttpResponseFor = + replace(params, RequestOptions.none()) + + /** @see replace */ + @MustBeClosed + fun replace( + params: ViewReplaceParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100755 index 00000000..6fcff875 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/ViewServiceImpl.kt @@ -0,0 +1,256 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.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 +import com.braintrustdata.api.models.ViewUpdateParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class ViewServiceImpl internal constructor(private val clientOptions: ClientOptions) : ViewService { + + private val withRawResponse: ViewService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): ViewService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): ViewService = + ViewServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun create(params: ViewCreateParams, requestOptions: RequestOptions): View = + // post /v1/view + withRawResponse().create(params, requestOptions).parse() + + override fun retrieve(params: ViewRetrieveParams, requestOptions: RequestOptions): View = + // get /v1/view/{view_id} + withRawResponse().retrieve(params, requestOptions).parse() + + override fun update(params: ViewUpdateParams, requestOptions: RequestOptions): View = + // patch /v1/view/{view_id} + withRawResponse().update(params, requestOptions).parse() + + override fun list(params: ViewListParams, requestOptions: RequestOptions): ViewListPage = + // get /v1/view + withRawResponse().list(params, requestOptions).parse() + + override fun delete(params: ViewDeleteParams, requestOptions: RequestOptions): View = + // delete /v1/view/{view_id} + withRawResponse().delete(params, requestOptions).parse() + + override fun replace(params: ViewReplaceParams, requestOptions: RequestOptions): View = + // put /v1/view + withRawResponse().replace(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + ViewService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): ViewService.WithRawResponse = + ViewServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun create( + params: ViewCreateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { createHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val retrieveHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun retrieve( + params: ViewRetrieveParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("viewId", params.viewId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view", params._pathParam(0)) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { retrieveHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val updateHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: ViewUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("viewId", params.viewId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: ViewListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + ViewListPage.builder() + .service(ViewServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun delete( + params: ViewDeleteParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("viewId", params.viewId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view", params._pathParam(0)) + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { deleteHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val replaceHandler: Handler = jsonHandler(clientOptions.jsonMapper) + + override fun replace( + params: ViewReplaceParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PUT) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "view") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { replaceHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberService.kt new file mode 100644 index 00000000..d664ed0e --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberService.kt @@ -0,0 +1,83 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking.organizations + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.OrganizationMemberUpdateParams +import com.braintrustdata.api.models.PatchOrganizationMembersOutput +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface MemberService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): MemberService + + /** Modify organization membership */ + fun update(): PatchOrganizationMembersOutput = update(OrganizationMemberUpdateParams.none()) + + /** @see update */ + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): PatchOrganizationMembersOutput + + /** @see update */ + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none() + ): PatchOrganizationMembersOutput = update(params, RequestOptions.none()) + + /** @see update */ + fun update(requestOptions: RequestOptions): PatchOrganizationMembersOutput = + update(OrganizationMemberUpdateParams.none(), requestOptions) + + /** A view of [MemberService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): MemberService.WithRawResponse + + /** + * Returns a raw HTTP response for `patch /v1/organization/members`, but is otherwise the + * same as [MemberService.update]. + */ + @MustBeClosed + fun update(): HttpResponseFor = + update(OrganizationMemberUpdateParams.none()) + + /** @see update */ + @MustBeClosed + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see update */ + @MustBeClosed + fun update( + params: OrganizationMemberUpdateParams = OrganizationMemberUpdateParams.none() + ): HttpResponseFor = update(params, RequestOptions.none()) + + /** @see update */ + @MustBeClosed + fun update( + requestOptions: RequestOptions + ): HttpResponseFor = + update(OrganizationMemberUpdateParams.none(), requestOptions) + } +} 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 new file mode 100644 index 00000000..23d69d69 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceImpl.kt @@ -0,0 +1,82 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking.organizations + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.OrganizationMemberUpdateParams +import com.braintrustdata.api.models.PatchOrganizationMembersOutput +import java.util.function.Consumer + +class MemberServiceImpl internal constructor(private val clientOptions: ClientOptions) : + MemberService { + + private val withRawResponse: MemberService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): MemberService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): MemberService = + MemberServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun update( + params: OrganizationMemberUpdateParams, + requestOptions: RequestOptions, + ): PatchOrganizationMembersOutput = + // patch /v1/organization/members + withRawResponse().update(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + MemberService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): MemberService.WithRawResponse = + MemberServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val updateHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun update( + params: OrganizationMemberUpdateParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + val request = + HttpRequest.builder() + .method(HttpMethod.PATCH) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "organization", "members") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { updateHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/project/LogService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/project/LogService.kt deleted file mode 100644 index 6970afa4..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/project/LogService.kt +++ /dev/null @@ -1,51 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - -package com.braintrustdata.api.services.blocking.project - -import com.braintrustdata.api.core.RequestOptions -import com.braintrustdata.api.models.ProjectLogFeedbackParams -import com.braintrustdata.api.models.ProjectLogFetchParams -import com.braintrustdata.api.models.ProjectLogFetchPostParams -import com.braintrustdata.api.models.ProjectLogFetchPostResponse -import com.braintrustdata.api.models.ProjectLogFetchResponse -import com.braintrustdata.api.models.ProjectLogInsertParams -import com.braintrustdata.api.models.ProjectLogInsertResponse - -interface LogService { - - /** Log feedback for a set of project logs events */ - @JvmOverloads - fun feedback( - params: ProjectLogFeedbackParams, - requestOptions: RequestOptions = RequestOptions.none() - ) - - /** - * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with - * the parameters in the URL query rather than in the request body - */ - @JvmOverloads - fun fetch( - params: ProjectLogFetchParams, - requestOptions: RequestOptions = RequestOptions.none() - ): ProjectLogFetchResponse - - /** - * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - @JvmOverloads - fun fetchPost( - params: ProjectLogFetchPostParams, - requestOptions: RequestOptions = RequestOptions.none() - ): ProjectLogFetchPostResponse - - /** Insert a set of events into the project logs */ - @JvmOverloads - fun insert( - params: ProjectLogInsertParams, - requestOptions: RequestOptions = RequestOptions.none() - ): ProjectLogInsertResponse -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/project/LogServiceImpl.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/project/LogServiceImpl.kt deleted file mode 100644 index 2ccbbe73..00000000 --- a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/project/LogServiceImpl.kt +++ /dev/null @@ -1,140 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.services.blocking.project - -import com.braintrustdata.api.core.ClientOptions -import com.braintrustdata.api.core.RequestOptions -import com.braintrustdata.api.core.http.HttpMethod -import com.braintrustdata.api.core.http.HttpRequest -import com.braintrustdata.api.core.http.HttpResponse.Handler -import com.braintrustdata.api.errors.BraintrustError -import com.braintrustdata.api.models.ProjectLogFeedbackParams -import com.braintrustdata.api.models.ProjectLogFetchParams -import com.braintrustdata.api.models.ProjectLogFetchPostParams -import com.braintrustdata.api.models.ProjectLogFetchPostResponse -import com.braintrustdata.api.models.ProjectLogFetchResponse -import com.braintrustdata.api.models.ProjectLogInsertParams -import com.braintrustdata.api.models.ProjectLogInsertResponse -import com.braintrustdata.api.services.emptyHandler -import com.braintrustdata.api.services.errorHandler -import com.braintrustdata.api.services.json -import com.braintrustdata.api.services.jsonHandler -import com.braintrustdata.api.services.withErrorHandler - -class LogServiceImpl -constructor( - private val clientOptions: ClientOptions, -) : LogService { - - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val feedbackHandler: Handler = emptyHandler().withErrorHandler(errorHandler) - - /** Log feedback for a set of project logs events */ - override fun feedback(params: ProjectLogFeedbackParams, requestOptions: RequestOptions) { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "feedback") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - clientOptions.httpClient.execute(request, requestOptions).let { response -> - response.use { feedbackHandler.handle(it) } - } - } - - private val fetchHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with - * the parameters in the URL query rather than in the request body - */ - override fun fetch( - params: ProjectLogFetchParams, - requestOptions: RequestOptions - ): ProjectLogFetchResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.GET) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { fetchHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } - - private val fetchPostHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the - * parameters in the request body rather than in the URL query - */ - override fun fetchPost( - params: ProjectLogFetchPostParams, - requestOptions: RequestOptions - ): ProjectLogFetchPostResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { fetchPostHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } - - private val insertHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** Insert a set of events into the project logs */ - override fun insert( - params: ProjectLogInsertParams, - requestOptions: RequestOptions - ): ProjectLogInsertResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "project_logs", params.getPathParam(0), "insert") - .putAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .putAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient.execute(request, requestOptions).let { response -> - response - .use { insertHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } -} diff --git a/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogService.kt b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogService.kt new file mode 100644 index 00000000..c12218d3 --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogService.kt @@ -0,0 +1,316 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking.projects + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.http.HttpResponseFor +import com.braintrustdata.api.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchProjectLogsEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.ProjectLogFeedbackParams +import com.braintrustdata.api.models.ProjectLogFetchParams +import com.braintrustdata.api.models.ProjectLogFetchPostParams +import com.braintrustdata.api.models.ProjectLogInsertParams +import com.google.errorprone.annotations.MustBeClosed +import java.util.function.Consumer + +interface LogService { + + /** + * Returns a view of this service that provides access to raw HTTP responses for each method. + */ + fun withRawResponse(): WithRawResponse + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): LogService + + /** Log feedback for a set of project logs events */ + fun feedback(projectId: String, params: ProjectLogFeedbackParams): FeedbackResponseSchema = + feedback(projectId, params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + projectId: String, + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FeedbackResponseSchema = + feedback(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see feedback */ + fun feedback(params: ProjectLogFeedbackParams): FeedbackResponseSchema = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FeedbackResponseSchema + + /** + * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with + * the parameters in the URL query rather than in the request body. For more complex queries, + * use the `POST /btql` endpoint. + */ + fun fetch(projectId: String): FetchProjectLogsEventsResponse = + fetch(projectId, ProjectLogFetchParams.none()) + + /** @see fetch */ + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchProjectLogsEventsResponse = + fetch(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetch */ + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + ): FetchProjectLogsEventsResponse = fetch(projectId, params, RequestOptions.none()) + + /** @see fetch */ + fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchProjectLogsEventsResponse + + /** @see fetch */ + fun fetch(params: ProjectLogFetchParams): FetchProjectLogsEventsResponse = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + fun fetch(projectId: String, requestOptions: RequestOptions): FetchProjectLogsEventsResponse = + fetch(projectId, ProjectLogFetchParams.none(), requestOptions) + + /** + * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the + * parameters in the request body rather than in the URL query. For more complex queries, use + * the `POST /btql` endpoint. + */ + fun fetchPost(projectId: String): FetchProjectLogsEventsResponse = + fetchPost(projectId, ProjectLogFetchPostParams.none()) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchProjectLogsEventsResponse = + fetchPost(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + ): FetchProjectLogsEventsResponse = fetchPost(projectId, params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): FetchProjectLogsEventsResponse + + /** @see fetchPost */ + fun fetchPost(params: ProjectLogFetchPostParams): FetchProjectLogsEventsResponse = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + fun fetchPost( + projectId: String, + requestOptions: RequestOptions, + ): FetchProjectLogsEventsResponse = + fetchPost(projectId, ProjectLogFetchPostParams.none(), requestOptions) + + /** Insert a set of events into the project logs */ + fun insert(projectId: String, params: ProjectLogInsertParams): InsertEventsResponse = + insert(projectId, params, RequestOptions.none()) + + /** @see insert */ + fun insert( + projectId: String, + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): InsertEventsResponse = + insert(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see insert */ + fun insert(params: ProjectLogInsertParams): InsertEventsResponse = + insert(params, RequestOptions.none()) + + /** @see insert */ + fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): InsertEventsResponse + + /** A view of [LogService] that provides access to raw HTTP responses for each method. */ + interface WithRawResponse { + + /** + * Returns a view of this service with the given option modifications applied. + * + * The original service is not modified. + */ + fun withOptions(modifier: Consumer): LogService.WithRawResponse + + /** + * Returns a raw HTTP response for `post /v1/project_logs/{project_id}/feedback`, but is + * otherwise the same as [LogService.feedback]. + */ + @MustBeClosed + fun feedback( + projectId: String, + params: ProjectLogFeedbackParams, + ): HttpResponseFor = + feedback(projectId, params, RequestOptions.none()) + + /** @see feedback */ + @MustBeClosed + fun feedback( + projectId: String, + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + feedback(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see feedback */ + @MustBeClosed + fun feedback(params: ProjectLogFeedbackParams): HttpResponseFor = + feedback(params, RequestOptions.none()) + + /** @see feedback */ + @MustBeClosed + fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** + * Returns a raw HTTP response for `get /v1/project_logs/{project_id}/fetch`, but is + * otherwise the same as [LogService.fetch]. + */ + @MustBeClosed + fun fetch(projectId: String): HttpResponseFor = + fetch(projectId, ProjectLogFetchParams.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + fetch(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetch */ + @MustBeClosed + fun fetch( + projectId: String, + params: ProjectLogFetchParams = ProjectLogFetchParams.none(), + ): HttpResponseFor = + fetch(projectId, params, RequestOptions.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see fetch */ + @MustBeClosed + fun fetch(params: ProjectLogFetchParams): HttpResponseFor = + fetch(params, RequestOptions.none()) + + /** @see fetch */ + @MustBeClosed + fun fetch( + projectId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + fetch(projectId, ProjectLogFetchParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/project_logs/{project_id}/fetch`, but is + * otherwise the same as [LogService.fetchPost]. + */ + @MustBeClosed + fun fetchPost(projectId: String): HttpResponseFor = + fetchPost(projectId, ProjectLogFetchPostParams.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + fetchPost(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + projectId: String, + params: ProjectLogFetchPostParams = ProjectLogFetchPostParams.none(), + ): HttpResponseFor = + fetchPost(projectId, params, RequestOptions.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + params: ProjectLogFetchPostParams + ): HttpResponseFor = + fetchPost(params, RequestOptions.none()) + + /** @see fetchPost */ + @MustBeClosed + fun fetchPost( + projectId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + fetchPost(projectId, ProjectLogFetchPostParams.none(), requestOptions) + + /** + * Returns a raw HTTP response for `post /v1/project_logs/{project_id}/insert`, but is + * otherwise the same as [LogService.insert]. + */ + @MustBeClosed + fun insert( + projectId: String, + params: ProjectLogInsertParams, + ): HttpResponseFor = insert(projectId, params, RequestOptions.none()) + + /** @see insert */ + @MustBeClosed + fun insert( + projectId: String, + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + insert(params.toBuilder().projectId(projectId).build(), requestOptions) + + /** @see insert */ + @MustBeClosed + fun insert(params: ProjectLogInsertParams): HttpResponseFor = + insert(params, RequestOptions.none()) + + /** @see insert */ + @MustBeClosed + fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + } +} 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 new file mode 100644 index 00000000..b2f5c6aa --- /dev/null +++ b/braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceImpl.kt @@ -0,0 +1,204 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking.projects + +import com.braintrustdata.api.core.ClientOptions +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.checkRequired +import com.braintrustdata.api.core.handlers.errorBodyHandler +import com.braintrustdata.api.core.handlers.errorHandler +import com.braintrustdata.api.core.handlers.jsonHandler +import com.braintrustdata.api.core.http.HttpMethod +import com.braintrustdata.api.core.http.HttpRequest +import com.braintrustdata.api.core.http.HttpResponse +import com.braintrustdata.api.core.http.HttpResponse.Handler +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.models.FeedbackResponseSchema +import com.braintrustdata.api.models.FetchProjectLogsEventsResponse +import com.braintrustdata.api.models.InsertEventsResponse +import com.braintrustdata.api.models.ProjectLogFeedbackParams +import com.braintrustdata.api.models.ProjectLogFetchParams +import com.braintrustdata.api.models.ProjectLogFetchPostParams +import com.braintrustdata.api.models.ProjectLogInsertParams +import java.util.function.Consumer +import kotlin.jvm.optionals.getOrNull + +class LogServiceImpl internal constructor(private val clientOptions: ClientOptions) : LogService { + + private val withRawResponse: LogService.WithRawResponse by lazy { + WithRawResponseImpl(clientOptions) + } + + override fun withRawResponse(): LogService.WithRawResponse = withRawResponse + + override fun withOptions(modifier: Consumer): LogService = + LogServiceImpl(clientOptions.toBuilder().apply(modifier::accept).build()) + + override fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions, + ): FeedbackResponseSchema = + // post /v1/project_logs/{project_id}/feedback + withRawResponse().feedback(params, requestOptions).parse() + + override fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions, + ): FetchProjectLogsEventsResponse = + // get /v1/project_logs/{project_id}/fetch + withRawResponse().fetch(params, requestOptions).parse() + + override fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions, + ): FetchProjectLogsEventsResponse = + // post /v1/project_logs/{project_id}/fetch + withRawResponse().fetchPost(params, requestOptions).parse() + + override fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions, + ): InsertEventsResponse = + // post /v1/project_logs/{project_id}/insert + withRawResponse().insert(params, requestOptions).parse() + + class WithRawResponseImpl internal constructor(private val clientOptions: ClientOptions) : + LogService.WithRawResponse { + + private val errorHandler: Handler = + errorHandler(errorBodyHandler(clientOptions.jsonMapper)) + + override fun withOptions( + modifier: Consumer + ): LogService.WithRawResponse = + LogServiceImpl.WithRawResponseImpl( + clientOptions.toBuilder().apply(modifier::accept).build() + ) + + private val feedbackHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun feedback( + params: ProjectLogFeedbackParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "feedback") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { feedbackHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val fetchHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun fetch( + params: ProjectLogFetchParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { fetchHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val fetchPostHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun fetchPost( + params: ProjectLogFetchPostParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "fetch") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { fetchPostHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + + private val insertHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun insert( + params: ProjectLogInsertParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("projectId", params.projectId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("v1", "project_logs", params._pathParam(0), "insert") + .body(json(clientOptions.jsonMapper, params._body())) + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { insertHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + } + } + } +} diff --git a/braintrust-java-core/src/main/resources/META-INF/proguard/braintrust-java-core.pro b/braintrust-java-core/src/main/resources/META-INF/proguard/braintrust-java-core.pro new file mode 100644 index 00000000..02cd18c2 --- /dev/null +++ b/braintrust-java-core/src/main/resources/META-INF/proguard/braintrust-java-core.pro @@ -0,0 +1,32 @@ +# Jackson uses reflection and depends heavily on runtime attributes. +-keepattributes Exceptions,InnerClasses,Signature,Deprecated,*Annotation* + +# Jackson uses Kotlin reflection utilities, which themselves use reflection to access things. +-keep class kotlin.reflect.** { *; } +-keep class kotlin.Metadata { *; } + +# Jackson uses reflection to access enum members (e.g. via `java.lang.Class.getEnumConstants()`). +-keepclassmembers class com.fasterxml.jackson.** extends java.lang.Enum { + ; + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +# Jackson uses reflection to access annotation members. +-keepclassmembers @interface com.fasterxml.jackson.annotation.** { + *; +} + +# Jackson uses reified type information to serialize and deserialize our classes (via `TypeReference`). +-keep class com.fasterxml.jackson.core.type.TypeReference { *; } +-keep class * extends com.fasterxml.jackson.core.type.TypeReference { *; } + +# Jackson uses reflection to access our class serializers and deserializers. +-keep @com.fasterxml.jackson.databind.annotation.JsonSerialize class com.braintrustdata.api.** { *; } +-keep @com.fasterxml.jackson.databind.annotation.JsonDeserialize class com.braintrustdata.api.** { *; } + +# Jackson uses reflection to serialize and deserialize our classes based on their constructors and annotated members. +-keepclassmembers class com.braintrustdata.api.** { + (...); + @com.fasterxml.jackson.annotation.* *; +} \ No newline at end of file diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/TestServerExtension.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/TestServerExtension.kt old mode 100644 new mode 100755 index d79a0c57..1d2dd2d0 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/TestServerExtension.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/TestServerExtension.kt @@ -36,7 +36,7 @@ class TestServerExtension : BeforeAllCallback, ExecutionCondition { $ prism mock path/to/your.openapi.yml """ .trimIndent(), - e + e, ) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/client/BraintrustClientTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/client/BraintrustClientTest.kt deleted file mode 100644 index 68d59a3f..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/client/BraintrustClientTest.kt +++ /dev/null @@ -1,5 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.client - -class BraintrustClientTest diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/AutoPagerAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/AutoPagerAsyncTest.kt new file mode 100644 index 00000000..df8e2d08 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/AutoPagerAsyncTest.kt @@ -0,0 +1,182 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +import com.braintrustdata.api.core.http.AsyncStreamResponse +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +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.extension.ExtendWith +import org.mockito.junit.jupiter.MockitoExtension +import org.mockito.kotlin.any +import org.mockito.kotlin.clearInvocations +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.spy +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@ExtendWith(MockitoExtension::class) +internal class AutoPagerAsyncTest { + + companion object { + + private val ERROR = RuntimeException("ERROR!") + } + + private class PageAsyncImpl( + private val items: List, + private val hasNext: Boolean = true, + ) : PageAsync { + + val nextPageFuture: CompletableFuture> = CompletableFuture() + + override fun hasNextPage(): Boolean = hasNext + + override fun nextPage(): CompletableFuture> = nextPageFuture + + override fun items(): List = items + } + + private val executor = + spy { + doAnswer { invocation -> invocation.getArgument(0).run() } + .whenever(it) + .execute(any()) + } + private val handler = mock>() + + @Test + fun subscribe_whenAlreadySubscribed_throws() { + val autoPagerAsync = AutoPagerAsync.from(PageAsyncImpl(emptyList()), executor) + autoPagerAsync.subscribe {} + clearInvocations(executor) + + val throwable = catchThrowable { autoPagerAsync.subscribe {} } + + assertThat(throwable).isInstanceOf(IllegalStateException::class.java) + assertThat(throwable).hasMessage("Cannot subscribe more than once") + verify(executor, never()).execute(any()) + } + + @Test + fun subscribe_whenClosed_throws() { + val autoPagerAsync = AutoPagerAsync.from(PageAsyncImpl(emptyList()), executor) + autoPagerAsync.close() + + val throwable = catchThrowable { autoPagerAsync.subscribe {} } + + assertThat(throwable).isInstanceOf(IllegalStateException::class.java) + assertThat(throwable).hasMessage("Cannot subscribe after the response is closed") + verify(executor, never()).execute(any()) + } + + @Test + fun subscribe_whenFirstPageNonEmpty_runsHandler() { + val page = PageAsyncImpl(listOf("item1", "item2", "item3"), hasNext = false) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + + autoPagerAsync.subscribe(handler) + + inOrder(executor, handler) { + verify(executor, times(1)).execute(any()) + verify(handler, times(1)).onNext("item1") + verify(handler, times(1)).onNext("item2") + verify(handler, times(1)).onNext("item3") + verify(handler, times(1)).onComplete(Optional.empty()) + } + } + + @Test + fun subscribe_whenFutureCompletesAfterClose_doesNothing() { + val page = PageAsyncImpl(listOf("page1")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe(handler) + autoPagerAsync.close() + + page.nextPageFuture.complete(PageAsyncImpl(listOf("page2"))) + + verify(handler, times(1)).onNext("page1") + verify(handler, never()).onNext("page2") + verify(handler, times(1)).onComplete(Optional.empty()) + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenFutureErrors_callsOnComplete() { + val page = PageAsyncImpl(emptyList()) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe(handler) + + page.nextPageFuture.completeExceptionally(ERROR) + + verify(executor, times(1)).execute(any()) + verify(handler, never()).onNext(any()) + verify(handler, times(1)).onComplete(Optional.of(ERROR)) + } + + @Test + fun subscribe_whenFutureCompletes_runsHandler() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + + autoPagerAsync.subscribe(handler) + + verify(handler, never()).onComplete(any()) + inOrder(executor, handler) { + verify(executor, times(1)).execute(any()) + verify(handler, times(1)).onNext("chunk1") + verify(handler, times(1)).onNext("chunk2") + } + clearInvocations(executor, handler) + + page.nextPageFuture.complete(PageAsyncImpl(listOf("chunk3", "chunk4"), hasNext = false)) + + verify(executor, never()).execute(any()) + inOrder(handler) { + verify(handler, times(1)).onNext("chunk3") + verify(handler, times(1)).onNext("chunk4") + verify(handler, times(1)).onComplete(Optional.empty()) + } + } + + @Test + fun onCompleteFuture_whenNextPageFutureNotCompleted_onCompleteFutureNotCompleted() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe {} + + val onCompletableFuture = autoPagerAsync.onCompleteFuture() + + assertThat(onCompletableFuture).isNotCompleted + } + + @Test + fun onCompleteFuture_whenNextPageFutureErrors_onCompleteFutureCompletedExceptionally() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2")) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe {} + page.nextPageFuture.completeExceptionally(ERROR) + + val onCompletableFuture = autoPagerAsync.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenNoNextPage_onCompleteFutureCompleted() { + val page = PageAsyncImpl(listOf("chunk1", "chunk2"), hasNext = false) + val autoPagerAsync = AutoPagerAsync.from(page, executor) + autoPagerAsync.subscribe {} + + val onCompletableFuture = autoPagerAsync.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/AutoPagerTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/AutoPagerTest.kt new file mode 100644 index 00000000..d456fd7b --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/AutoPagerTest.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AutoPagerTest { + + private class PageImpl( + private val items: List, + private val nextPage: Page? = null, + ) : Page { + + override fun hasNextPage(): Boolean = nextPage != null + + override fun nextPage(): Page = nextPage!! + + override fun items(): List = items + } + + @Test + fun iterator() { + val firstPage = + PageImpl(listOf("chunk1", "chunk2"), nextPage = PageImpl(listOf("chunk3", "chunk4"))) + + val autoPager = AutoPager.from(firstPage) + + assertThat(autoPager).containsExactly("chunk1", "chunk2", "chunk3", "chunk4") + } + + @Test + fun stream() { + val firstPage = + PageImpl(listOf("chunk1", "chunk2"), nextPage = PageImpl(listOf("chunk3", "chunk4"))) + + val autoPager = AutoPager.from(firstPage) + + assertThat(autoPager.stream()).containsExactly("chunk1", "chunk2", "chunk3", "chunk4") + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ClientOptionsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ClientOptionsTest.kt new file mode 100644 index 00000000..9e5eb475 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ClientOptionsTest.kt @@ -0,0 +1,34 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.core + +import com.braintrustdata.api.core.http.HttpClient +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.mockito.junit.jupiter.MockitoExtension +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify + +@ExtendWith(MockitoExtension::class) +internal class ClientOptionsTest { + + private val httpClient = mock() + + @Test + fun toBuilder_whenOriginalClientOptionsGarbageCollected_doesNotCloseOriginalClient() { + var clientOptions = + ClientOptions.builder().httpClient(httpClient).apiKey("My API Key").build() + verify(httpClient, never()).close() + + // Overwrite the `clientOptions` variable so that the original `ClientOptions` is GC'd. + clientOptions = clientOptions.toBuilder().build() + System.gc() + Thread.sleep(100) + + verify(httpClient, never()).close() + // This exists so that `clientOptions` is still reachable. + assertThat(clientOptions).isEqualTo(clientOptions) + } +} 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 new file mode 100644 index 00000000..787e3b1f --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/PhantomReachableTest.kt @@ -0,0 +1,27 @@ +package com.braintrustdata.api.core + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PhantomReachableTest { + + @Test + fun closeWhenPhantomReachable_whenObservedIsGarbageCollected_closesCloseable() { + var closed = false + val closeable = AutoCloseable { closed = true } + + closeWhenPhantomReachable( + // Pass an inline object for the object to observe so that it becomes immediately + // unreachable. + Any(), + closeable, + ) + + assertThat(closed).isFalse() + + System.gc() + Thread.sleep(100) + + assertThat(closed).isTrue() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/UtilsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/UtilsTest.kt new file mode 100644 index 00000000..43a97498 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/UtilsTest.kt @@ -0,0 +1,33 @@ +package com.braintrustdata.api.core + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UtilsTest { + @Test + fun contentDeepEquals() { + assertThat(42 contentEquals 42).isTrue() + assertThat(42 contentEquals "Hello World!").isFalse() + assertThat(byteArrayOf(1, 2, 3) contentEquals byteArrayOf(1, 2, 3)).isTrue() + assertThat(byteArrayOf(1, 2, 3) contentEquals byteArrayOf(1, 2, 4)).isFalse() + assertThat( + arrayOf(byteArrayOf(1, 2), byteArrayOf(3)) contentEquals + arrayOf(byteArrayOf(1, 2), byteArrayOf(3)) + ) + .isTrue() + assertThat( + arrayOf(byteArrayOf(1, 2), byteArrayOf(3)) contentEquals + arrayOf(byteArrayOf(1), byteArrayOf(2, 3)) + ) + .isFalse() + } + + @Test + fun contentToString() { + assertThat((42).contentToString()).isEqualTo("42") + assertThat("Hello World!".contentToString()).isEqualTo("Hello World!") + assertThat(byteArrayOf(1, 2, 3).contentToString()).isEqualTo("[1, 2, 3]") + assertThat(arrayOf(byteArrayOf(1, 2), byteArrayOf(3)).contentToString()) + .isEqualTo("[[1, 2], [3]]") + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ValuesTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ValuesTest.kt new file mode 100644 index 00000000..fcdb9f5c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/ValuesTest.kt @@ -0,0 +1,144 @@ +package com.braintrustdata.api.core + +import java.util.Optional +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class ValuesTest { + companion object { + private val NON_JSON = Any() + } + + enum class TestCase( + val value: JsonField<*>, + val expectedIsMissing: Boolean = false, + val expectedIsNull: Boolean = false, + val expectedAsKnown: Optional<*> = Optional.empty(), + val expectedAsBoolean: Optional = Optional.empty(), + val expectedAsNumber: Optional = Optional.empty(), + val expectedAsString: Optional = Optional.empty(), + val expectedAsArray: Optional> = Optional.empty(), + val expectedAsObject: Optional> = Optional.empty(), + ) { + MISSING(JsonMissing.of(), expectedIsMissing = true), + NULL(JsonNull.of(), expectedIsNull = true), + KNOWN(KnownValue.of(NON_JSON), expectedAsKnown = Optional.of(NON_JSON)), + KNOWN_BOOLEAN( + KnownValue.of(true), + expectedAsKnown = Optional.of(true), + expectedAsBoolean = Optional.of(true), + ), + BOOLEAN(JsonBoolean.of(true), expectedAsBoolean = Optional.of(true)), + KNOWN_NUMBER( + KnownValue.of(42), + expectedAsKnown = Optional.of(42), + expectedAsNumber = Optional.of(42), + ), + NUMBER(JsonNumber.of(42), expectedAsNumber = Optional.of(42)), + KNOWN_STRING( + KnownValue.of("hello"), + expectedAsKnown = Optional.of("hello"), + expectedAsString = Optional.of("hello"), + ), + STRING(JsonString.of("hello"), expectedAsString = Optional.of("hello")), + KNOWN_ARRAY_NOT_ALL_JSON( + KnownValue.of(listOf("a", "b", NON_JSON)), + expectedAsKnown = Optional.of(listOf("a", "b", NON_JSON)), + ), + KNOWN_ARRAY( + KnownValue.of(listOf("a", "b", "c")), + expectedAsKnown = Optional.of(listOf("a", "b", "c")), + expectedAsArray = + Optional.of(listOf(JsonString.of("a"), JsonString.of("b"), JsonString.of("c"))), + ), + ARRAY( + JsonArray.of(listOf(JsonString.of("a"), JsonString.of("b"), JsonString.of("c"))), + expectedAsArray = + Optional.of(listOf(JsonString.of("a"), JsonString.of("b"), JsonString.of("c"))), + ), + KNOWN_OBJECT_NOT_ALL_STRING_KEYS( + KnownValue.of(mapOf("a" to "b", 42 to "c")), + expectedAsKnown = Optional.of(mapOf("a" to "b", 42 to "c")), + ), + KNOWN_OBJECT_NOT_ALL_JSON( + KnownValue.of(mapOf("a" to "b", "b" to NON_JSON)), + expectedAsKnown = Optional.of(mapOf("a" to "b", "b" to NON_JSON)), + ), + KNOWN_OBJECT( + KnownValue.of(mapOf("a" to "b", "b" to "c")), + expectedAsKnown = Optional.of(mapOf("a" to "b", "b" to "c")), + expectedAsObject = + Optional.of(mapOf("a" to JsonString.of("b"), "b" to JsonString.of("c"))), + ), + OBJECT( + JsonObject.of(mapOf("a" to JsonString.of("b"), "b" to JsonString.of("c"))), + expectedAsObject = + Optional.of(mapOf("a" to JsonString.of("b"), "b" to JsonString.of("c"))), + ), + } + + @ParameterizedTest + @EnumSource + fun isMissing(testCase: TestCase) { + val isMissing = testCase.value.isMissing() + + assertThat(isMissing).isEqualTo(testCase.expectedIsMissing) + } + + @ParameterizedTest + @EnumSource + fun isNull(testCase: TestCase) { + val isNull = testCase.value.isNull() + + assertThat(isNull).isEqualTo(testCase.expectedIsNull) + } + + @ParameterizedTest + @EnumSource + fun asKnown(testCase: TestCase) { + val known = testCase.value.asKnown() + + assertThat(known).isEqualTo(testCase.expectedAsKnown) + } + + @ParameterizedTest + @EnumSource + fun asBoolean(testCase: TestCase) { + val boolean = testCase.value.asBoolean() + + assertThat(boolean).isEqualTo(testCase.expectedAsBoolean) + } + + @ParameterizedTest + @EnumSource + fun asNumber(testCase: TestCase) { + val number = testCase.value.asNumber() + + assertThat(number).isEqualTo(testCase.expectedAsNumber) + } + + @ParameterizedTest + @EnumSource + fun asString(testCase: TestCase) { + val string = testCase.value.asString() + + assertThat(string).isEqualTo(testCase.expectedAsString) + } + + @ParameterizedTest + @EnumSource + fun asArray(testCase: TestCase) { + val array = testCase.value.asArray() + + assertThat(array).isEqualTo(testCase.expectedAsArray) + } + + @ParameterizedTest + @EnumSource + fun asObject(testCase: TestCase) { + val obj = testCase.value.asObject() + + assertThat(obj).isEqualTo(testCase.expectedAsObject) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/AsyncStreamResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/AsyncStreamResponseTest.kt new file mode 100644 index 00000000..a622292c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/AsyncStreamResponseTest.kt @@ -0,0 +1,268 @@ +package com.braintrustdata.api.core.http + +import java.util.* +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.stream.Stream +import kotlin.streams.asStream +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.api.extension.ExtendWith +import org.mockito.junit.jupiter.MockitoExtension +import org.mockito.kotlin.* + +@ExtendWith(MockitoExtension::class) +internal class AsyncStreamResponseTest { + + companion object { + private val ERROR = RuntimeException("ERROR!") + } + + private val streamResponse = + spy> { + doReturn(Stream.of("chunk1", "chunk2", "chunk3")).whenever(it).stream() + } + private val erroringStreamResponse = + spy> { + doReturn( + sequence { + yield("chunk1") + yield("chunk2") + throw ERROR + } + .asStream() + ) + .whenever(it) + .stream() + } + private val executor = + spy { + doAnswer { invocation -> invocation.getArgument(0).run() } + .whenever(it) + .execute(any()) + } + private val handler = mock>() + + @Test + fun subscribe_whenAlreadySubscribed_throws() { + val asyncStreamResponse = CompletableFuture>().toAsync(executor) + asyncStreamResponse.subscribe {} + + val throwable = catchThrowable { asyncStreamResponse.subscribe {} } + + assertThat(throwable).isInstanceOf(IllegalStateException::class.java) + assertThat(throwable).hasMessage("Cannot subscribe more than once") + verify(executor, never()).execute(any()) + } + + @Test + fun subscribe_whenClosed_throws() { + val asyncStreamResponse = CompletableFuture>().toAsync(executor) + asyncStreamResponse.close() + + val throwable = catchThrowable { asyncStreamResponse.subscribe {} } + + assertThat(throwable).isInstanceOf(IllegalStateException::class.java) + assertThat(throwable).hasMessage("Cannot subscribe after the response is closed") + verify(executor, never()).execute(any()) + } + + @Test + fun subscribe_whenFutureCompletesAfterClose_doesNothing() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + asyncStreamResponse.close() + + future.complete(streamResponse) + + verify(handler, never()).onNext(any()) + verify(handler, never()).onComplete(any()) + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenFutureErrors_callsOnComplete() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + + future.completeExceptionally(ERROR) + + verify(handler, never()).onNext(any()) + verify(handler, times(1)).onComplete(Optional.of(ERROR)) + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenFutureCompletes_runsHandler() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + + future.complete(streamResponse) + + inOrder(handler, streamResponse) { + verify(handler, times(1)).onNext("chunk1") + verify(handler, times(1)).onNext("chunk2") + verify(handler, times(1)).onNext("chunk3") + verify(handler, times(1)).onComplete(Optional.empty()) + verify(streamResponse, times(1)).close() + } + verify(executor, times(1)).execute(any()) + } + + @Test + fun subscribe_whenStreamErrors_callsOnCompleteEarly() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + + future.complete(erroringStreamResponse) + + inOrder(handler, erroringStreamResponse) { + verify(handler, times(1)).onNext("chunk1") + verify(handler, times(1)).onNext("chunk2") + verify(handler, times(1)).onComplete(Optional.of(ERROR)) + verify(erroringStreamResponse, times(1)).close() + } + verify(executor, times(1)).execute(any()) + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureNotCompleted_onCompleteFutureNotCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isNotCompleted + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureErrors_onCompleteFutureCompletedExceptionally() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + future.completeExceptionally(ERROR) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureCompletedButStillStreaming_onCompleteFutureNotCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + future.complete(streamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isNotCompleted + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureCompletedAndStreamErrors_onCompleteFutureCompletedExceptionally() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + future.complete(erroringStreamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenStreamResponseFutureCompletedAndStreamCompleted_onCompleteFutureCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe(handler) + future.complete(streamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } + + @Test + fun onCompleteFuture_whenHandlerOnCompleteWithoutThrowableThrows_onCompleteFutureCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe( + object : AsyncStreamResponse.Handler { + override fun onNext(value: String) {} + + override fun onComplete(error: Optional) = throw ERROR + } + ) + future.complete(streamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } + + @Test + fun onCompleteFuture_whenHandlerOnCompleteWithThrowableThrows_onCompleteFutureCompletedExceptionally() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.subscribe( + object : AsyncStreamResponse.Handler { + override fun onNext(value: String) {} + + override fun onComplete(error: Optional) = throw ERROR + } + ) + future.complete(erroringStreamResponse) + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompletedExceptionally + } + + @Test + fun onCompleteFuture_whenClosed_onCompleteFutureCompleted() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.close() + + val onCompletableFuture = asyncStreamResponse.onCompleteFuture() + + assertThat(onCompletableFuture).isCompleted + } + + @Test + fun close_whenNotClosed_closesStreamResponse() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + + asyncStreamResponse.close() + future.complete(streamResponse) + + verify(streamResponse, times(1)).close() + } + + @Test + fun close_whenAlreadyClosed_doesNothing() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.close() + future.complete(streamResponse) + + asyncStreamResponse.close() + + verify(streamResponse, times(1)).close() + } + + @Test + fun close_whenFutureErrors_doesNothing() { + val future = CompletableFuture>() + val asyncStreamResponse = future.toAsync(executor) + asyncStreamResponse.close() + + assertDoesNotThrow { future.completeExceptionally(ERROR) } + } +} 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 new file mode 100644 index 00000000..a4e77e29 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HeadersTest.kt @@ -0,0 +1,242 @@ +package com.braintrustdata.api.core.http + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class HeadersTest { + + enum class TestCase( + val headers: Headers, + val expectedMap: Map>, + val expectedSize: Int, + ) { + EMPTY(Headers.builder().build(), expectedMap = mapOf(), expectedSize = 0), + PUT_ONE( + Headers.builder().put("name", "value").build(), + expectedMap = mapOf("name" to listOf("value")), + expectedSize = 1, + ), + PUT_MULTIPLE( + Headers.builder().put("name", listOf("value1", "value2")).build(), + expectedMap = mapOf("name" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT( + Headers.builder().put("name1", "value").put("name2", "value").build(), + expectedMap = mapOf("name1" to listOf("value"), "name2" to listOf("value")), + expectedSize = 2, + ), + MULTIPLE_PUT_SAME_NAME( + Headers.builder().put("name", "value1").put("name", "value2").build(), + expectedMap = mapOf("name" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT_MULTIPLE( + Headers.builder() + .put("name", listOf("value1", "value2")) + .put("name", listOf("value1", "value2")) + .build(), + expectedMap = mapOf("name" to listOf("value1", "value2", "value1", "value2")), + expectedSize = 4, + ), + PUT_CASE_INSENSITIVE( + Headers.builder() + .put("name", "value1") + .put("NAME", "value2") + .put("nAmE", "value3") + .build(), + expectedMap = mapOf("name" to listOf("value1", "value2", "value3")), + expectedSize = 3, + ), + PUT_ALL_MAP( + Headers.builder() + .putAll( + mapOf( + "name1" to listOf("value1", "value2"), + "name2" to listOf("value1", "value2"), + ) + ) + .build(), + expectedMap = + mapOf("name1" to listOf("value1", "value2"), "name2" to listOf("value1", "value2")), + expectedSize = 4, + ), + PUT_ALL_HEADERS( + Headers.builder().putAll(Headers.builder().put("name", "value").build()).build(), + expectedMap = mapOf("name" to listOf("value")), + expectedSize = 1, + ), + PUT_ALL_CASE_INSENSITIVE( + Headers.builder() + .putAll( + mapOf( + "name" to listOf("value1"), + "NAME" to listOf("value2"), + "nAmE" to listOf("value3"), + ) + ) + .build(), + expectedMap = mapOf("name" to listOf("value1", "value2", "value3")), + expectedSize = 3, + ), + REMOVE_ABSENT( + Headers.builder().remove("name").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_ONE( + Headers.builder().put("name", "value").remove("name").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_MULTIPLE( + Headers.builder().put("name", listOf("value1", "value2")).remove("name").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_CASE_INSENSITIVE( + Headers.builder().put("name", listOf("value1", "value2")).remove("NAME").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_ALL( + Headers.builder() + .put("name1", "value") + .put("name3", "value") + .removeAll(setOf("name1", "name2", "name3")) + .build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_ALL_CASE_INSENSITIVE( + Headers.builder() + .put("name1", "value") + .put("name3", "value") + .removeAll(setOf("NAME1", "nAmE3")) + .build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + CLEAR( + Headers.builder().put("name1", "value").put("name2", "value").clear().build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REPLACE_ONE_ABSENT( + Headers.builder().replace("name", "value").build(), + expectedMap = mapOf("name" to listOf("value")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_ONE( + Headers.builder().put("name", "value1").replace("name", "value2").build(), + expectedMap = mapOf("name" to listOf("value2")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_MULTIPLE( + Headers.builder() + .put("name", listOf("value1", "value2")) + .replace("name", "value3") + .build(), + expectedMap = mapOf("name" to listOf("value3")), + expectedSize = 1, + ), + REPLACE_MULTIPLE_ABSENT( + Headers.builder().replace("name", listOf("value1", "value2")).build(), + expectedMap = mapOf("name" to listOf("value1", "value2")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_ONE( + Headers.builder() + .put("name", "value1") + .replace("name", listOf("value2", "value3")) + .build(), + expectedMap = mapOf("name" to listOf("value2", "value3")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_MULTIPLE( + Headers.builder() + .put("name", listOf("value1", "value2")) + .replace("name", listOf("value3", "value4")) + .build(), + expectedMap = mapOf("name" to listOf("value3", "value4")), + expectedSize = 2, + ), + REPLACE_CASE_INSENSITIVE( + Headers.builder() + .put("name", "value1") + .replace("NAME", listOf("value2", "value3")) + .build(), + expectedMap = mapOf("NAME" to listOf("value2", "value3")), + expectedSize = 2, + ), + REPLACE_ALL_MAP( + Headers.builder() + .put("name1", "value1") + .put("name2", "value1") + .put("name3", "value1") + .replaceAll(mapOf("name1" to listOf("value2"), "name3" to listOf("value2"))) + .build(), + expectedMap = + mapOf( + "name1" to listOf("value2"), + "name2" to listOf("value1"), + "name3" to listOf("value2"), + ), + expectedSize = 3, + ), + REPLACE_ALL_HEADERS( + Headers.builder() + .put("name1", "value1") + .put("name2", "value1") + .put("name3", "value1") + .replaceAll(Headers.builder().put("name1", "value2").put("name3", "value2").build()) + .build(), + expectedMap = + mapOf( + "name1" to listOf("value2"), + "name2" to listOf("value1"), + "name3" to listOf("value2"), + ), + expectedSize = 3, + ), + REPLACE_ALL_CASE_INSENSITIVE( + Headers.builder() + .put("name1", "value1") + .put("name2", "value1") + .replaceAll(mapOf("NAME1" to listOf("value2"), "nAmE2" to listOf("value2"))) + .build(), + expectedMap = mapOf("NAME1" to listOf("value2"), "nAmE2" to listOf("value2")), + expectedSize = 2, + ), + } + + @ParameterizedTest + @EnumSource + fun namesAndValues(testCase: TestCase) { + val map = mutableMapOf>() + val headers = testCase.headers + headers.names().forEach { name -> map[name] = headers.values(name) } + + assertThat(map).isEqualTo(testCase.expectedMap) + } + + @ParameterizedTest + @EnumSource + fun caseInsensitiveNames(testCase: TestCase) { + val headers = testCase.headers + + for (name in headers.names()) { + assertThat(headers.values(name)).isEqualTo(headers.values(name.lowercase())) + assertThat(headers.values(name)).isEqualTo(headers.values(name.uppercase())) + } + } + + @ParameterizedTest + @EnumSource + fun size(testCase: TestCase) { + val size = testCase.headers.size + + assertThat(size).isEqualTo(testCase.expectedSize) + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HttpRequestTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HttpRequestTest.kt deleted file mode 100644 index 8c937928..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/HttpRequestTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.braintrustdata.api.core.http - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -internal class HttpRequestTest { - - @Test - fun caseInsensitiveHeadersAccessors() { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .putHeader("something_lowercase", "lowercase") - .putHeader("Something_Capitalized", "Capitalized") - .putHeader("SOMETHING_UPPERCASE", "UPPERCASE") - .build() - assertThat(request.headers.get("SOMETHING_LOWERCASE").getOrNull(0)).isEqualTo("lowercase") - assertThat(request.headers.get("something_capitalized").getOrNull(0)) - .isEqualTo("Capitalized") - assertThat(request.headers.get("Something_Uppercase").getOrNull(0)).isEqualTo("UPPERCASE") - } -} 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 new file mode 100644 index 00000000..0fd285c1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/QueryParamsTest.kt @@ -0,0 +1,180 @@ +package com.braintrustdata.api.core.http + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource + +internal class QueryParamsTest { + + enum class TestCase( + val queryParams: QueryParams, + val expectedMap: Map>, + val expectedSize: Int, + ) { + EMPTY(QueryParams.builder().build(), expectedMap = mapOf(), expectedSize = 0), + PUT_ONE( + QueryParams.builder().put("key", "value").build(), + expectedMap = mapOf("key" to listOf("value")), + expectedSize = 1, + ), + PUT_MULTIPLE( + QueryParams.builder().put("key", listOf("value1", "value2")).build(), + expectedMap = mapOf("key" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT( + QueryParams.builder().put("key1", "value").put("key2", "value").build(), + expectedMap = mapOf("key1" to listOf("value"), "key2" to listOf("value")), + expectedSize = 2, + ), + MULTIPLE_PUT_SAME_NAME( + QueryParams.builder().put("key", "value1").put("key", "value2").build(), + expectedMap = mapOf("key" to listOf("value1", "value2")), + expectedSize = 2, + ), + MULTIPLE_PUT_MULTIPLE( + QueryParams.builder() + .put("key", listOf("value1", "value2")) + .put("key", listOf("value1", "value2")) + .build(), + expectedMap = mapOf("key" to listOf("value1", "value2", "value1", "value2")), + expectedSize = 4, + ), + PUT_ALL_MAP( + QueryParams.builder() + .putAll( + mapOf( + "key1" to listOf("value1", "value2"), + "key2" to listOf("value1", "value2"), + ) + ) + .build(), + expectedMap = + mapOf("key1" to listOf("value1", "value2"), "key2" to listOf("value1", "value2")), + expectedSize = 4, + ), + PUT_ALL_HEADERS( + QueryParams.builder().putAll(QueryParams.builder().put("key", "value").build()).build(), + expectedMap = mapOf("key" to listOf("value")), + expectedSize = 1, + ), + REMOVE_ABSENT( + QueryParams.builder().remove("key").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_ONE( + QueryParams.builder().put("key", "value").remove("key").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_PRESENT_MULTIPLE( + QueryParams.builder().put("key", listOf("value1", "value2")).remove("key").build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REMOVE_ALL( + QueryParams.builder() + .put("key1", "value") + .put("key3", "value") + .removeAll(setOf("key1", "key2", "key3")) + .build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + CLEAR( + QueryParams.builder().put("key1", "value").put("key2", "value").clear().build(), + expectedMap = mapOf(), + expectedSize = 0, + ), + REPLACE_ONE_ABSENT( + QueryParams.builder().replace("key", "value").build(), + expectedMap = mapOf("key" to listOf("value")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_ONE( + QueryParams.builder().put("key", "value1").replace("key", "value2").build(), + expectedMap = mapOf("key" to listOf("value2")), + expectedSize = 1, + ), + REPLACE_ONE_PRESENT_MULTIPLE( + QueryParams.builder() + .put("key", listOf("value1", "value2")) + .replace("key", "value3") + .build(), + expectedMap = mapOf("key" to listOf("value3")), + expectedSize = 1, + ), + REPLACE_MULTIPLE_ABSENT( + QueryParams.builder().replace("key", listOf("value1", "value2")).build(), + expectedMap = mapOf("key" to listOf("value1", "value2")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_ONE( + QueryParams.builder() + .put("key", "value1") + .replace("key", listOf("value2", "value3")) + .build(), + expectedMap = mapOf("key" to listOf("value2", "value3")), + expectedSize = 2, + ), + REPLACE_MULTIPLE_PRESENT_MULTIPLE( + QueryParams.builder() + .put("key", listOf("value1", "value2")) + .replace("key", listOf("value3", "value4")) + .build(), + expectedMap = mapOf("key" to listOf("value3", "value4")), + expectedSize = 2, + ), + REPLACE_ALL_MAP( + QueryParams.builder() + .put("key1", "value1") + .put("key2", "value1") + .put("key3", "value1") + .replaceAll(mapOf("key1" to listOf("value2"), "key3" to listOf("value2"))) + .build(), + expectedMap = + mapOf( + "key1" to listOf("value2"), + "key2" to listOf("value1"), + "key3" to listOf("value2"), + ), + expectedSize = 3, + ), + REPLACE_ALL_HEADERS( + QueryParams.builder() + .put("key1", "value1") + .put("key2", "value1") + .put("key3", "value1") + .replaceAll( + QueryParams.builder().put("key1", "value2").put("key3", "value2").build() + ) + .build(), + expectedMap = + mapOf( + "key1" to listOf("value2"), + "key2" to listOf("value1"), + "key3" to listOf("value2"), + ), + expectedSize = 3, + ), + } + + @ParameterizedTest + @EnumSource + fun keysAndValues(testCase: TestCase) { + val map = mutableMapOf>() + val queryParams = testCase.queryParams + queryParams.keys().forEach { key -> map[key] = queryParams.values(key) } + + assertThat(map).isEqualTo(testCase.expectedMap) + } + + @ParameterizedTest + @EnumSource + fun size(testCase: TestCase) { + val size = testCase.queryParams.size + + assertThat(size).isEqualTo(testCase.expectedSize) + } +} 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 old mode 100644 new mode 100755 index 16ddf16d..c34665e3 --- 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 @@ -1,62 +1,130 @@ package com.braintrustdata.api.core.http import com.braintrustdata.api.client.okhttp.OkHttpClient +import com.braintrustdata.api.core.RequestOptions +import com.braintrustdata.api.core.Sleeper +import com.braintrustdata.api.errors.BraintrustRetryableException import com.github.tomakehurst.wiremock.client.WireMock.* 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.Test +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 + private lateinit var baseUrl: String private lateinit var httpClient: HttpClient @BeforeEach fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { - httpClient = OkHttpClient.builder().baseUrl(wmRuntimeInfo.httpBaseUrl).build() + baseUrl = wmRuntimeInfo.httpBaseUrl + val okHttpClient = OkHttpClient.builder().build() + httpClient = + object : HttpClient { + + override fun execute( + request: HttpRequest, + requestOptions: RequestOptions, + ): HttpResponse = trackClose(okHttpClient.execute(request, requestOptions)) + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture = + okHttpClient.executeAsync(request, requestOptions).thenApply { trackClose(it) } + + override fun close() = okHttpClient.close() + + private fun trackClose(response: HttpResponse): HttpResponse { + openResponseCount++ + return object : HttpResponse { + + private var isClosed = false + + override fun statusCode(): Int = response.statusCode() + + override fun headers(): Headers = response.headers() + + override fun body(): InputStream = response.body() + + override fun close() { + response.close() + if (isClosed) { + return + } + openResponseCount-- + isClosed = true + } + } + } + } resetAllScenarios() } - @Test - fun byDefaultShouldNotAddIdempotencyHeaderToRequest() { - val request = - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build() + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute(async: Boolean) { stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) - val retryingClient = RetryingHttpClient.builder().httpClient(httpClient).build() - val response = retryingClient.execute(request) + val retryingClient = retryingHttpClientBuilder().build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + assertThat(response.statusCode()).isEqualTo(200) verify(1, postRequestedFor(urlPathEqualTo("/something"))) + assertNoResponseLeaks() } - @Test - fun whenProvidedShouldAddIdempotencyHeaderToRequest() { - val request = - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build() + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withIdempotencyHeader(async: Boolean) { stubFor( post(urlPathEqualTo("/something")) .withHeader("X-Some-Header", matching("stainless-java-retry-.+")) .willReturn(ok()) ) val retryingClient = - RetryingHttpClient.builder() - .httpClient(httpClient) - .idempotencyHeader("X-Some-Header") - .build() - val response = retryingClient.execute(request) + retryingHttpClientBuilder().maxRetries(2).idempotencyHeader("X-Some-Header").build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + assertThat(response.statusCode()).isEqualTo(200) verify(1, postRequestedFor(urlPathEqualTo("/something"))) + assertNoResponseLeaks() } - @Test - fun retryAfterHeader() { - val request = - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build() + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withRetryAfterHeader(async: Boolean) { stubFor( post(urlPathEqualTo("/something")) - .inScenario("foo") // first we fail with a retry after header given as a date + // First we fail with a retry after header given as a date + .inScenario("foo") .whenScenarioStateIs(Scenario.STARTED) .willReturn( serviceUnavailable().withHeader("Retry-After", "Wed, 21 Oct 2015 07:28:00 GMT") @@ -65,29 +133,95 @@ internal class RetryingHttpClientTest { ) stubFor( post(urlPathEqualTo("/something")) - .inScenario("foo") // then we fail with a retry after header given as a delay + // Then we fail with a retry after header given as a delay + .inScenario("foo") .whenScenarioStateIs("RETRY_AFTER_DATE") .willReturn(serviceUnavailable().withHeader("Retry-After", "1.234")) .willSetStateTo("RETRY_AFTER_DELAY") ) stubFor( post(urlPathEqualTo("/something")) - .inScenario("foo") // then we return a success + // Then we return a success + .inScenario("foo") .whenScenarioStateIs("RETRY_AFTER_DELAY") .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(2).build() - val response = retryingClient.execute(request) + val retryingClient = retryingHttpClientBuilder().maxRetries(2).build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("0")), + ) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("1")), + ) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("2")), + ) + assertNoResponseLeaks() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withOverwrittenRetryCountHeader(async: Boolean) { + stubFor( + post(urlPathEqualTo("/something")) + .inScenario("foo") // first we fail with a retry after header given as a date + .whenScenarioStateIs(Scenario.STARTED) + .willReturn( + serviceUnavailable().withHeader("Retry-After", "Wed, 21 Oct 2015 07:28:00 GMT") + ) + .willSetStateTo("RETRY_AFTER_DATE") + ) + stubFor( + post(urlPathEqualTo("/something")) + .inScenario("foo") // then we return a success + .whenScenarioStateIs("RETRY_AFTER_DATE") + .willReturn(ok()) + .willSetStateTo("COMPLETED") + ) + val retryingClient = retryingHttpClientBuilder().maxRetries(2).build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .putHeader("x-stainless-retry-count", "42") + .build(), + async, + ) + assertThat(response.statusCode()).isEqualTo(200) - verify(3, postRequestedFor(urlPathEqualTo("/something"))) + verify( + 2, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("42")), + ) + assertNoResponseLeaks() } - @Test - fun retryAfterMsHeader() { - val request = - HttpRequest.builder().method(HttpMethod.POST).addPathSegment("something").build() + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withRetryAfterMsHeader(async: Boolean) { stubFor( post(urlPathEqualTo("/something")) .inScenario("foo") @@ -102,10 +236,121 @@ internal class RetryingHttpClientTest { .willReturn(ok()) .willSetStateTo("COMPLETED") ) - val retryingClient = - RetryingHttpClient.builder().httpClient(httpClient).maxRetries(1).build() - val response = retryingClient.execute(request) + val retryingClient = retryingHttpClientBuilder().maxRetries(1).build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + assertThat(response.statusCode()).isEqualTo(200) verify(2, postRequestedFor(urlPathEqualTo("/something"))) + assertNoResponseLeaks() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun execute_withRetryableException(async: Boolean) { + stubFor(post(urlPathEqualTo("/something")).willReturn(ok())) + + var callCount = 0 + val failingHttpClient = + object : HttpClient { + override fun execute( + request: HttpRequest, + requestOptions: RequestOptions, + ): HttpResponse { + callCount++ + if (callCount == 1) { + throw BraintrustRetryableException("Simulated retryable failure") + } + return httpClient.execute(request, requestOptions) + } + + override fun executeAsync( + request: HttpRequest, + requestOptions: RequestOptions, + ): CompletableFuture { + callCount++ + if (callCount == 1) { + val future = CompletableFuture() + future.completeExceptionally( + BraintrustRetryableException("Simulated retryable failure") + ) + return future + } + return httpClient.executeAsync(request, requestOptions) + } + + override fun close() = httpClient.close() + } + + val retryingClient = + RetryingHttpClient.builder() + .httpClient(failingHttpClient) + .maxRetries(2) + .sleeper( + object : Sleeper { + + override fun sleep(duration: Duration) {} + + override fun sleepAsync(duration: Duration): CompletableFuture = + CompletableFuture.completedFuture(null) + + override fun close() {} + } + ) + .build() + + val response = + retryingClient.execute( + HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl(baseUrl) + .addPathSegment("something") + .build(), + async, + ) + + assertThat(response.statusCode()).isEqualTo(200) + verify( + 1, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("1")), + ) + verify( + 0, + postRequestedFor(urlPathEqualTo("/something")) + .withHeader("x-stainless-retry-count", equalTo("0")), + ) + assertNoResponseLeaks() } + + private fun retryingHttpClientBuilder() = + RetryingHttpClient.builder() + .httpClient(httpClient) + // Use a no-op `Sleeper` to make the test fast. + .sleeper( + object : Sleeper { + + override fun sleep(duration: Duration) {} + + override fun sleepAsync(duration: Duration): CompletableFuture = + CompletableFuture.completedFuture(null) + + override fun close() {} + } + ) + + private fun HttpClient.execute(request: HttpRequest, async: Boolean): HttpResponse = + if (async) executeAsync(request).get() else execute(request) + + // When retrying, all failed responses should be closed. Only the final returned response should + // be open. + private fun assertNoResponseLeaks() = assertThat(openResponseCount).isEqualTo(1) } 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 100644 index f1c1f965..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/core/http/SerializerTest.kt +++ /dev/null @@ -1,105 +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 { - 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.toUnmodifiable(), - ) - } - } - - @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 new file mode 100644 index 00000000..32bc9fc5 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AISecretTest.kt @@ -0,0 +1,74 @@ +// 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 AISecretTest { + + @Test + fun create() { + 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() + + assertThat(aiSecret.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(aiSecret.name()).isEqualTo("name") + assertThat(aiSecret.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(aiSecret.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(aiSecret.metadata()) + .contains( + AISecret.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(aiSecret.previewSecret()).contains("preview_secret") + 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 new file mode 100644 index 00000000..c59b1e7a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateParamsTest.kt @@ -0,0 +1,101 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AclBatchUpdateParamsTest { + + @Test + fun create() { + AclBatchUpdateParams.builder() + .addAddAcl( + 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() + ) + .addRemoveAcl( + 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() + ) + .build() + } + + @Test + fun body() { + val params = + AclBatchUpdateParams.builder() + .addAddAcl( + 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() + ) + .addRemoveAcl( + 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() + ) + .build() + + val body = params._body() + + 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().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() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = AclBatchUpdateParams.builder().build() + + val body = params._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 new file mode 100644 index 00000000..e414f12a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclBatchUpdateResponseTest.kt @@ -0,0 +1,122 @@ +// 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 AclBatchUpdateResponseTest { + + @Test + fun create() { + 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() + + assertThat(aclBatchUpdateResponse.addedAcls()) + .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() + ) + assertThat(aclBatchUpdateResponse.removedAcls()) + .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 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 new file mode 100755 index 00000000..8076e142 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclCreateParamsTest.kt @@ -0,0 +1,60 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AclCreateParamsTest { + + @Test + fun create() { + AclCreateParams.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() + } + + @Test + fun body() { + val params = + AclCreateParams.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() + + val body = params._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") + assertThat(body.permission()).contains(Permission.CREATE) + assertThat(body.restrictObjectType()).contains(AclObjectType.ORGANIZATION) + assertThat(body.roleId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + AclCreateParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + + val body = params._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 new file mode 100755 index 00000000..3f7c31e8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclDeleteParamsTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AclDeleteParamsTest { + + @Test + fun create() { + AclDeleteParams.builder().aclId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = AclDeleteParams.builder().aclId("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("") + } +} 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 new file mode 100644 index 00000000..3185f02a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclFindAndDeleteParamsTest.kt @@ -0,0 +1,60 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AclFindAndDeleteParamsTest { + + @Test + fun create() { + AclFindAndDeleteParams.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() + } + + @Test + fun body() { + val params = + AclFindAndDeleteParams.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() + + val body = params._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") + assertThat(body.permission()).contains(Permission.CREATE) + assertThat(body.restrictObjectType()).contains(AclObjectType.ORGANIZATION) + assertThat(body.roleId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + AclFindAndDeleteParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + + val body = params._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/AclListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclListParamsTest.kt new file mode 100755 index 00000000..e5288078 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclListParamsTest.kt @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AclListParamsTest { + + @Test + fun create() { + AclListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + AclListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("object_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("object_type", "organization") + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = + AclListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .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() + ) + } +} 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 new file mode 100755 index 00000000..0dc6c6be --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AclRetrieveParamsTest { + + @Test + fun create() { + AclRetrieveParams.builder().aclId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + AclRetrieveParams.builder().aclId("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("") + } +} 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 new file mode 100755 index 00000000..862ff24d --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AclTest.kt @@ -0,0 +1,63 @@ +// 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 AclTest { + + @Test + fun create() { + 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() + + 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") + assertThat(acl.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(acl.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(acl.groupId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(acl.permission()).contains(Permission.CREATE) + assertThat(acl.restrictObjectType()).contains(AclObjectType.ORGANIZATION) + 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 new file mode 100644 index 00000000..a3115935 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretCreateParamsTest.kt @@ -0,0 +1,63 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretCreateParamsTest { + + @Test + fun create() { + AiSecretCreateParams.builder() + .name("name") + .metadata( + AiSecretCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + } + + @Test + fun body() { + val params = + AiSecretCreateParams.builder() + .name("name") + .metadata( + AiSecretCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.metadata()) + .contains( + AiSecretCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.orgName()).contains("org_name") + assertThat(body.secret()).contains("secret") + assertThat(body.type()).contains("type") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = AiSecretCreateParams.builder().name("name").build() + + val body = params._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 new file mode 100644 index 00000000..0aecaacb --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretDeleteParamsTest.kt @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretDeleteParamsTest { + + @Test + fun create() { + AiSecretDeleteParams.builder().aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + AiSecretDeleteParams.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("") + } +} 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 new file mode 100644 index 00000000..7e72a927 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretFindAndDeleteParamsTest.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretFindAndDeleteParamsTest { + + @Test + fun create() { + AiSecretFindAndDeleteParams.builder().name("name").orgName("org_name").build() + } + + @Test + fun body() { + val params = AiSecretFindAndDeleteParams.builder().name("name").orgName("org_name").build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.orgName()).contains("org_name") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = AiSecretFindAndDeleteParams.builder().name("name").build() + + val body = params._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/AiSecretListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretListParamsTest.kt new file mode 100644 index 00000000..20af378c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretListParamsTest.kt @@ -0,0 +1,61 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretListParamsTest { + + @Test + fun create() { + AiSecretListParams.builder() + .aiSecretName("ai_secret_name") + .aiSecretType("string") + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + AiSecretListParams.builder() + .aiSecretName("ai_secret_name") + .aiSecretType("string") + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ai_secret_name", "ai_secret_name") + .put("ai_secret_type", "string") + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = AiSecretListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100644 index 00000000..4f3b98f1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretReplaceParamsTest.kt @@ -0,0 +1,63 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretReplaceParamsTest { + + @Test + fun create() { + AiSecretReplaceParams.builder() + .name("name") + .metadata( + AiSecretReplaceParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + } + + @Test + fun body() { + val params = + AiSecretReplaceParams.builder() + .name("name") + .metadata( + AiSecretReplaceParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.metadata()) + .contains( + AiSecretReplaceParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.orgName()).contains("org_name") + assertThat(body.secret()).contains("secret") + assertThat(body.type()).contains("type") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = AiSecretReplaceParams.builder().name("name").build() + + val body = params._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 new file mode 100644 index 00000000..6fa5c828 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretRetrieveParamsTest.kt @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretRetrieveParamsTest { + + @Test + fun create() { + AiSecretRetrieveParams.builder().aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + AiSecretRetrieveParams.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("") + } +} 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 new file mode 100644 index 00000000..27e6e879 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/AiSecretUpdateParamsTest.kt @@ -0,0 +1,75 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class AiSecretUpdateParamsTest { + + @Test + fun create() { + AiSecretUpdateParams.builder() + .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .metadata( + AiSecretUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") + .secret("secret") + .type("type") + .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 = + AiSecretUpdateParams.builder() + .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .metadata( + AiSecretUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") + .secret("secret") + .type("type") + .build() + + val body = params._body() + + assertThat(body.metadata()) + .contains( + AiSecretUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.name()).contains("name") + assertThat(body.secret()).contains("secret") + assertThat(body.type()).contains("type") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + AiSecretUpdateParams.builder() + .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + } +} 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 new file mode 100644 index 00000000..ef31b0d6 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyCreateParamsTest.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ApiKeyCreateParamsTest { + + @Test + fun create() { + ApiKeyCreateParams.builder().name("name").orgName("org_name").build() + } + + @Test + fun body() { + val params = ApiKeyCreateParams.builder().name("name").orgName("org_name").build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.orgName()).contains("org_name") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = ApiKeyCreateParams.builder().name("name").build() + + val body = params._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 new file mode 100644 index 00000000..4172b7c4 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyDeleteParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ApiKeyDeleteParamsTest { + + @Test + fun create() { + ApiKeyDeleteParams.builder().apiKeyId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + ApiKeyDeleteParams.builder().apiKeyId("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("") + } +} 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/ApiKeyListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyListParamsTest.kt new file mode 100644 index 00000000..e9582d7c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyListParamsTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ApiKeyListParamsTest { + + @Test + fun create() { + ApiKeyListParams.builder() + .apiKeyName("api_key_name") + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + ApiKeyListParams.builder() + .apiKeyName("api_key_name") + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("api_key_name", "api_key_name") + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = ApiKeyListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100644 index 00000000..1612ee3b --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ApiKeyRetrieveParamsTest { + + @Test + fun create() { + ApiKeyRetrieveParams.builder().apiKeyId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + ApiKeyRetrieveParams.builder().apiKeyId("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("") + } +} 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 new file mode 100755 index 00000000..0bda4c73 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ApiKeyTest.kt @@ -0,0 +1,51 @@ +// 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 ApiKeyTest { + + @Test + fun create() { + 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() + + assertThat(apiKey.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(apiKey.name()).isEqualTo("name") + assertThat(apiKey.previewName()).isEqualTo("preview_name") + assertThat(apiKey.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + 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 new file mode 100644 index 00000000..ccce4723 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartImageTest.kt @@ -0,0 +1,59 @@ +// 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 ChatCompletionContentPartImageTest { + + @Test + fun create() { + val chatCompletionContentPartImage = + ChatCompletionContentPartImage.builder() + .imageUrl( + ChatCompletionContentPartImage.ImageUrl.builder() + .url("url") + .detail(ChatCompletionContentPartImage.ImageUrl.Detail.AUTO) + .build() + ) + .type(ChatCompletionContentPartImage.Type.IMAGE_URL) + .build() + + assertThat(chatCompletionContentPartImage.imageUrl()) + .isEqualTo( + ChatCompletionContentPartImage.ImageUrl.builder() + .url("url") + .detail(ChatCompletionContentPartImage.ImageUrl.Detail.AUTO) + .build() + ) + 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 new file mode 100644 index 00000000..23dea46b --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionContentPartTextTest.kt @@ -0,0 +1,43 @@ +// 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 ChatCompletionContentPartTextTest { + + @Test + fun create() { + val chatCompletionContentPartText = + ChatCompletionContentPartText.builder() + .type(ChatCompletionContentPartText.Type.TEXT) + .text("text") + .build() + + 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 new file mode 100644 index 00000000..4ff757fd --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ChatCompletionMessageToolCallTest.kt @@ -0,0 +1,62 @@ +// 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 ChatCompletionMessageToolCallTest { + + @Test + fun create() { + val chatCompletionMessageToolCall = + ChatCompletionMessageToolCall.builder() + .id("id") + .function( + ChatCompletionMessageToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + .type(ChatCompletionMessageToolCall.Type.FUNCTION) + .build() + + assertThat(chatCompletionMessageToolCall.id()).isEqualTo("id") + assertThat(chatCompletionMessageToolCall.function()) + .isEqualTo( + ChatCompletionMessageToolCall.Function.builder() + .arguments("arguments") + .name("name") + .build() + ) + 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 new file mode 100644 index 00000000..e3df5465 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CodeBundleTest.kt @@ -0,0 +1,96 @@ +// 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 CodeBundleTest { + + @Test + fun create() { + 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() + + assertThat(codeBundle.bundleId()).isEqualTo("bundle_id") + assertThat(codeBundle.location()) + .isEqualTo( + CodeBundle.Location.ofExperiment( + 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() + ) + ) + assertThat(codeBundle.runtimeContext()) + .isEqualTo( + CodeBundle.RuntimeContext.builder() + .runtime(CodeBundle.RuntimeContext.Runtime.NODE) + .version("version") + .build() + ) + 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 new file mode 100755 index 00000000..931c2a7f --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CreateApiKeyOutputTest.kt @@ -0,0 +1,58 @@ +// 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 CreateApiKeyOutputTest { + + @Test + fun create() { + 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() + + assertThat(createApiKeyOutput.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(createApiKeyOutput.key()).isEqualTo("key") + assertThat(createApiKeyOutput.name()).isEqualTo("name") + assertThat(createApiKeyOutput.previewName()).isEqualTo("preview_name") + assertThat(createApiKeyOutput.created()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + 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 new file mode 100755 index 00000000..efd9ee0d --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/CrossObjectInsertResponseTest.kt @@ -0,0 +1,111 @@ +// 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 org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class CrossObjectInsertResponseTest { + + @Test + fun create() { + 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() + + assertThat(crossObjectInsertResponse.dataset()) + .contains( + CrossObjectInsertResponse.Dataset.builder() + .putAdditionalProperty( + "foo", + JsonValue.from(mapOf("row_ids" to listOf("string"))), + ) + .build() + ) + assertThat(crossObjectInsertResponse.experiment()) + .contains( + CrossObjectInsertResponse.Experiment.builder() + .putAdditionalProperty( + "foo", + JsonValue.from(mapOf("row_ids" to listOf("string"))), + ) + .build() + ) + assertThat(crossObjectInsertResponse.projectLogs()) + .contains( + CrossObjectInsertResponse.ProjectLogs.builder() + .putAdditionalProperty( + "foo", + JsonValue.from(mapOf("row_ids" to listOf("string"))), + ) + .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 new file mode 100755 index 00000000..40a33b54 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DataSummaryTest.kt @@ -0,0 +1,32 @@ +// 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 DataSummaryTest { + + @Test + fun create() { + val dataSummary = DataSummary.builder().totalRecords(0L).build() + + 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 old mode 100644 new mode 100755 index 353b25f6..117b3591 --- 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 @@ -2,41 +2,64 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetCreateParamsTest { +internal class DatasetCreateParamsTest { @Test - fun createDatasetCreateParams() { + fun create() { DatasetCreateParams.builder() - .name("string") - .description("string") + .name("x") .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .metadata( + DatasetCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) .build() } @Test - fun getBody() { + fun body() { val params = DatasetCreateParams.builder() - .name("string") - .description("string") + .name("x") .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .metadata( + DatasetCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") - assertThat(body.description()).isEqualTo("string") + + val body = params._body() + + assertThat(body.name()).isEqualTo("x") assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.description()).contains("description") + assertThat(body.metadata()) + .contains( + DatasetCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) } @Test - fun getBodyWithoutOptionalFields() { - val params = DatasetCreateParams.builder().name("string").build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") + fun bodyWithoutOptionalFields() { + val params = + DatasetCreateParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._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 old mode 100644 new mode 100755 index bb209233..87b85a35 --- 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 @@ -2,25 +2,23 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetDeleteParamsTest { +internal class DatasetDeleteParamsTest { @Test - fun createDatasetDeleteParams() { + fun create() { DatasetDeleteParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() } @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 new file mode 100755 index 00000000..de13fd72 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetEventTest.kt @@ -0,0 +1,104 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class DatasetEventTest { + + @Test + fun create() { + 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() + + assertThat(datasetEvent.id()).isEqualTo("id") + assertThat(datasetEvent._xactId()).isEqualTo("_xact_id") + assertThat(datasetEvent.created()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(datasetEvent.datasetId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(datasetEvent.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(datasetEvent.rootSpanId()).isEqualTo("root_span_id") + assertThat(datasetEvent.spanId()).isEqualTo("span_id") + assertThat(datasetEvent._expected()).isEqualTo(JsonValue.from(mapOf())) + assertThat(datasetEvent._input()).isEqualTo(JsonValue.from(mapOf())) + assertThat(datasetEvent.isRoot()).contains(true) + assertThat(datasetEvent.metadata()) + .contains(DatasetEvent.Metadata.builder().model("model").build()) + assertThat(datasetEvent.origin()) + .contains( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + 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 old mode 100644 new mode 100755 index eca95d86..383af384 --- 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 @@ -2,84 +2,93 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetFeedbackParamsTest { +internal class DatasetFeedbackParamsTest { @Test - fun createDatasetFeedbackParams() { + fun create() { DatasetFeedbackParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - DatasetFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .metadata(DatasetFeedbackParams.Feedback.Metadata.builder().build()) - .source(DatasetFeedbackParams.Feedback.Source.APP) - .build() - ) + .addFeedback( + FeedbackDatasetItem.builder() + .id("id") + .comment("comment") + .metadata( + FeedbackDatasetItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .source(FeedbackDatasetItem.Source.APP) + .addTag("string") + .build() ) .build() } @Test - fun getBody() { + fun pathParams() { val params = DatasetFeedbackParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - DatasetFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .metadata(DatasetFeedbackParams.Feedback.Metadata.builder().build()) - .source(DatasetFeedbackParams.Feedback.Source.APP) - .build() - ) - ) + .addFeedback(FeedbackDatasetItem.builder().id("id").build()) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.feedback()) - .isEqualTo( - listOf( - DatasetFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .metadata(DatasetFeedbackParams.Feedback.Metadata.builder().build()) - .source(DatasetFeedbackParams.Feedback.Source.APP) - .build() - ) - ) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = DatasetFeedbackParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback(listOf(DatasetFeedbackParams.Feedback.builder().id("string").build())) + .addFeedback( + FeedbackDatasetItem.builder() + .id("id") + .comment("comment") + .metadata( + FeedbackDatasetItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .source(FeedbackDatasetItem.Source.APP) + .addTag("string") + .build() + ) .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + assertThat(body.feedback()) - .isEqualTo(listOf(DatasetFeedbackParams.Feedback.builder().id("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() + ) } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = DatasetFeedbackParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback(listOf(DatasetFeedbackParams.Feedback.builder().id("string").build())) + .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("") + + val body = params._body() + + 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 old mode 100644 new mode 100755 index 85bc16de..79504f72 --- 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 @@ -2,57 +2,64 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetFetchParamsTest { +internal class DatasetFetchParamsTest { @Test - fun createDatasetFetchParams() { + fun create() { DatasetFetchParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() } @Test - fun getQueryParams() { + fun pathParams() { val params = - DatasetFetchParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) - .build() - val expected = mutableMapOf>() - expected.put("limit", listOf("123")) - expected.put("max_root_span_id", listOf("string")) - expected.put("max_xact_id", listOf("123")) - expected.put("version", listOf("123")) - assertThat(params.getQueryParams()).isEqualTo(expected) + 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 getQueryParamsWithoutOptionalFields() { + fun queryParams() { val params = - DatasetFetchParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - val expected = mutableMapOf>() - assertThat(params.getQueryParams()).isEqualTo(expected) + DatasetFetchParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("limit", "0") + .put("max_root_span_id", "max_root_span_id") + .put("max_xact_id", "max_xact_id") + .put("version", "version") + .build() + ) } @Test - fun getPathParam() { + fun queryParamsWithoutOptionalFields() { 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("") + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } 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 old mode 100644 new mode 100755 index ee354e5f..e3e09e9b --- 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,90 +2,63 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetFetchPostParamsTest { +internal class DatasetFetchPostParamsTest { @Test - fun createDatasetFetchPostParams() { + fun create() { DatasetFetchPostParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - DatasetFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(DatasetFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() } @Test - fun getBody() { + fun pathParams() { val params = DatasetFetchPostParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - DatasetFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(DatasetFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.filters()) - .isEqualTo( - listOf( - DatasetFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(DatasetFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - assertThat(body.limit()).isEqualTo(123L) - assertThat(body.maxRootSpanId()).isEqualTo("string") - assertThat(body.maxXactId()).isEqualTo(123L) - assertThat(body.version()).isEqualTo(123L) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = DatasetFetchPostParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + + assertThat(body.cursor()).contains("cursor") + assertThat(body.limit()).contains(0L) + assertThat(body.maxRootSpanId()).contains("max_root_span_id") + assertThat(body.maxXactId()).contains("max_xact_id") + assertThat(body.version()).contains("version") } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { 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("") + + val body = params._body() } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchPostResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchPostResponseTest.kt deleted file mode 100644 index 2d251f95..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchPostResponseTest.kt +++ /dev/null @@ -1,50 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.core.JsonValue -import java.time.OffsetDateTime -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class DatasetFetchPostResponseTest { - - @Test - fun createDatasetFetchPostResponse() { - val datasetFetchPostResponse = - DatasetFetchPostResponse.builder() - .events( - listOf( - DatasetFetchPostResponse.Event.builder() - .id("string") - ._xactId(123L) - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .input(JsonValue.from(mapOf())) - .metadata(DatasetFetchPostResponse.Event.Metadata.builder().build()) - .output(JsonValue.from(mapOf())) - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - ) - .build() - assertThat(datasetFetchPostResponse).isNotNull - assertThat(datasetFetchPostResponse.events()) - .containsExactly( - DatasetFetchPostResponse.Event.builder() - .id("string") - ._xactId(123L) - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .input(JsonValue.from(mapOf())) - .metadata(DatasetFetchPostResponse.Event.Metadata.builder().build()) - .output(JsonValue.from(mapOf())) - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - } -} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchResponseTest.kt deleted file mode 100644 index 4a16e5c6..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetFetchResponseTest.kt +++ /dev/null @@ -1,50 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.core.JsonValue -import java.time.OffsetDateTime -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class DatasetFetchResponseTest { - - @Test - fun createDatasetFetchResponse() { - val datasetFetchResponse = - DatasetFetchResponse.builder() - .events( - listOf( - DatasetFetchResponse.Event.builder() - .id("string") - ._xactId(123L) - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .input(JsonValue.from(mapOf())) - .metadata(DatasetFetchResponse.Event.Metadata.builder().build()) - .output(JsonValue.from(mapOf())) - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - ) - .build() - assertThat(datasetFetchResponse).isNotNull - assertThat(datasetFetchResponse.events()) - .containsExactly( - DatasetFetchResponse.Event.builder() - .id("string") - ._xactId(123L) - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .input(JsonValue.from(mapOf())) - .metadata(DatasetFetchResponse.Event.Metadata.builder().build()) - .output(JsonValue.from(mapOf())) - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - } -} 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 old mode 100644 new mode 100755 index 3f53fe8c..09847227 --- 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 @@ -3,129 +3,132 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* +import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetInsertParamsTest { +internal class DatasetInsertParamsTest { @Test - fun createDatasetInsertParams() { + fun create() { DatasetInsertParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - DatasetInsertParams.Event.ofInsertDatasetEventReplace( - DatasetInsertParams.Event.InsertDatasetEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .input(JsonValue.from(mapOf())) - .metadata( - DatasetInsertParams.Event.InsertDatasetEventReplace.Metadata - .builder() - .build() - ) - .output(JsonValue.from(mapOf())) + .addEvent( + 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() ) .build() } @Test - fun getBody() { + fun pathParams() { val params = DatasetInsertParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - DatasetInsertParams.Event.ofInsertDatasetEventReplace( - DatasetInsertParams.Event.InsertDatasetEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .input(JsonValue.from(mapOf())) - .metadata( - DatasetInsertParams.Event.InsertDatasetEventReplace.Metadata - .builder() - .build() - ) - .output(JsonValue.from(mapOf())) - .build() - ) - ) - ) + .addEvent(InsertDatasetEvent.builder().build()) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.events()) - .isEqualTo( - listOf( - DatasetInsertParams.Event.ofInsertDatasetEventReplace( - DatasetInsertParams.Event.InsertDatasetEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .input(JsonValue.from(mapOf())) - .metadata( - DatasetInsertParams.Event.InsertDatasetEventReplace.Metadata - .builder() - .build() - ) - .output(JsonValue.from(mapOf())) - .build() - ) - ) - ) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = DatasetInsertParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - DatasetInsertParams.Event.ofInsertDatasetEventReplace( - DatasetInsertParams.Event.InsertDatasetEventReplace.builder().build() + .addEvent( + 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() ) .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + assertThat(body.events()) - .isEqualTo( - listOf( - DatasetInsertParams.Event.ofInsertDatasetEventReplace( - DatasetInsertParams.Event.InsertDatasetEventReplace.builder().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() ) } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = DatasetInsertParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - DatasetInsertParams.Event.ofInsertDatasetEventReplace( - DatasetInsertParams.Event.InsertDatasetEventReplace.builder().build() - ) - ) - ) + .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("") + + val body = params._body() + + assertThat(body.events()).containsExactly(InsertDatasetEvent.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetInsertResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetInsertResponseTest.kt deleted file mode 100644 index a65d0c2f..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetInsertResponseTest.kt +++ /dev/null @@ -1,16 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class DatasetInsertResponseTest { - - @Test - fun createDatasetInsertResponse() { - val datasetInsertResponse = DatasetInsertResponse.builder().rowIds(listOf("string")).build() - assertThat(datasetInsertResponse).isNotNull - assertThat(datasetInsertResponse.rowIds()).containsExactly("string") - } -} 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/DatasetListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetListParamsTest.kt old mode 100644 new mode 100755 index d8f515ee..a6ffbbd4 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetListParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetListParamsTest.kt @@ -2,49 +2,63 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetListParamsTest { +internal class DatasetListParamsTest { @Test - fun createDatasetListParams() { + fun create() { DatasetListParams.builder() - .datasetName("string") + .datasetName("dataset_name") .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .orgName("string") - .projectName("string") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() } @Test - fun getQueryParams() { + fun queryParams() { val params = DatasetListParams.builder() - .datasetName("string") + .datasetName("dataset_name") .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .orgName("string") - .projectName("string") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - val expected = mutableMapOf>() - expected.put("dataset_name", listOf("string")) - expected.put("ending_before", listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - expected.put("limit", listOf("123")) - expected.put("org_name", listOf("string")) - expected.put("project_name", listOf("string")) - expected.put("starting_after", listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("dataset_name", "dataset_name") + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("project_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("project_name", "project_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) } @Test - fun getQueryParamsWithoutOptionalFields() { + fun queryParamsWithoutOptionalFields() { val params = DatasetListParams.builder().build() - val expected = mutableMapOf>() - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetReplaceParamsTest.kt deleted file mode 100644 index 953731b1..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetReplaceParamsTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.models.* -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class DatasetReplaceParamsTest { - - @Test - fun createDatasetReplaceParams() { - DatasetReplaceParams.builder() - .name("string") - .description("string") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - } - - @Test - fun getBody() { - val params = - DatasetReplaceParams.builder() - .name("string") - .description("string") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") - assertThat(body.description()).isEqualTo("string") - assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - } - - @Test - fun getBodyWithoutOptionalFields() { - val params = DatasetReplaceParams.builder().name("string").build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") - } -} 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 old mode 100644 new mode 100755 index 776cce3b..1cdff551 --- 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 @@ -2,27 +2,25 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetRetrieveParamsTest { +internal class DatasetRetrieveParamsTest { @Test - fun createDatasetRetrieveParams() { + fun create() { DatasetRetrieveParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() } @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 new file mode 100755 index 00000000..49062a2c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/DatasetSummarizeParamsTest.kt @@ -0,0 +1,56 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class DatasetSummarizeParamsTest { + + @Test + fun create() { + DatasetSummarizeParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeData(true) + .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 = + DatasetSummarizeParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeData(true) + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo(QueryParams.builder().put("summarize_data", "true").build()) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = + DatasetSummarizeParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 old mode 100644 new mode 100755 index bd1eebe9..b46ed92a --- 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 @@ -2,31 +2,70 @@ 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 -class DatasetTest { +internal class DatasetTest { @Test - fun createDataset() { + fun create() { val dataset = Dataset.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") + .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("string") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .metadata( + Dataset.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(dataset).isNotNull + assertThat(dataset.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(dataset.name()).isEqualTo("string") + assertThat(dataset.name()).isEqualTo("name") + assertThat(dataset.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(dataset.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(dataset.deletedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - assertThat(dataset.description()).contains("string") - assertThat(dataset.projectId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(dataset.description()).contains("description") + assertThat(dataset.metadata()) + .contains( + Dataset.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) 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 old mode 100644 new mode 100755 index d91f2208..daee439a --- 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 @@ -2,58 +2,67 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class DatasetUpdateParamsTest { +internal class DatasetUpdateParamsTest { @Test - fun createDatasetUpdateParams() { + fun create() { DatasetUpdateParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") - .description("string") + .description("description") + .metadata( + DatasetUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") .build() } @Test - fun getBody() { + fun pathParams() { val params = - DatasetUpdateParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") - .description("string") - .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") - assertThat(body.description()).isEqualTo("string") + 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 getBodyWithoutOptionalFields() { + fun body() { val params = DatasetUpdateParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") + .description("description") + .metadata( + DatasetUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") + + val body = params._body() + + assertThat(body.description()).contains("description") + assertThat(body.metadata()) + .contains( + DatasetUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.name()).contains("name") } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = - DatasetUpdateParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") - .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("") + DatasetUpdateParams.builder().datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + val body = params._body() } } 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 new file mode 100644 index 00000000..fbb18ad2 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarCreateParamsTest.kt @@ -0,0 +1,53 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EnvVarCreateParamsTest { + + @Test + fun create() { + EnvVarCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarCreateParams.ObjectType.ORGANIZATION) + .value("value") + .build() + } + + @Test + fun body() { + val params = + EnvVarCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarCreateParams.ObjectType.ORGANIZATION) + .value("value") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.objectType()).isEqualTo(EnvVarCreateParams.ObjectType.ORGANIZATION) + assertThat(body.value()).contains("value") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + EnvVarCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarCreateParams.ObjectType.ORGANIZATION) + .build() + + val body = params._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 new file mode 100644 index 00000000..80887f78 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarDeleteParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EnvVarDeleteParamsTest { + + @Test + fun create() { + EnvVarDeleteParams.builder().envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + EnvVarDeleteParams.builder().envVarId("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("") + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListParamsTest.kt new file mode 100644 index 00000000..4978303f --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListParamsTest.kt @@ -0,0 +1,55 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EnvVarListParamsTest { + + @Test + fun create() { + EnvVarListParams.builder() + .envVarName("env_var_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarObjectType.ORGANIZATION) + .build() + } + + @Test + fun queryParams() { + val params = + EnvVarListParams.builder() + .envVarName("env_var_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarObjectType.ORGANIZATION) + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("env_var_name", "env_var_name") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("object_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("object_type", "organization") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = EnvVarListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100644 index 00000000..d10c2868 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarListResponseTest.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 EnvVarListResponseTest { + + @Test + fun create() { + 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() + + assertThat(envVarListResponse.objects()) + .containsExactly( + 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() + ) + } + + @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 new file mode 100644 index 00000000..bb097933 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarReplaceParamsTest.kt @@ -0,0 +1,53 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EnvVarReplaceParamsTest { + + @Test + fun create() { + EnvVarReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarReplaceParams.ObjectType.ORGANIZATION) + .value("value") + .build() + } + + @Test + fun body() { + val params = + EnvVarReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarReplaceParams.ObjectType.ORGANIZATION) + .value("value") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.objectType()).isEqualTo(EnvVarReplaceParams.ObjectType.ORGANIZATION) + assertThat(body.value()).contains("value") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + EnvVarReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarReplaceParams.ObjectType.ORGANIZATION) + .build() + + val body = params._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 new file mode 100644 index 00000000..b3cefe22 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EnvVarRetrieveParamsTest { + + @Test + fun create() { + EnvVarRetrieveParams.builder().envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + EnvVarRetrieveParams.builder().envVarId("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("") + } +} 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 new file mode 100644 index 00000000..f046db47 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarTest.kt @@ -0,0 +1,51 @@ +// 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 EnvVarTest { + + @Test + fun create() { + 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() + + assertThat(envVar.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(envVar.name()).isEqualTo("name") + assertThat(envVar.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(envVar.objectType()).isEqualTo(EnvVar.ObjectType.ORGANIZATION) + 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 new file mode 100644 index 00000000..ec4c0edc --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EnvVarUpdateParamsTest.kt @@ -0,0 +1,59 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EnvVarUpdateParamsTest { + + @Test + fun create() { + EnvVarUpdateParams.builder() + .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .value("value") + .build() + } + + @Test + fun pathParams() { + val params = + EnvVarUpdateParams.builder() + .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .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 = + EnvVarUpdateParams.builder() + .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .value("value") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.value()).contains("value") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + EnvVarUpdateParams.builder() + .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .build() + + 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 new file mode 100644 index 00000000..99ba29a1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/EvalCreateParamsTest.kt @@ -0,0 +1,302 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class EvalCreateParamsTest { + + @Test + fun create() { + EvalCreateParams.builder() + .data( + EvalCreateParams.Data.DatasetId.builder() + .datasetId("dataset_id") + ._internalBtql( + EvalCreateParams.Data.DatasetId._InternalBtql + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .projectId("project_id") + .addScore( + EvalCreateParams.Score.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .task( + EvalCreateParams.Task.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .baseExperimentId("base_experiment_id") + .baseExperimentName("base_experiment_name") + .experimentName("experiment_name") + .gitMetadataSettings( + EvalCreateParams.GitMetadataSettings.builder() + .collect(EvalCreateParams.GitMetadataSettings.Collect.ALL) + .addField(EvalCreateParams.GitMetadataSettings.Field.COMMIT) + .build() + ) + .isPublic(true) + .maxConcurrency(0.0) + .metadata( + EvalCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .parent( + EvalCreateParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType(EvalCreateParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS) + .propagatedEvent( + EvalCreateParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + EvalCreateParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .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() + ) + .stream(true) + .timeout(0.0) + .trialCount(0.0) + .build() + } + + @Test + fun body() { + val params = + EvalCreateParams.builder() + .data( + EvalCreateParams.Data.DatasetId.builder() + .datasetId("dataset_id") + ._internalBtql( + EvalCreateParams.Data.DatasetId._InternalBtql + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .projectId("project_id") + .addScore( + EvalCreateParams.Score.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .task( + EvalCreateParams.Task.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .baseExperimentId("base_experiment_id") + .baseExperimentName("base_experiment_name") + .experimentName("experiment_name") + .gitMetadataSettings( + EvalCreateParams.GitMetadataSettings.builder() + .collect(EvalCreateParams.GitMetadataSettings.Collect.ALL) + .addField(EvalCreateParams.GitMetadataSettings.Field.COMMIT) + .build() + ) + .isPublic(true) + .maxConcurrency(0.0) + .metadata( + EvalCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .parent( + EvalCreateParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + EvalCreateParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + EvalCreateParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + EvalCreateParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .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() + ) + .stream(true) + .timeout(0.0) + .trialCount(0.0) + .build() + + val body = params._body() + + assertThat(body.data()) + .isEqualTo( + EvalCreateParams.Data.ofDatasetId( + EvalCreateParams.Data.DatasetId.builder() + .datasetId("dataset_id") + ._internalBtql( + EvalCreateParams.Data.DatasetId._InternalBtql + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + ) + assertThat(body.projectId()).isEqualTo("project_id") + assertThat(body.scores()) + .containsExactly( + EvalCreateParams.Score.ofFunctionId( + EvalCreateParams.Score.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + ) + assertThat(body.task()) + .isEqualTo( + EvalCreateParams.Task.ofFunctionId( + EvalCreateParams.Task.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + ) + assertThat(body.baseExperimentId()).contains("base_experiment_id") + assertThat(body.baseExperimentName()).contains("base_experiment_name") + assertThat(body.experimentName()).contains("experiment_name") + assertThat(body.gitMetadataSettings()) + .contains( + EvalCreateParams.GitMetadataSettings.builder() + .collect(EvalCreateParams.GitMetadataSettings.Collect.ALL) + .addField(EvalCreateParams.GitMetadataSettings.Field.COMMIT) + .build() + ) + assertThat(body.isPublic()).contains(true) + assertThat(body.maxConcurrency()).contains(0.0) + assertThat(body.metadata()) + .contains( + EvalCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.parent()) + .contains( + EvalCreateParams.Parent.ofSpanParentStruct( + EvalCreateParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + EvalCreateParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + EvalCreateParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + EvalCreateParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .build() + ) + ) + assertThat(body.repoInfo()) + .contains( + 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() + ) + assertThat(body.stream()).contains(true) + assertThat(body.timeout()).contains(0.0) + assertThat(body.trialCount()).contains(0.0) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + EvalCreateParams.builder() + .data(EvalCreateParams.Data.DatasetId.builder().datasetId("dataset_id").build()) + .projectId("project_id") + .addScore( + EvalCreateParams.Score.FunctionId.builder().functionId("function_id").build() + ) + .task(EvalCreateParams.Task.FunctionId.builder().functionId("function_id").build()) + .build() + + val body = params._body() + + assertThat(body.data()) + .isEqualTo( + EvalCreateParams.Data.ofDatasetId( + EvalCreateParams.Data.DatasetId.builder().datasetId("dataset_id").build() + ) + ) + assertThat(body.projectId()).isEqualTo("project_id") + assertThat(body.scores()) + .containsExactly( + EvalCreateParams.Score.ofFunctionId( + EvalCreateParams.Score.FunctionId.builder().functionId("function_id").build() + ) + ) + assertThat(body.task()) + .isEqualTo( + EvalCreateParams.Task.ofFunctionId( + EvalCreateParams.Task.FunctionId.builder().functionId("function_id").build() + ) + ) + } +} 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 old mode 100644 new mode 100755 index fcf3dc92..9c672670 --- 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 @@ -2,99 +2,117 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentCreateParamsTest { +internal class ExperimentCreateParamsTest { @Test - fun createExperimentCreateParams() { + fun create() { ExperimentCreateParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentCreateParams.Metadata.builder().build()) - .name("string") + .datasetVersion("dataset_version") + .description("description") + .ensureNew(true) + .metadata( + ExperimentCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("x") .public_(true) .repoInfo( - ExperimentCreateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) .build() } @Test - fun getBody() { + fun body() { val params = ExperimentCreateParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentCreateParams.Metadata.builder().build()) - .name("string") + .datasetVersion("dataset_version") + .description("description") + .ensureNew(true) + .metadata( + ExperimentCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("x") .public_(true) .repoInfo( - ExperimentCreateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.baseExpId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.datasetId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.datasetVersion()).isEqualTo("string") - assertThat(body.description()).isEqualTo("string") - assertThat(body.metadata()).isEqualTo(ExperimentCreateParams.Metadata.builder().build()) - assertThat(body.name()).isEqualTo("string") - assertThat(body.public_()).isEqualTo(true) + assertThat(body.baseExpId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.datasetId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.datasetVersion()).contains("dataset_version") + assertThat(body.description()).contains("description") + assertThat(body.ensureNew()).contains(true) + assertThat(body.metadata()) + .contains( + ExperimentCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.name()).contains("x") + assertThat(body.public_()).contains(true) assertThat(body.repoInfo()) - .isEqualTo( - ExperimentCreateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + .contains( + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) } @Test - fun getBodyWithoutOptionalFields() { + fun bodyWithoutOptionalFields() { val params = ExperimentCreateParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._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 old mode 100644 new mode 100755 index 4577db52..d3aa984d --- 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 @@ -2,29 +2,27 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentDeleteParamsTest { +internal class ExperimentDeleteParamsTest { @Test - fun createExperimentDeleteParams() { + fun create() { ExperimentDeleteParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() } @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 new file mode 100755 index 00000000..44c2afc8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentEventTest.kt @@ -0,0 +1,192 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ExperimentEventTest { + + @Test + fun create() { + 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() + + assertThat(experimentEvent.id()).isEqualTo("id") + assertThat(experimentEvent._xactId()).isEqualTo("_xact_id") + assertThat(experimentEvent.created()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(experimentEvent.experimentId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(experimentEvent.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(experimentEvent.rootSpanId()).isEqualTo("root_span_id") + assertThat(experimentEvent.spanId()).isEqualTo("span_id") + assertThat(experimentEvent.context()) + .contains( + ExperimentEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + assertThat(experimentEvent._error()).isEqualTo(JsonValue.from(mapOf())) + assertThat(experimentEvent._expected()).isEqualTo(JsonValue.from(mapOf())) + assertThat(experimentEvent._input()).isEqualTo(JsonValue.from(mapOf())) + assertThat(experimentEvent.isRoot()).contains(true) + assertThat(experimentEvent.metadata()) + .contains(ExperimentEvent.Metadata.builder().model("model").build()) + assertThat(experimentEvent.metrics()) + .contains( + 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() + ) + assertThat(experimentEvent.origin()) + .contains( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + assertThat(experimentEvent._output()).isEqualTo(JsonValue.from(mapOf())) + assertThat(experimentEvent.scores()) + .contains( + ExperimentEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(experimentEvent.spanAttributes()) + .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + 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 old mode 100644 new mode 100755 index fe0ce4af..ed20850d --- 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,90 +3,111 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentFeedbackParamsTest { +internal class ExperimentFeedbackParamsTest { @Test - fun createExperimentFeedbackParams() { + fun create() { ExperimentFeedbackParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - ExperimentFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .expected(JsonValue.from(mapOf())) - .metadata(ExperimentFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ExperimentFeedbackParams.Feedback.Scores.builder().build()) - .source(ExperimentFeedbackParams.Feedback.Source.APP) - .build() - ) + .addFeedback( + 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() ) .build() } @Test - fun getBody() { + fun pathParams() { val params = ExperimentFeedbackParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - ExperimentFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .expected(JsonValue.from(mapOf())) - .metadata(ExperimentFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ExperimentFeedbackParams.Feedback.Scores.builder().build()) - .source(ExperimentFeedbackParams.Feedback.Source.APP) - .build() - ) - ) + .addFeedback(FeedbackExperimentItem.builder().id("id").build()) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.feedback()) - .isEqualTo( - listOf( - ExperimentFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .expected(JsonValue.from(mapOf())) - .metadata(ExperimentFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ExperimentFeedbackParams.Feedback.Scores.builder().build()) - .source(ExperimentFeedbackParams.Feedback.Source.APP) - .build() - ) - ) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = ExperimentFeedbackParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback(listOf(ExperimentFeedbackParams.Feedback.builder().id("string").build())) + .addFeedback( + 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() + ) .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + assertThat(body.feedback()) - .isEqualTo(listOf(ExperimentFeedbackParams.Feedback.builder().id("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() + ) } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = ExperimentFeedbackParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback(listOf(ExperimentFeedbackParams.Feedback.builder().id("string").build())) + .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("") + + val body = params._body() + + assertThat(body.feedback()) + .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 old mode 100644 new mode 100755 index f3ed3811..70160fd1 --- 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 @@ -2,61 +2,68 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentFetchParamsTest { +internal class ExperimentFetchParamsTest { @Test - fun createExperimentFetchParams() { + fun create() { ExperimentFetchParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() } @Test - fun getQueryParams() { + fun pathParams() { val params = ExperimentFetchParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) .build() - val expected = mutableMapOf>() - expected.put("limit", listOf("123")) - expected.put("max_root_span_id", listOf("string")) - expected.put("max_xact_id", listOf("123")) - expected.put("version", listOf("123")) - assertThat(params.getQueryParams()).isEqualTo(expected) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getQueryParamsWithoutOptionalFields() { + fun queryParams() { val params = ExperimentFetchParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() - val expected = mutableMapOf>() - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("limit", "0") + .put("max_root_span_id", "max_root_span_id") + .put("max_xact_id", "max_xact_id") + .put("version", "version") + .build() + ) } @Test - fun getPathParam() { + fun queryParamsWithoutOptionalFields() { 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("") + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } 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 old mode 100644 new mode 100755 index a0f83206..b1a4e806 --- 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,90 +2,63 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentFetchPostParamsTest { +internal class ExperimentFetchPostParamsTest { @Test - fun createExperimentFetchPostParams() { + fun create() { ExperimentFetchPostParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - ExperimentFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ExperimentFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() } @Test - fun getBody() { + fun pathParams() { val params = ExperimentFetchPostParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - ExperimentFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ExperimentFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.filters()) - .isEqualTo( - listOf( - ExperimentFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ExperimentFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - assertThat(body.limit()).isEqualTo(123L) - assertThat(body.maxRootSpanId()).isEqualTo("string") - assertThat(body.maxXactId()).isEqualTo(123L) - assertThat(body.version()).isEqualTo(123L) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = ExperimentFetchPostParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + + assertThat(body.cursor()).contains("cursor") + assertThat(body.limit()).contains(0L) + assertThat(body.maxRootSpanId()).contains("max_root_span_id") + assertThat(body.maxXactId()).contains("max_xact_id") + assertThat(body.version()).contains("version") } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { 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("") + + val body = params._body() } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchPostResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchPostResponseTest.kt deleted file mode 100644 index 866256d5..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchPostResponseTest.kt +++ /dev/null @@ -1,96 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.core.JsonValue -import java.time.OffsetDateTime -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ExperimentFetchPostResponseTest { - - @Test - fun createExperimentFetchPostResponse() { - val experimentFetchPostResponse = - ExperimentFetchPostResponse.builder() - .events( - listOf( - ExperimentFetchPostResponse.Event.builder() - .id("string") - ._xactId(123L) - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ExperimentFetchPostResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ExperimentFetchPostResponse.Event.Metadata.builder().build()) - .metrics( - ExperimentFetchPostResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ExperimentFetchPostResponse.Event.Scores.builder().build()) - .spanAttributes( - ExperimentFetchPostResponse.Event.SpanAttributes.builder() - .name("string") - .type(ExperimentFetchPostResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - ) - .build() - assertThat(experimentFetchPostResponse).isNotNull - assertThat(experimentFetchPostResponse.events()) - .containsExactly( - ExperimentFetchPostResponse.Event.builder() - .id("string") - ._xactId(123L) - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ExperimentFetchPostResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ExperimentFetchPostResponse.Event.Metadata.builder().build()) - .metrics( - ExperimentFetchPostResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ExperimentFetchPostResponse.Event.Scores.builder().build()) - .spanAttributes( - ExperimentFetchPostResponse.Event.SpanAttributes.builder() - .name("string") - .type(ExperimentFetchPostResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - } -} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchResponseTest.kt deleted file mode 100644 index ac2da73a..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentFetchResponseTest.kt +++ /dev/null @@ -1,96 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.core.JsonValue -import java.time.OffsetDateTime -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ExperimentFetchResponseTest { - - @Test - fun createExperimentFetchResponse() { - val experimentFetchResponse = - ExperimentFetchResponse.builder() - .events( - listOf( - ExperimentFetchResponse.Event.builder() - .id("string") - ._xactId(123L) - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ExperimentFetchResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ExperimentFetchResponse.Event.Metadata.builder().build()) - .metrics( - ExperimentFetchResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ExperimentFetchResponse.Event.Scores.builder().build()) - .spanAttributes( - ExperimentFetchResponse.Event.SpanAttributes.builder() - .name("string") - .type(ExperimentFetchResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - ) - .build() - assertThat(experimentFetchResponse).isNotNull - assertThat(experimentFetchResponse.events()) - .containsExactly( - ExperimentFetchResponse.Event.builder() - .id("string") - ._xactId(123L) - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ExperimentFetchResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ExperimentFetchResponse.Event.Metadata.builder().build()) - .metrics( - ExperimentFetchResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ExperimentFetchResponse.Event.Scores.builder().build()) - .spanAttributes( - ExperimentFetchResponse.Event.SpanAttributes.builder() - .name("string") - .type(ExperimentFetchResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - } -} 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 old mode 100644 new mode 100755 index 5acb4ed5..105b8225 --- 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 @@ -3,240 +3,219 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* +import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentInsertParamsTest { +internal class ExperimentInsertParamsTest { @Test - fun createExperimentInsertParams() { + fun create() { ExperimentInsertParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ExperimentInsertParams.Event.ofInsertExperimentEventReplace( - ExperimentInsertParams.Event.InsertExperimentEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Metadata - .builder() - .build() - ) - .metrics( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Scores - .builder() - .build() - ) - .spanAttributes( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) + .addEvent( + 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() ) .build() } @Test - fun getBody() { + fun pathParams() { val params = ExperimentInsertParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ExperimentInsertParams.Event.ofInsertExperimentEventReplace( - ExperimentInsertParams.Event.InsertExperimentEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .Metadata - .builder() - .build() - ) - .metrics( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Scores - .builder() - .build() - ) - .spanAttributes( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ExperimentInsertParams.Event - .InsertExperimentEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) - .build() - ) - ) - ) + .addEvent(InsertExperimentEvent.builder().build()) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.events()) - .isEqualTo( - listOf( - ExperimentInsertParams.Event.ofInsertExperimentEventReplace( - ExperimentInsertParams.Event.InsertExperimentEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Metadata - .builder() - .build() - ) - .metrics( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ExperimentInsertParams.Event.InsertExperimentEventReplace.Scores - .builder() - .build() - ) - .spanAttributes( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) - .build() - ) - ) - ) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = ExperimentInsertParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ExperimentInsertParams.Event.ofInsertExperimentEventReplace( - ExperimentInsertParams.Event.InsertExperimentEventReplace.builder() + .addEvent( + 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() ) .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + assertThat(body.events()) - .isEqualTo( - listOf( - ExperimentInsertParams.Event.ofInsertExperimentEventReplace( - ExperimentInsertParams.Event.InsertExperimentEventReplace.builder().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() ) } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = ExperimentInsertParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ExperimentInsertParams.Event.ofInsertExperimentEventReplace( - ExperimentInsertParams.Event.InsertExperimentEventReplace.builder() - .build() - ) - ) - ) + .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("") + + val body = params._body() + + assertThat(body.events()).containsExactly(InsertExperimentEvent.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentInsertResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentInsertResponseTest.kt deleted file mode 100644 index 382e1f24..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentInsertResponseTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ExperimentInsertResponseTest { - - @Test - fun createExperimentInsertResponse() { - val experimentInsertResponse = - ExperimentInsertResponse.builder().rowIds(listOf("string")).build() - assertThat(experimentInsertResponse).isNotNull - assertThat(experimentInsertResponse.rowIds()).containsExactly("string") - } -} 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/ExperimentListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentListParamsTest.kt old mode 100644 new mode 100755 index 8323b09b..9c1814c3 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentListParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentListParamsTest.kt @@ -2,49 +2,63 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentListParamsTest { +internal class ExperimentListParamsTest { @Test - fun createExperimentListParams() { + fun create() { ExperimentListParams.builder() .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .experimentName("string") - .limit(123L) - .orgName("string") - .projectName("string") + .experimentName("experiment_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() } @Test - fun getQueryParams() { + fun queryParams() { val params = ExperimentListParams.builder() .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .experimentName("string") - .limit(123L) - .orgName("string") - .projectName("string") + .experimentName("experiment_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - val expected = mutableMapOf>() - expected.put("ending_before", listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - expected.put("experiment_name", listOf("string")) - expected.put("limit", listOf("123")) - expected.put("org_name", listOf("string")) - expected.put("project_name", listOf("string")) - expected.put("starting_after", listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("experiment_name", "experiment_name") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("project_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("project_name", "project_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) } @Test - fun getQueryParamsWithoutOptionalFields() { + fun queryParamsWithoutOptionalFields() { val params = ExperimentListParams.builder().build() - val expected = mutableMapOf>() - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentReplaceParamsTest.kt deleted file mode 100644 index 90991ef3..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentReplaceParamsTest.kt +++ /dev/null @@ -1,100 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.models.* -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ExperimentReplaceParamsTest { - - @Test - fun createExperimentReplaceParams() { - ExperimentReplaceParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentReplaceParams.Metadata.builder().build()) - .name("string") - .public_(true) - .repoInfo( - ExperimentReplaceParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") - .dirty(true) - .gitDiff("string") - .tag("string") - .build() - ) - .build() - } - - @Test - fun getBody() { - val params = - ExperimentReplaceParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentReplaceParams.Metadata.builder().build()) - .name("string") - .public_(true) - .repoInfo( - ExperimentReplaceParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") - .dirty(true) - .gitDiff("string") - .tag("string") - .build() - ) - .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.baseExpId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.datasetId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.datasetVersion()).isEqualTo("string") - assertThat(body.description()).isEqualTo("string") - assertThat(body.metadata()).isEqualTo(ExperimentReplaceParams.Metadata.builder().build()) - assertThat(body.name()).isEqualTo("string") - assertThat(body.public_()).isEqualTo(true) - assertThat(body.repoInfo()) - .isEqualTo( - ExperimentReplaceParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") - .dirty(true) - .gitDiff("string") - .tag("string") - .build() - ) - } - - @Test - fun getBodyWithoutOptionalFields() { - val params = - ExperimentReplaceParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - } -} 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 old mode 100644 new mode 100755 index 5efe0624..26795ef7 --- 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 @@ -2,29 +2,27 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentRetrieveParamsTest { +internal class ExperimentRetrieveParamsTest { @Test - fun createExperimentRetrieveParams() { + fun create() { ExperimentRetrieveParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() } @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 new file mode 100755 index 00000000..c5599fa2 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ExperimentSummarizeParamsTest.kt @@ -0,0 +1,63 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ExperimentSummarizeParamsTest { + + @Test + fun create() { + ExperimentSummarizeParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeScores(true) + .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 = + ExperimentSummarizeParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeScores(true) + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("comparison_experiment_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("summarize_scores", "true") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = + ExperimentSummarizeParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 old mode 100644 new mode 100755 index b4233ecc..551f6fd0 --- 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 @@ -2,71 +2,129 @@ 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 -class ExperimentTest { +internal class ExperimentTest { @Test - fun createExperiment() { + fun create() { val experiment = Experiment.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") + .name("name") .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .public_(true) .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .commit("string") + .commit("commit") .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") + .datasetVersion("dataset_version") .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .description("string") - .metadata(Experiment.Metadata.builder().build()) + .description("description") + .metadata( + Experiment.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) .repoInfo( - Experiment.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - assertThat(experiment).isNotNull + assertThat(experiment.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(experiment.name()).isEqualTo("string") + assertThat(experiment.name()).isEqualTo("name") assertThat(experiment.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(experiment.public_()).isEqualTo(true) assertThat(experiment.baseExpId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(experiment.commit()).contains("string") + assertThat(experiment.commit()).contains("commit") assertThat(experiment.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(experiment.datasetId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(experiment.datasetVersion()).contains("string") + assertThat(experiment.datasetVersion()).contains("dataset_version") assertThat(experiment.deletedAt()) .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - assertThat(experiment.description()).contains("string") - assertThat(experiment.metadata()).contains(Experiment.Metadata.builder().build()) + assertThat(experiment.description()).contains("description") + assertThat(experiment.metadata()) + .contains( + Experiment.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) assertThat(experiment.repoInfo()) .contains( - Experiment.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) 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 old mode 100644 new mode 100755 index 88cbb07f..214f8988 --- 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 @@ -2,110 +2,123 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ExperimentUpdateParamsTest { +internal class ExperimentUpdateParamsTest { @Test - fun createExperimentUpdateParams() { + fun create() { ExperimentUpdateParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentUpdateParams.Metadata.builder().build()) - .name("string") + .datasetVersion("dataset_version") + .description("description") + .metadata( + ExperimentUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") .public_(true) .repoInfo( - ExperimentUpdateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) .build() } @Test - fun getBody() { + 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 = ExperimentUpdateParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentUpdateParams.Metadata.builder().build()) - .name("string") + .datasetVersion("dataset_version") + .description("description") + .metadata( + ExperimentUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") .public_(true) .repoInfo( - ExperimentUpdateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.baseExpId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.datasetId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(body.datasetVersion()).isEqualTo("string") - assertThat(body.description()).isEqualTo("string") - assertThat(body.metadata()).isEqualTo(ExperimentUpdateParams.Metadata.builder().build()) - assertThat(body.name()).isEqualTo("string") - assertThat(body.public_()).isEqualTo(true) + + val body = params._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") + assertThat(body.description()).contains("description") + assertThat(body.metadata()) + .contains( + ExperimentUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.name()).contains("name") + assertThat(body.public_()).contains(true) assertThat(body.repoInfo()) - .isEqualTo( - ExperimentUpdateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + .contains( + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) } @Test - fun getBodyWithoutOptionalFields() { + fun bodyWithoutOptionalFields() { val params = ExperimentUpdateParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - val body = params.getBody() - assertThat(body).isNotNull - } - @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("") + val body = params._body() } } 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 new file mode 100755 index 00000000..4018b1b8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackDatasetItemTest.kt @@ -0,0 +1,65 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FeedbackDatasetItemTest { + + @Test + fun create() { + 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() + + assertThat(feedbackDatasetItem.id()).isEqualTo("id") + assertThat(feedbackDatasetItem.comment()).contains("comment") + assertThat(feedbackDatasetItem.metadata()) + .contains( + FeedbackDatasetItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(feedbackDatasetItem.source()).contains(FeedbackDatasetItem.Source.APP) + 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 new file mode 100755 index 00000000..733c7f31 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackExperimentItemTest.kt @@ -0,0 +1,85 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FeedbackExperimentItemTest { + + @Test + fun create() { + 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() + + assertThat(feedbackExperimentItem.id()).isEqualTo("id") + assertThat(feedbackExperimentItem.comment()).contains("comment") + assertThat(feedbackExperimentItem._expected()) + .isEqualTo(JsonValue.from(mapOf())) + assertThat(feedbackExperimentItem.metadata()) + .contains( + FeedbackExperimentItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(feedbackExperimentItem.scores()) + .contains( + FeedbackExperimentItem.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(feedbackExperimentItem.source()).contains(FeedbackExperimentItem.Source.APP) + 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 new file mode 100755 index 00000000..91b52fe5 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackProjectLogsItemTest.kt @@ -0,0 +1,85 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FeedbackProjectLogsItemTest { + + @Test + fun create() { + 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() + + assertThat(feedbackProjectLogsItem.id()).isEqualTo("id") + assertThat(feedbackProjectLogsItem.comment()).contains("comment") + assertThat(feedbackProjectLogsItem._expected()) + .isEqualTo(JsonValue.from(mapOf())) + assertThat(feedbackProjectLogsItem.metadata()) + .contains( + FeedbackProjectLogsItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(feedbackProjectLogsItem.scores()) + .contains( + FeedbackProjectLogsItem.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(feedbackProjectLogsItem.source()).contains(FeedbackProjectLogsItem.Source.APP) + 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 new file mode 100755 index 00000000..f7e73e95 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FeedbackResponseSchemaTest.kt @@ -0,0 +1,34 @@ +// 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 FeedbackResponseSchemaTest { + + @Test + fun create() { + val feedbackResponseSchema = + FeedbackResponseSchema.builder().status(FeedbackResponseSchema.Status.SUCCESS).build() + + 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 new file mode 100755 index 00000000..b61492e2 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchDatasetEventsResponseTest.kt @@ -0,0 +1,116 @@ +// 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 FetchDatasetEventsResponseTest { + + @Test + fun create() { + 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() + + assertThat(fetchDatasetEventsResponse.events()) + .containsExactly( + 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() + ) + 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 new file mode 100755 index 00000000..89e2327e --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchExperimentEventsResponseTest.kt @@ -0,0 +1,207 @@ +// 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 FetchExperimentEventsResponseTest { + + @Test + fun create() { + 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() + + assertThat(fetchExperimentEventsResponse.events()) + .containsExactly( + 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() + ) + 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 new file mode 100755 index 00000000..53d51aa5 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FetchProjectLogsEventsResponseTest.kt @@ -0,0 +1,210 @@ +// 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 FetchProjectLogsEventsResponseTest { + + @Test + fun create() { + 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() + + assertThat(fetchProjectLogsEventsResponse.events()) + .containsExactly( + 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() + ) + 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 new file mode 100755 index 00000000..1c191402 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionCreateParamsTest.kt @@ -0,0 +1,372 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionCreateParamsTest { + + @Test + fun create() { + FunctionCreateParams.builder() + .functionData( + FunctionCreateParams.FunctionData.Prompt.builder() + .type(FunctionCreateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionCreateParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionCreateParams.FunctionType.LLM) + .origin( + FunctionCreateParams.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 body() { + val params = + FunctionCreateParams.builder() + .functionData( + FunctionCreateParams.FunctionData.Prompt.builder() + .type(FunctionCreateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionCreateParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionCreateParams.FunctionType.LLM) + .origin( + FunctionCreateParams.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 body = params._body() + + assertThat(body.functionData()) + .isEqualTo( + FunctionCreateParams.FunctionData.ofPrompt( + FunctionCreateParams.FunctionData.Prompt.builder() + .type(FunctionCreateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + ) + assertThat(body.name()).isEqualTo("x") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.slug()).isEqualTo("x") + assertThat(body.description()).contains("description") + assertThat(body.functionSchema()) + .contains( + FunctionCreateParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + assertThat(body.functionType()).contains(FunctionCreateParams.FunctionType.LLM) + assertThat(body.origin()) + .contains( + FunctionCreateParams.Origin.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .internal_(true) + .build() + ) + assertThat(body.promptData()) + .contains( + 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() + ) + assertThat(body.tags().getOrNull()).containsExactly("string") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FunctionCreateParams.builder() + .functionData( + FunctionCreateParams.FunctionData.Prompt.builder() + .type(FunctionCreateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .build() + + val body = params._body() + + assertThat(body.functionData()) + .isEqualTo( + FunctionCreateParams.FunctionData.ofPrompt( + FunctionCreateParams.FunctionData.Prompt.builder() + .type(FunctionCreateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + ) + 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/FunctionDeleteParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionDeleteParamsTest.kt new file mode 100755 index 00000000..3e0df519 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionDeleteParamsTest.kt @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionDeleteParamsTest { + + @Test + fun create() { + FunctionDeleteParams.builder().functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + FunctionDeleteParams.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("") + } +} 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 new file mode 100644 index 00000000..5709c972 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionInvokeParamsTest.kt @@ -0,0 +1,169 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionInvokeParamsTest { + + @Test + fun create() { + FunctionInvokeParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .addMessage( + FunctionInvokeParams.Message.System.builder() + .role(FunctionInvokeParams.Message.System.Role.SYSTEM) + .content("content") + .name("name") + .build() + ) + .metadata( + FunctionInvokeParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .mode(FunctionInvokeParams.Mode.AUTO) + .parent( + FunctionInvokeParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + FunctionInvokeParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + FunctionInvokeParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + FunctionInvokeParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .build() + ) + .stream(true) + .version("version") + .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 = + FunctionInvokeParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .addMessage( + FunctionInvokeParams.Message.System.builder() + .role(FunctionInvokeParams.Message.System.Role.SYSTEM) + .content("content") + .name("name") + .build() + ) + .metadata( + FunctionInvokeParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .mode(FunctionInvokeParams.Mode.AUTO) + .parent( + FunctionInvokeParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + FunctionInvokeParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + FunctionInvokeParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + FunctionInvokeParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .build() + ) + .stream(true) + .version("version") + .build() + + val body = params._body() + + assertThat(body._expected()).isEqualTo(JsonValue.from(mapOf())) + assertThat(body._input()).isEqualTo(JsonValue.from(mapOf())) + 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()) + .contains( + FunctionInvokeParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(body.mode()).contains(FunctionInvokeParams.Mode.AUTO) + assertThat(body.parent()) + .contains( + FunctionInvokeParams.Parent.ofSpanParentStruct( + FunctionInvokeParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + FunctionInvokeParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + FunctionInvokeParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + FunctionInvokeParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .build() + ) + ) + assertThat(body.stream()).contains(true) + assertThat(body.version()).contains("version") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FunctionInvokeParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + } +} 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/FunctionListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionListParamsTest.kt new file mode 100755 index 00000000..00e37ef9 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionListParamsTest.kt @@ -0,0 +1,70 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionListParamsTest { + + @Test + fun create() { + FunctionListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .functionName("function_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .slug("slug") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .version("version") + .build() + } + + @Test + fun queryParams() { + val params = + FunctionListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .functionName("function_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .slug("slug") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .version("version") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("function_name", "function_name") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("project_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("project_name", "project_name") + .put("slug", "slug") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("version", "version") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = FunctionListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100755 index 00000000..3e43d5eb --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionReplaceParamsTest.kt @@ -0,0 +1,372 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionReplaceParamsTest { + + @Test + fun create() { + FunctionReplaceParams.builder() + .functionData( + FunctionReplaceParams.FunctionData.Prompt.builder() + .type(FunctionReplaceParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionReplaceParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionReplaceParams.FunctionType.LLM) + .origin( + FunctionReplaceParams.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 body() { + val params = + FunctionReplaceParams.builder() + .functionData( + FunctionReplaceParams.FunctionData.Prompt.builder() + .type(FunctionReplaceParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionReplaceParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionReplaceParams.FunctionType.LLM) + .origin( + FunctionReplaceParams.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 body = params._body() + + assertThat(body.functionData()) + .isEqualTo( + FunctionReplaceParams.FunctionData.ofPrompt( + FunctionReplaceParams.FunctionData.Prompt.builder() + .type(FunctionReplaceParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + ) + assertThat(body.name()).isEqualTo("x") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.slug()).isEqualTo("x") + assertThat(body.description()).contains("description") + assertThat(body.functionSchema()) + .contains( + FunctionReplaceParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + assertThat(body.functionType()).contains(FunctionReplaceParams.FunctionType.LLM) + assertThat(body.origin()) + .contains( + FunctionReplaceParams.Origin.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .internal_(true) + .build() + ) + assertThat(body.promptData()) + .contains( + 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() + ) + assertThat(body.tags().getOrNull()).containsExactly("string") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FunctionReplaceParams.builder() + .functionData( + FunctionReplaceParams.FunctionData.Prompt.builder() + .type(FunctionReplaceParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .build() + + val body = params._body() + + assertThat(body.functionData()) + .isEqualTo( + FunctionReplaceParams.FunctionData.ofPrompt( + FunctionReplaceParams.FunctionData.Prompt.builder() + .type(FunctionReplaceParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + ) + 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/FunctionRetrieveParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionRetrieveParamsTest.kt new file mode 100755 index 00000000..fd70fae8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionRetrieveParamsTest.kt @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionRetrieveParamsTest { + + @Test + fun create() { + FunctionRetrieveParams.builder().functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + FunctionRetrieveParams.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("") + } +} 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 new file mode 100755 index 00000000..45ecb9f8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionTest.kt @@ -0,0 +1,386 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionTest { + + @Test + fun create() { + 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() + + assertThat(function.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(function._xactId()).isEqualTo("_xact_id") + assertThat(function.functionData()) + .isEqualTo( + Function.FunctionData.ofPrompt( + Function.FunctionData.Prompt.builder() + .type(Function.FunctionData.Prompt.Type.PROMPT) + .build() + ) + ) + assertThat(function.logId()).isEqualTo(Function.LogId.P) + assertThat(function.name()).isEqualTo("name") + assertThat(function.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(function.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(function.slug()).isEqualTo("slug") + assertThat(function.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(function.description()).contains("description") + assertThat(function.functionSchema()) + .contains( + Function.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + assertThat(function.functionType()).contains(Function.FunctionType.LLM) + assertThat(function.metadata()) + .contains( + Function.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(function.origin()) + .contains( + Function.Origin.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .internal_(true) + .build() + ) + assertThat(function.promptData()) + .contains( + 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() + ) + 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 new file mode 100755 index 00000000..efa128b9 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/FunctionUpdateParamsTest.kt @@ -0,0 +1,317 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class FunctionUpdateParamsTest { + + @Test + fun create() { + FunctionUpdateParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .functionData( + FunctionUpdateParams.FunctionData.Prompt.builder() + .type(FunctionUpdateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("name") + .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 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 = + FunctionUpdateParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .functionData( + FunctionUpdateParams.FunctionData.Prompt.builder() + .type(FunctionUpdateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("name") + .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 body = params._body() + + assertThat(body.description()).contains("description") + assertThat(body.functionData()) + .contains( + FunctionUpdateParams.FunctionData.ofPrompt( + FunctionUpdateParams.FunctionData.Prompt.builder() + .type(FunctionUpdateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + ) + assertThat(body.name()).contains("name") + assertThat(body.promptData()) + .contains( + 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() + ) + assertThat(body.tags().getOrNull()).containsExactly("string") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + FunctionUpdateParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + } +} 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 new file mode 100755 index 00000000..f050afce --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupCreateParamsTest.kt @@ -0,0 +1,52 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupCreateParamsTest { + + @Test + fun create() { + GroupCreateParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + } + + @Test + fun body() { + val params = + GroupCreateParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("x") + assertThat(body.description()).contains("description") + 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") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = GroupCreateParams.builder().name("x").build() + + val body = params._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 new file mode 100755 index 00000000..3f194aea --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupDeleteParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupDeleteParamsTest { + + @Test + fun create() { + GroupDeleteParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + GroupDeleteParams.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("") + } +} 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/GroupListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupListParamsTest.kt new file mode 100755 index 00000000..17892a31 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupListParamsTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupListParamsTest { + + @Test + fun create() { + GroupListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .groupName("group_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + GroupListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .groupName("group_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("group_name", "group_name") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = GroupListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100755 index 00000000..380f91aa --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupReplaceParamsTest.kt @@ -0,0 +1,52 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupReplaceParamsTest { + + @Test + fun create() { + GroupReplaceParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + } + + @Test + fun body() { + val params = + GroupReplaceParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("x") + assertThat(body.description()).contains("description") + 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") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = GroupReplaceParams.builder().name("x").build() + + val body = params._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 new file mode 100755 index 00000000..88125d11 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupRetrieveParamsTest { + + @Test + fun create() { + GroupRetrieveParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + GroupRetrieveParams.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("") + } +} 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 new file mode 100755 index 00000000..1f75b26f --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupTest.kt @@ -0,0 +1,63 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupTest { + + @Test + fun create() { + 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() + + 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().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + 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 new file mode 100755 index 00000000..f5ea0ee6 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/GroupUpdateParamsTest.kt @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class GroupUpdateParamsTest { + + @Test + fun create() { + GroupUpdateParams.builder() + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addRemoveMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .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 = + GroupUpdateParams.builder() + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addRemoveMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + + 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().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.removeMemberUsers().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + GroupUpdateParams.builder().groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + val body = params._body() + } +} 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 new file mode 100644 index 00000000..77302d95 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertDatasetEventTest.kt @@ -0,0 +1,107 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InsertDatasetEventTest { + + @Test + fun create() { + 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() + + assertThat(insertDatasetEvent.id()).contains("id") + assertThat(insertDatasetEvent._isMerge()).contains(true) + assertThat(insertDatasetEvent._mergePaths().getOrNull()).containsExactly(listOf("string")) + assertThat(insertDatasetEvent._objectDelete()).contains(true) + assertThat(insertDatasetEvent._parentId()).contains("_parent_id") + assertThat(insertDatasetEvent.created()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(insertDatasetEvent._expected()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertDatasetEvent._input()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertDatasetEvent.metadata()) + .contains(InsertDatasetEvent.Metadata.builder().model("model").build()) + assertThat(insertDatasetEvent.origin()) + .contains( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + assertThat(insertDatasetEvent.rootSpanId()).contains("root_span_id") + assertThat(insertDatasetEvent.spanId()).contains("span_id") + 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 new file mode 100755 index 00000000..560e7fd1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertEventsResponseTest.kt @@ -0,0 +1,32 @@ +// 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 InsertEventsResponseTest { + + @Test + fun create() { + val insertEventsResponse = InsertEventsResponse.builder().addRowId("string").build() + + 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 new file mode 100644 index 00000000..c56170f1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertExperimentEventTest.kt @@ -0,0 +1,194 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InsertExperimentEventTest { + + @Test + fun create() { + 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() + + assertThat(insertExperimentEvent.id()).contains("id") + assertThat(insertExperimentEvent._isMerge()).contains(true) + assertThat(insertExperimentEvent._mergePaths().getOrNull()) + .containsExactly(listOf("string")) + assertThat(insertExperimentEvent._objectDelete()).contains(true) + assertThat(insertExperimentEvent._parentId()).contains("_parent_id") + assertThat(insertExperimentEvent.context()) + .contains( + InsertExperimentEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + assertThat(insertExperimentEvent.created()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(insertExperimentEvent._error()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertExperimentEvent._expected()) + .isEqualTo(JsonValue.from(mapOf())) + assertThat(insertExperimentEvent._input()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertExperimentEvent.metadata()) + .contains(InsertExperimentEvent.Metadata.builder().model("model").build()) + assertThat(insertExperimentEvent.metrics()) + .contains( + 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() + ) + assertThat(insertExperimentEvent.origin()) + .contains( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + assertThat(insertExperimentEvent._output()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertExperimentEvent.rootSpanId()).contains("root_span_id") + assertThat(insertExperimentEvent.scores()) + .contains( + InsertExperimentEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(insertExperimentEvent.spanAttributes()) + .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + assertThat(insertExperimentEvent.spanId()).contains("span_id") + 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 new file mode 100644 index 00000000..5320624c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/InsertProjectLogsEventTest.kt @@ -0,0 +1,194 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InsertProjectLogsEventTest { + + @Test + fun create() { + 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() + + assertThat(insertProjectLogsEvent.id()).contains("id") + assertThat(insertProjectLogsEvent._isMerge()).contains(true) + assertThat(insertProjectLogsEvent._mergePaths().getOrNull()) + .containsExactly(listOf("string")) + assertThat(insertProjectLogsEvent._objectDelete()).contains(true) + assertThat(insertProjectLogsEvent._parentId()).contains("_parent_id") + assertThat(insertProjectLogsEvent.context()) + .contains( + InsertProjectLogsEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + assertThat(insertProjectLogsEvent.created()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(insertProjectLogsEvent._error()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertProjectLogsEvent._expected()) + .isEqualTo(JsonValue.from(mapOf())) + assertThat(insertProjectLogsEvent._input()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertProjectLogsEvent.metadata()) + .contains(InsertProjectLogsEvent.Metadata.builder().model("model").build()) + assertThat(insertProjectLogsEvent.metrics()) + .contains( + 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() + ) + assertThat(insertProjectLogsEvent.origin()) + .contains( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + assertThat(insertProjectLogsEvent._output()).isEqualTo(JsonValue.from(mapOf())) + assertThat(insertProjectLogsEvent.rootSpanId()).contains("root_span_id") + assertThat(insertProjectLogsEvent.scores()) + .contains( + InsertProjectLogsEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(insertProjectLogsEvent.spanAttributes()) + .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + assertThat(insertProjectLogsEvent.spanId()).contains("span_id") + 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 new file mode 100755 index 00000000..e236bd38 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/MetricSummaryTest.kt @@ -0,0 +1,53 @@ +// 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 MetricSummaryTest { + + @Test + fun create() { + val metricSummary = + MetricSummary.builder() + .improvements(0L) + .metric(0.0) + .name("name") + .regressions(0L) + .unit("unit") + .diff(0.0) + .build() + + assertThat(metricSummary.improvements()).isEqualTo(0L) + assertThat(metricSummary.metric()).isEqualTo(0.0) + assertThat(metricSummary.name()).isEqualTo("name") + assertThat(metricSummary.regressions()).isEqualTo(0L) + 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 new file mode 100644 index 00000000..80d4a6e0 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ObjectReferenceTest.kt @@ -0,0 +1,50 @@ +// 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 ObjectReferenceTest { + + @Test + fun create() { + val objectReference = + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + + 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 new file mode 100644 index 00000000..9a1a9f83 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OnlineScoreConfigTest.kt @@ -0,0 +1,66 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OnlineScoreConfigTest { + + @Test + fun create() { + 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() + + assertThat(onlineScoreConfig.samplingRate()).isEqualTo(0.0) + assertThat(onlineScoreConfig.scorers()) + .containsExactly( + OnlineScoreConfig.Scorer.ofFunction( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type(OnlineScoreConfig.Scorer.Function.Type.FUNCTION) + .build() + ) + ) + assertThat(onlineScoreConfig.applyToRootSpan()).contains(true) + 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 new file mode 100755 index 00000000..365faa22 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationDeleteParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OrganizationDeleteParamsTest { + + @Test + fun create() { + OrganizationDeleteParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + OrganizationDeleteParams.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("") + } +} 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/OrganizationListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationListParamsTest.kt new file mode 100755 index 00000000..32cdfdf6 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationListParamsTest.kt @@ -0,0 +1,55 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OrganizationListParamsTest { + + @Test + fun create() { + OrganizationListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + OrganizationListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = OrganizationListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100755 index 00000000..bc86325c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationMemberUpdateParamsTest.kt @@ -0,0 +1,91 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OrganizationMemberUpdateParamsTest { + + @Test + fun create() { + OrganizationMemberUpdateParams.builder() + .inviteUsers( + OrganizationMemberUpdateParams.InviteUsers.builder() + .addEmail("string") + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addGroupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .groupName("group_name") + .addGroupName("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .sendInviteEmails(true) + .build() + ) + .orgId("org_id") + .orgName("org_name") + .removeUsers( + OrganizationMemberUpdateParams.RemoveUsers.builder() + .addEmail("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + } + + @Test + fun body() { + val params = + OrganizationMemberUpdateParams.builder() + .inviteUsers( + OrganizationMemberUpdateParams.InviteUsers.builder() + .addEmail("string") + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addGroupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .groupName("group_name") + .addGroupName("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .sendInviteEmails(true) + .build() + ) + .orgId("org_id") + .orgName("org_name") + .removeUsers( + OrganizationMemberUpdateParams.RemoveUsers.builder() + .addEmail("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + + val body = params._body() + + assertThat(body.inviteUsers()) + .contains( + OrganizationMemberUpdateParams.InviteUsers.builder() + .addEmail("string") + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addGroupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .groupName("group_name") + .addGroupName("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .sendInviteEmails(true) + .build() + ) + assertThat(body.orgId()).contains("org_id") + assertThat(body.orgName()).contains("org_name") + assertThat(body.removeUsers()) + .contains( + OrganizationMemberUpdateParams.RemoveUsers.builder() + .addEmail("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = OrganizationMemberUpdateParams.builder().build() + + val body = params._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 new file mode 100755 index 00000000..bb59a8e4 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationRetrieveParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OrganizationRetrieveParamsTest { + + @Test + fun create() { + OrganizationRetrieveParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + OrganizationRetrieveParams.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("") + } +} 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 new file mode 100755 index 00000000..83448fde --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationTest.kt @@ -0,0 +1,58 @@ +// 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 OrganizationTest { + + @Test + fun create() { + 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() + + assertThat(organization.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(organization.name()).isEqualTo("name") + assertThat(organization.apiUrl()).contains("api_url") + assertThat(organization.created()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(organization.isUniversalApi()).contains(true) + 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 new file mode 100755 index 00000000..a66f513e --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/OrganizationUpdateParamsTest.kt @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class OrganizationUpdateParamsTest { + + @Test + fun create() { + OrganizationUpdateParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .apiUrl("api_url") + .isUniversalApi(true) + .name("name") + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .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 = + OrganizationUpdateParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .apiUrl("api_url") + .isUniversalApi(true) + .name("name") + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .build() + + val body = params._body() + + assertThat(body.apiUrl()).contains("api_url") + assertThat(body.isUniversalApi()).contains(true) + assertThat(body.name()).contains("name") + assertThat(body.proxyUrl()).contains("proxy_url") + assertThat(body.realtimeUrl()).contains("realtime_url") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + OrganizationUpdateParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + } +} 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 new file mode 100644 index 00000000..3afc427b --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PatchOrganizationMembersOutputTest.kt @@ -0,0 +1,46 @@ +// 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 PatchOrganizationMembersOutputTest { + + @Test + fun create() { + val patchOrganizationMembersOutput = + PatchOrganizationMembersOutput.builder() + .orgId("org_id") + .status(PatchOrganizationMembersOutput.Status.SUCCESS) + .sendEmailError("send_email_error") + .build() + + 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 old mode 100644 new mode 100755 index cb28d8f0..8751112d --- 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,31 +2,32 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectCreateParamsTest { +internal class ProjectCreateParamsTest { @Test - fun createProjectCreateParams() { - ProjectCreateParams.builder().name("string").orgName("string").build() + fun create() { + ProjectCreateParams.builder().name("x").orgName("org_name").build() } @Test - fun getBody() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") - assertThat(body.orgName()).isEqualTo("string") + fun body() { + val params = ProjectCreateParams.builder().name("x").orgName("org_name").build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("x") + assertThat(body.orgName()).contains("org_name") } @Test - fun getBodyWithoutOptionalFields() { - val params = ProjectCreateParams.builder().name("string").build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") + fun bodyWithoutOptionalFields() { + val params = ProjectCreateParams.builder().name("x").build() + + val body = params._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 old mode 100644 new mode 100755 index caa2ac8b..47a71480 --- 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 @@ -2,25 +2,23 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectDeleteParamsTest { +internal class ProjectDeleteParamsTest { @Test - fun createProjectDeleteParams() { + fun create() { ProjectDeleteParams.builder().projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() } @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/ProjectListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectListParamsTest.kt old mode 100644 new mode 100755 index 3b682bdc..9f6452cd --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectListParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectListParamsTest.kt @@ -2,46 +2,57 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectListParamsTest { +internal class ProjectListParamsTest { @Test - fun createProjectListParams() { + fun create() { ProjectListParams.builder() .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .orgName("string") - .projectName("string") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectName("project_name") .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() } @Test - fun getQueryParams() { + fun queryParams() { val params = ProjectListParams.builder() .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .orgName("string") - .projectName("string") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectName("project_name") .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .build() - val expected = mutableMapOf>() - expected.put("ending_before", listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - expected.put("limit", listOf("123")) - expected.put("org_name", listOf("string")) - expected.put("project_name", listOf("string")) - expected.put("starting_after", listOf("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e")) - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("project_name", "project_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) } @Test - fun getQueryParamsWithoutOptionalFields() { + fun queryParamsWithoutOptionalFields() { val params = ProjectListParams.builder().build() - val expected = mutableMapOf>() - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } 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 old mode 100644 new mode 100755 index 4a264a1f..59f797ac --- 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,90 +3,111 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectLogFeedbackParamsTest { +internal class ProjectLogFeedbackParamsTest { @Test - fun createProjectLogFeedbackParams() { + fun create() { ProjectLogFeedbackParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - ProjectLogFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .expected(JsonValue.from(mapOf())) - .metadata(ProjectLogFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ProjectLogFeedbackParams.Feedback.Scores.builder().build()) - .source(ProjectLogFeedbackParams.Feedback.Source.APP) - .build() - ) + .addFeedback( + 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() ) .build() } @Test - fun getBody() { + fun pathParams() { val params = ProjectLogFeedbackParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - ProjectLogFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .expected(JsonValue.from(mapOf())) - .metadata(ProjectLogFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ProjectLogFeedbackParams.Feedback.Scores.builder().build()) - .source(ProjectLogFeedbackParams.Feedback.Source.APP) - .build() - ) - ) + .addFeedback(FeedbackProjectLogsItem.builder().id("id").build()) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.feedback()) - .isEqualTo( - listOf( - ProjectLogFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .expected(JsonValue.from(mapOf())) - .metadata(ProjectLogFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ProjectLogFeedbackParams.Feedback.Scores.builder().build()) - .source(ProjectLogFeedbackParams.Feedback.Source.APP) - .build() - ) - ) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = ProjectLogFeedbackParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback(listOf(ProjectLogFeedbackParams.Feedback.builder().id("string").build())) + .addFeedback( + 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() + ) .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + assertThat(body.feedback()) - .isEqualTo(listOf(ProjectLogFeedbackParams.Feedback.builder().id("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() + ) } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = ProjectLogFeedbackParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback(listOf(ProjectLogFeedbackParams.Feedback.builder().id("string").build())) + .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("") + + val body = params._body() + + assertThat(body.feedback()) + .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 old mode 100644 new mode 100755 index 8c298569..545e215e --- 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 @@ -2,61 +2,68 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* +import com.braintrustdata.api.core.http.QueryParams import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectLogFetchParamsTest { +internal class ProjectLogFetchParamsTest { @Test - fun createProjectLogFetchParams() { + fun create() { ProjectLogFetchParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() } @Test - fun getQueryParams() { + fun pathParams() { val params = ProjectLogFetchParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) .build() - val expected = mutableMapOf>() - expected.put("limit", listOf("123")) - expected.put("max_root_span_id", listOf("string")) - expected.put("max_xact_id", listOf("123")) - expected.put("version", listOf("123")) - assertThat(params.getQueryParams()).isEqualTo(expected) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getQueryParamsWithoutOptionalFields() { + fun queryParams() { val params = ProjectLogFetchParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() - val expected = mutableMapOf>() - assertThat(params.getQueryParams()).isEqualTo(expected) + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("limit", "0") + .put("max_root_span_id", "max_root_span_id") + .put("max_xact_id", "max_xact_id") + .put("version", "version") + .build() + ) } @Test - fun getPathParam() { + fun queryParamsWithoutOptionalFields() { 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("") + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) } } 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 old mode 100644 new mode 100755 index 14f48340..e6c1f8ff --- 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,90 +2,63 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectLogFetchPostParamsTest { +internal class ProjectLogFetchPostParamsTest { @Test - fun createProjectLogFetchPostParams() { + fun create() { ProjectLogFetchPostParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - ProjectLogFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ProjectLogFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() } @Test - fun getBody() { + fun pathParams() { val params = ProjectLogFetchPostParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - ProjectLogFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ProjectLogFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.filters()) - .isEqualTo( - listOf( - ProjectLogFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ProjectLogFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - assertThat(body.limit()).isEqualTo(123L) - assertThat(body.maxRootSpanId()).isEqualTo("string") - assertThat(body.maxXactId()).isEqualTo(123L) - assertThat(body.version()).isEqualTo(123L) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = ProjectLogFetchPostParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + + assertThat(body.cursor()).contains("cursor") + assertThat(body.limit()).contains(0L) + assertThat(body.maxRootSpanId()).contains("max_root_span_id") + assertThat(body.maxXactId()).contains("max_xact_id") + assertThat(body.version()).contains("version") } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { 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("") + + val body = params._body() } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostResponseTest.kt deleted file mode 100644 index eb47bb61..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchPostResponseTest.kt +++ /dev/null @@ -1,96 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.core.JsonValue -import java.time.OffsetDateTime -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ProjectLogFetchPostResponseTest { - - @Test - fun createProjectLogFetchPostResponse() { - val projectLogFetchPostResponse = - ProjectLogFetchPostResponse.builder() - .events( - listOf( - ProjectLogFetchPostResponse.Event.builder() - .id("string") - ._xactId(123L) - .logId(ProjectLogFetchPostResponse.Event.LogId.G) - .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ProjectLogFetchPostResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ProjectLogFetchPostResponse.Event.Metadata.builder().build()) - .metrics( - ProjectLogFetchPostResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ProjectLogFetchPostResponse.Event.Scores.builder().build()) - .spanAttributes( - ProjectLogFetchPostResponse.Event.SpanAttributes.builder() - .name("string") - .type(ProjectLogFetchPostResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - ) - .build() - assertThat(projectLogFetchPostResponse).isNotNull - assertThat(projectLogFetchPostResponse.events()) - .containsExactly( - ProjectLogFetchPostResponse.Event.builder() - .id("string") - ._xactId(123L) - .logId(ProjectLogFetchPostResponse.Event.LogId.G) - .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ProjectLogFetchPostResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ProjectLogFetchPostResponse.Event.Metadata.builder().build()) - .metrics( - ProjectLogFetchPostResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ProjectLogFetchPostResponse.Event.Scores.builder().build()) - .spanAttributes( - ProjectLogFetchPostResponse.Event.SpanAttributes.builder() - .name("string") - .type(ProjectLogFetchPostResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - } -} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchResponseTest.kt deleted file mode 100644 index 8a0c8cd4..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogFetchResponseTest.kt +++ /dev/null @@ -1,96 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.core.JsonValue -import java.time.OffsetDateTime -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ProjectLogFetchResponseTest { - - @Test - fun createProjectLogFetchResponse() { - val projectLogFetchResponse = - ProjectLogFetchResponse.builder() - .events( - listOf( - ProjectLogFetchResponse.Event.builder() - .id("string") - ._xactId(123L) - .logId(ProjectLogFetchResponse.Event.LogId.G) - .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ProjectLogFetchResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ProjectLogFetchResponse.Event.Metadata.builder().build()) - .metrics( - ProjectLogFetchResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ProjectLogFetchResponse.Event.Scores.builder().build()) - .spanAttributes( - ProjectLogFetchResponse.Event.SpanAttributes.builder() - .name("string") - .type(ProjectLogFetchResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - ) - .build() - assertThat(projectLogFetchResponse).isNotNull - assertThat(projectLogFetchResponse.events()) - .containsExactly( - ProjectLogFetchResponse.Event.builder() - .id("string") - ._xactId(123L) - .logId(ProjectLogFetchResponse.Event.LogId.G) - .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .rootSpanId("string") - .spanId("string") - .context( - ProjectLogFetchResponse.Event.Context.builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata(ProjectLogFetchResponse.Event.Metadata.builder().build()) - .metrics( - ProjectLogFetchResponse.Event.Metrics.builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores(ProjectLogFetchResponse.Event.Scores.builder().build()) - .spanAttributes( - ProjectLogFetchResponse.Event.SpanAttributes.builder() - .name("string") - .type(ProjectLogFetchResponse.Event.SpanAttributes.Type.LLM) - .build() - ) - .spanParents(listOf("string")) - .build() - ) - } -} 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 old mode 100644 new mode 100755 index 38043534..1cf5e777 --- 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 @@ -3,238 +3,219 @@ package com.braintrustdata.api.models import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* +import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectLogInsertParamsTest { +internal class ProjectLogInsertParamsTest { @Test - fun createProjectLogInsertParams() { + fun create() { ProjectLogInsertParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ProjectLogInsertParams.Event.ofInsertProjectLogsEventReplace( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Metadata - .builder() - .build() - ) - .metrics( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Scores - .builder() - .build() - ) - .spanAttributes( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) + .addEvent( + 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() ) .build() } @Test - fun getBody() { + fun pathParams() { val params = ProjectLogInsertParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ProjectLogInsertParams.Event.ofInsertProjectLogsEventReplace( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Metadata - .builder() - .build() - ) - .metrics( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Scores - .builder() - .build() - ) - .spanAttributes( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ProjectLogInsertParams.Event - .InsertProjectLogsEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) - .build() - ) - ) - ) + .addEvent(InsertProjectLogsEvent.builder().build()) .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.events()) - .isEqualTo( - listOf( - ProjectLogInsertParams.Event.ofInsertProjectLogsEventReplace( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Metadata - .builder() - .build() - ) - .metrics( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.Scores - .builder() - .build() - ) - .spanAttributes( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) - .build() - ) - ) - ) + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") } @Test - fun getBodyWithoutOptionalFields() { + fun body() { val params = ProjectLogInsertParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ProjectLogInsertParams.Event.ofInsertProjectLogsEventReplace( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.builder() + .addEvent( + 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() ) .build() - val body = params.getBody() - assertThat(body).isNotNull + + val body = params._body() + assertThat(body.events()) - .isEqualTo( - listOf( - ProjectLogInsertParams.Event.ofInsertProjectLogsEventReplace( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.builder().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() ) } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { val params = ProjectLogInsertParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ProjectLogInsertParams.Event.ofInsertProjectLogsEventReplace( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.builder() - .build() - ) - ) - ) + .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("") + + val body = params._body() + + assertThat(body.events()).containsExactly(InsertProjectLogsEvent.builder().build()) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogInsertResponseTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogInsertResponseTest.kt deleted file mode 100644 index c505360d..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogInsertResponseTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ProjectLogInsertResponseTest { - - @Test - fun createProjectLogInsertResponse() { - val projectLogInsertResponse = - ProjectLogInsertResponse.builder().rowIds(listOf("string")).build() - assertThat(projectLogInsertResponse).isNotNull - assertThat(projectLogInsertResponse.rowIds()).containsExactly("string") - } -} 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 new file mode 100755 index 00000000..e91f1d39 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectLogsEventTest.kt @@ -0,0 +1,195 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectLogsEventTest { + + @Test + fun create() { + 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() + + assertThat(projectLogsEvent.id()).isEqualTo("id") + assertThat(projectLogsEvent._xactId()).isEqualTo("_xact_id") + assertThat(projectLogsEvent.created()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(projectLogsEvent.logId()).isEqualTo(ProjectLogsEvent.LogId.G) + assertThat(projectLogsEvent.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectLogsEvent.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectLogsEvent.rootSpanId()).isEqualTo("root_span_id") + assertThat(projectLogsEvent.spanId()).isEqualTo("span_id") + assertThat(projectLogsEvent.context()) + .contains( + ProjectLogsEvent.Context.builder() + .callerFilename("caller_filename") + .callerFunctionname("caller_functionname") + .callerLineno(0L) + .build() + ) + assertThat(projectLogsEvent._error()).isEqualTo(JsonValue.from(mapOf())) + assertThat(projectLogsEvent._expected()).isEqualTo(JsonValue.from(mapOf())) + assertThat(projectLogsEvent._input()).isEqualTo(JsonValue.from(mapOf())) + assertThat(projectLogsEvent.isRoot()).contains(true) + assertThat(projectLogsEvent.metadata()) + .contains(ProjectLogsEvent.Metadata.builder().model("model").build()) + assertThat(projectLogsEvent.metrics()) + .contains( + 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() + ) + assertThat(projectLogsEvent.origin()) + .contains( + ObjectReference.builder() + .id("id") + ._xactId("_xact_id") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(ObjectReference.ObjectType.EXPERIMENT) + .created("created") + .build() + ) + assertThat(projectLogsEvent._output()).isEqualTo(JsonValue.from(mapOf())) + assertThat(projectLogsEvent.scores()) + .contains( + ProjectLogsEvent.Scores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(projectLogsEvent.spanAttributes()) + .contains(SpanAttributes.builder().name("name").type(SpanType.LLM).build()) + 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/ProjectReplaceParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectReplaceParamsTest.kt deleted file mode 100644 index c74489a0..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectReplaceParamsTest.kt +++ /dev/null @@ -1,32 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.models - -import com.braintrustdata.api.models.* -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ProjectReplaceParamsTest { - - @Test - fun createProjectReplaceParams() { - ProjectReplaceParams.builder().name("string").orgName("string").build() - } - - @Test - fun getBody() { - val params = ProjectReplaceParams.builder().name("string").orgName("string").build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") - assertThat(body.orgName()).isEqualTo("string") - } - - @Test - fun getBodyWithoutOptionalFields() { - val params = ProjectReplaceParams.builder().name("string").build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") - } -} 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 old mode 100644 new mode 100755 index 231a1864..e83306b3 --- 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 @@ -2,27 +2,25 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectRetrieveParamsTest { +internal class ProjectRetrieveParamsTest { @Test - fun createProjectRetrieveParams() { + fun create() { ProjectRetrieveParams.builder().projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() } @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 new file mode 100755 index 00000000..3e4d1ce0 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCategoryTest.kt @@ -0,0 +1,33 @@ +// 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 ProjectScoreCategoryTest { + + @Test + fun create() { + val projectScoreCategory = ProjectScoreCategory.builder().name("name").value(0.0).build() + + 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 new file mode 100644 index 00000000..613487b8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreConfigTest.kt @@ -0,0 +1,81 @@ +// 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 ProjectScoreConfigTest { + + @Test + fun create() { + 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() + + assertThat(projectScoreConfig.destination()).contains("destination") + assertThat(projectScoreConfig.multiSelect()).contains(true) + assertThat(projectScoreConfig.online()) + .contains( + OnlineScoreConfig.builder() + .samplingRate(0.0) + .addScorer( + OnlineScoreConfig.Scorer.Function.builder() + .id("id") + .type(OnlineScoreConfig.Scorer.Function.Type.FUNCTION) + .build() + ) + .applyToRootSpan(true) + .addApplyToSpanName("string") + .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 new file mode 100755 index 00000000..a192a789 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreCreateParamsTest.kt @@ -0,0 +1,123 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectScoreCreateParamsTest { + + @Test + fun create() { + ProjectScoreCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + } + + @Test + fun body() { + val params = + ProjectScoreCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.scoreType()).isEqualTo(ProjectScoreType.SLIDER) + assertThat(body.categories()) + .contains( + ProjectScoreCreateParams.Categories.ofCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + ) + assertThat(body.config()) + .contains( + 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() + ) + assertThat(body.description()).contains("description") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ProjectScoreCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .build() + + val body = params._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 new file mode 100755 index 00000000..c90b6173 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreDeleteParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectScoreDeleteParamsTest { + + @Test + fun create() { + ProjectScoreDeleteParams.builder() + .projectScoreId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + ProjectScoreDeleteParams.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("") + } +} 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/ProjectScoreListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreListParamsTest.kt new file mode 100755 index 00000000..e1ff4653 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreListParamsTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectScoreListParamsTest { + + @Test + fun create() { + ProjectScoreListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .projectScoreName("project_score_name") + .scoreType(ProjectScoreType.SLIDER) + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + ProjectScoreListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .projectScoreName("project_score_name") + .scoreType(ProjectScoreType.SLIDER) + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("project_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("project_name", "project_name") + .put("project_score_name", "project_score_name") + .put("score_type", "slider") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = ProjectScoreListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100755 index 00000000..b569d015 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreReplaceParamsTest.kt @@ -0,0 +1,123 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectScoreReplaceParamsTest { + + @Test + fun create() { + ProjectScoreReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + } + + @Test + fun body() { + val params = + ProjectScoreReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.scoreType()).isEqualTo(ProjectScoreType.SLIDER) + assertThat(body.categories()) + .contains( + ProjectScoreReplaceParams.Categories.ofCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + ) + assertThat(body.config()) + .contains( + 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() + ) + assertThat(body.description()).contains("description") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ProjectScoreReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .build() + + val body = params._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 new file mode 100755 index 00000000..8bfde8f2 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreRetrieveParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectScoreRetrieveParamsTest { + + @Test + fun create() { + ProjectScoreRetrieveParams.builder() + .projectScoreId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + ProjectScoreRetrieveParams.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("") + } +} 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 new file mode 100755 index 00000000..3fc8a833 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreTest.kt @@ -0,0 +1,131 @@ +// 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 ProjectScoreTest { + + @Test + fun create() { + 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() + + assertThat(projectScore.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectScore.name()).isEqualTo("name") + assertThat(projectScore.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectScore.scoreType()).isEqualTo(ProjectScoreType.SLIDER) + assertThat(projectScore.userId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectScore.categories()) + .contains( + ProjectScore.Categories.ofCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + ) + assertThat(projectScore.config()) + .contains( + 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() + ) + assertThat(projectScore.created()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + 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 new file mode 100755 index 00000000..1feddf2e --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectScoreUpdateParamsTest.kt @@ -0,0 +1,128 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectScoreUpdateParamsTest { + + @Test + fun create() { + ProjectScoreUpdateParams.builder() + .projectScoreId("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() + ) + .description("description") + .name("name") + .scoreType(ProjectScoreType.SLIDER) + .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 = + ProjectScoreUpdateParams.builder() + .projectScoreId("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() + ) + .description("description") + .name("name") + .scoreType(ProjectScoreType.SLIDER) + .build() + + val body = params._body() + + assertThat(body.categories()) + .contains( + ProjectScoreUpdateParams.Categories.ofCategorical( + listOf(ProjectScoreCategory.builder().name("name").value(0.0).build()) + ) + ) + assertThat(body.config()) + .contains( + 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() + ) + assertThat(body.description()).contains("description") + assertThat(body.name()).contains("name") + assertThat(body.scoreType()).contains(ProjectScoreType.SLIDER) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ProjectScoreUpdateParams.builder() + .projectScoreId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + } +} 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 new file mode 100644 index 00000000..3d5015d9 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectSettingsTest.kt @@ -0,0 +1,68 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectSettingsTest { + + @Test + fun create() { + 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() + + assertThat(projectSettings.baselineExperimentId()) + .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectSettings.comparisonKey()).contains("comparison_key") + assertThat(projectSettings.spanFieldOrder().getOrNull()) + .containsExactly( + ProjectSettings.SpanFieldOrder.builder() + .columnId("column_id") + .objectType("object_type") + .position("position") + .layout(ProjectSettings.SpanFieldOrder.Layout.FULL) + .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 new file mode 100755 index 00000000..c738ab63 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagCreateParamsTest.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectTagCreateParamsTest { + + @Test + fun create() { + ProjectTagCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + } + + @Test + fun body() { + val params = + ProjectTagCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.color()).contains("color") + assertThat(body.description()).contains("description") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ProjectTagCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._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 new file mode 100755 index 00000000..16087334 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagDeleteParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectTagDeleteParamsTest { + + @Test + fun create() { + ProjectTagDeleteParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + ProjectTagDeleteParams.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("") + } +} 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/ProjectTagListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagListParamsTest.kt new file mode 100755 index 00000000..5b43e3ad --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagListParamsTest.kt @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectTagListParamsTest { + + @Test + fun create() { + ProjectTagListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .projectTagName("project_tag_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + ProjectTagListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .projectTagName("project_tag_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("project_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("project_name", "project_name") + .put("project_tag_name", "project_tag_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = ProjectTagListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100755 index 00000000..39eae201 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagReplaceParamsTest.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectTagReplaceParamsTest { + + @Test + fun create() { + ProjectTagReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + } + + @Test + fun body() { + val params = + ProjectTagReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.color()).contains("color") + assertThat(body.description()).contains("description") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ProjectTagReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._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 new file mode 100755 index 00000000..f7bbf553 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagRetrieveParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectTagRetrieveParamsTest { + + @Test + fun create() { + ProjectTagRetrieveParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + ProjectTagRetrieveParams.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("") + } +} 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 new file mode 100755 index 00000000..efeaf87b --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagTest.kt @@ -0,0 +1,57 @@ +// 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 ProjectTagTest { + + @Test + fun create() { + 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() + + assertThat(projectTag.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectTag.name()).isEqualTo("name") + assertThat(projectTag.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectTag.userId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(projectTag.color()).contains("color") + 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 new file mode 100755 index 00000000..beb3b668 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ProjectTagUpdateParamsTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProjectTagUpdateParamsTest { + + @Test + fun create() { + ProjectTagUpdateParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .name("name") + .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 = + ProjectTagUpdateParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .name("name") + .build() + + val body = params._body() + + assertThat(body.color()).contains("color") + assertThat(body.description()).contains("description") + assertThat(body.name()).contains("name") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ProjectTagUpdateParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + } +} 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 9288581a..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,29 +2,93 @@ 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 -class ProjectTest { +internal class ProjectTest { @Test - fun createProject() { + fun create() { val project = Project.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") + .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() - assertThat(project).isNotNull + assertThat(project.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(project.name()).isEqualTo("string") + assertThat(project.name()).isEqualTo("name") assertThat(project.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(project.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(project.deletedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(project.settings()) + .contains( + 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() + ) 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 old mode 100644 new mode 100755 index cadd5a89..99b062a2 --- 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,48 +2,90 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class ProjectUpdateParamsTest { +internal class ProjectUpdateParamsTest { @Test - fun createProjectUpdateParams() { + fun create() { ProjectUpdateParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") + .name("name") + .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() + ) .build() } @Test - fun getBody() { + fun pathParams() { val params = - ProjectUpdateParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") - .build() - val body = params.getBody() - assertThat(body).isNotNull - assertThat(body.name()).isEqualTo("string") + 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 getBodyWithoutOptionalFields() { + fun body() { val params = - ProjectUpdateParams.builder().projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() - val body = params.getBody() - assertThat(body).isNotNull + ProjectUpdateParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .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() + ) + .build() + + val body = params._body() + + assertThat(body.name()).contains("name") + assertThat(body.settings()) + .contains( + 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() + ) } @Test - fun getPathParam() { + fun bodyWithoutOptionalFields() { 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("") + + val body = params._body() } } 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 new file mode 100755 index 00000000..8013fd96 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptCreateParamsTest.kt @@ -0,0 +1,300 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptCreateParamsTest { + + @Test + fun create() { + PromptCreateParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptCreateParams.FunctionType.LLM) + .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 body() { + val params = + PromptCreateParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptCreateParams.FunctionType.LLM) + .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 body = params._body() + + assertThat(body.name()).isEqualTo("x") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.slug()).isEqualTo("x") + assertThat(body.description()).contains("description") + assertThat(body.functionType()).contains(PromptCreateParams.FunctionType.LLM) + assertThat(body.promptData()) + .contains( + 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() + ) + assertThat(body.tags().getOrNull()).containsExactly("string") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + PromptCreateParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .build() + + val body = params._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 new file mode 100755 index 00000000..97966fac --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDataTest.kt @@ -0,0 +1,258 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptDataTest { + + @Test + fun create() { + 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() + + assertThat(promptData.options()) + .contains( + 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() + ) + assertThat(promptData.origin()) + .contains( + PromptData.Origin.builder() + .projectId("project_id") + .promptId("prompt_id") + .promptVersion("prompt_version") + .build() + ) + assertThat(promptData.parser()) + .contains( + PromptData.Parser.builder() + .choiceScores( + PromptData.Parser.ChoiceScores.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .type(PromptData.Parser.Type.LLM_CLASSIFIER) + .useCot(true) + .build() + ) + assertThat(promptData.prompt()) + .contains( + PromptData.Prompt.ofCompletion( + PromptData.Prompt.Completion.builder() + .content("content") + .type(PromptData.Prompt.Completion.Type.COMPLETION) + .build() + ) + ) + assertThat(promptData.toolFunctions().getOrNull()) + .containsExactly( + PromptData.ToolFunction.ofFunction( + PromptData.ToolFunction.Function.builder() + .id("id") + .type(PromptData.ToolFunction.Function.Type.FUNCTION) + .build() + ) + ) + } + + @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 new file mode 100755 index 00000000..45b20f34 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptDeleteParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptDeleteParamsTest { + + @Test + fun create() { + PromptDeleteParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + PromptDeleteParams.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("") + } +} 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/PromptListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptListParamsTest.kt new file mode 100755 index 00000000..ef6a5e48 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptListParamsTest.kt @@ -0,0 +1,70 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptListParamsTest { + + @Test + fun create() { + PromptListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .promptName("prompt_name") + .slug("slug") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .version("version") + .build() + } + + @Test + fun queryParams() { + val params = + PromptListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .projectName("project_name") + .promptName("prompt_name") + .slug("slug") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .version("version") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("project_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("project_name", "project_name") + .put("prompt_name", "prompt_name") + .put("slug", "slug") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("version", "version") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = PromptListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100644 index 00000000..46cf6e9a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptOptionsTest.kt @@ -0,0 +1,134 @@ +// 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 PromptOptionsTest { + + @Test + fun create() { + 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() + + assertThat(promptOptions.model()).contains("model") + assertThat(promptOptions.params()) + .contains( + PromptOptions.Params.ofOpenAIModel( + 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() + ) + ) + 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 new file mode 100755 index 00000000..2b627b25 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptReplaceParamsTest.kt @@ -0,0 +1,300 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptReplaceParamsTest { + + @Test + fun create() { + PromptReplaceParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptReplaceParams.FunctionType.LLM) + .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 body() { + val params = + PromptReplaceParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptReplaceParams.FunctionType.LLM) + .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 body = params._body() + + assertThat(body.name()).isEqualTo("x") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.slug()).isEqualTo("x") + assertThat(body.description()).contains("description") + assertThat(body.functionType()).contains(PromptReplaceParams.FunctionType.LLM) + assertThat(body.promptData()) + .contains( + 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() + ) + assertThat(body.tags().getOrNull()).containsExactly("string") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + PromptReplaceParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .build() + + val body = params._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 new file mode 100755 index 00000000..97f8cb26 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptRetrieveParamsTest { + + @Test + fun create() { + PromptRetrieveParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + PromptRetrieveParams.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("") + } +} 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 new file mode 100755 index 00000000..0928b7d9 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptTest.kt @@ -0,0 +1,324 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptTest { + + @Test + fun create() { + 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() + + assertThat(prompt.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(prompt._xactId()).isEqualTo("_xact_id") + assertThat(prompt.logId()).isEqualTo(Prompt.LogId.P) + assertThat(prompt.name()).isEqualTo("name") + assertThat(prompt.orgId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(prompt.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(prompt.slug()).isEqualTo("slug") + assertThat(prompt.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(prompt.description()).contains("description") + assertThat(prompt.functionType()).contains(Prompt.FunctionType.LLM) + assertThat(prompt.metadata()) + .contains( + Prompt.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(prompt.promptData()) + .contains( + 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() + ) + 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 new file mode 100755 index 00000000..43dfac44 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/PromptUpdateParamsTest.kt @@ -0,0 +1,298 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PromptUpdateParamsTest { + + @Test + fun create() { + PromptUpdateParams.builder() + .promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .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() + ) + .slug("slug") + .addTag("string") + .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 = + PromptUpdateParams.builder() + .promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .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() + ) + .slug("slug") + .addTag("string") + .build() + + val body = params._body() + + assertThat(body.description()).contains("description") + assertThat(body.name()).contains("name") + assertThat(body.promptData()) + .contains( + 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() + ) + assertThat(body.slug()).contains("slug") + assertThat(body.tags().getOrNull()).containsExactly("string") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + PromptUpdateParams.builder().promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + val body = params._body() + } +} 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 new file mode 100755 index 00000000..8c8ccdc8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RepoInfoTest.kt @@ -0,0 +1,62 @@ +// 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 RepoInfoTest { + + @Test + fun create() { + 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() + + assertThat(repoInfo.authorEmail()).contains("author_email") + assertThat(repoInfo.authorName()).contains("author_name") + assertThat(repoInfo.branch()).contains("branch") + assertThat(repoInfo.commit()).contains("commit") + assertThat(repoInfo.commitMessage()).contains("commit_message") + assertThat(repoInfo.commitTime()).contains("commit_time") + assertThat(repoInfo.dirty()).contains(true) + 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 new file mode 100755 index 00000000..74b23cad --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleCreateParamsTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleCreateParamsTest { + + @Test + fun create() { + RoleCreateParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleCreateParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + } + + @Test + fun body() { + val params = + RoleCreateParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleCreateParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("x") + assertThat(body.description()).contains("description") + assertThat(body.memberPermissions().getOrNull()) + .containsExactly( + RoleCreateParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + assertThat(body.memberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.orgName()).contains("org_name") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = RoleCreateParams.builder().name("x").build() + + val body = params._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 new file mode 100755 index 00000000..8a61140e --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleDeleteParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleDeleteParamsTest { + + @Test + fun create() { + RoleDeleteParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + RoleDeleteParams.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("") + } +} 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/RoleListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleListParamsTest.kt new file mode 100755 index 00000000..c023fec1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleListParamsTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleListParamsTest { + + @Test + fun create() { + RoleListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .roleName("role_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + RoleListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .roleName("role_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("role_name", "role_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = RoleListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100755 index 00000000..5b3ce5ce --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleReplaceParamsTest.kt @@ -0,0 +1,67 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleReplaceParamsTest { + + @Test + fun create() { + RoleReplaceParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleReplaceParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + } + + @Test + fun body() { + val params = + RoleReplaceParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleReplaceParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("x") + assertThat(body.description()).contains("description") + assertThat(body.memberPermissions().getOrNull()) + .containsExactly( + RoleReplaceParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + assertThat(body.memberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.orgName()).contains("org_name") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = RoleReplaceParams.builder().name("x").build() + + val body = params._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 new file mode 100755 index 00000000..27d753fa --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleRetrieveParamsTest { + + @Test + fun create() { + RoleRetrieveParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + RoleRetrieveParams.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("") + } +} 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 new file mode 100755 index 00000000..d057dcc7 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleTest.kt @@ -0,0 +1,78 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleTest { + + @Test + fun create() { + 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() + + 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().getOrNull()) + .containsExactly( + Role.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + 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 new file mode 100755 index 00000000..bfa8c9bf --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/RoleUpdateParamsTest.kt @@ -0,0 +1,98 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class RoleUpdateParamsTest { + + @Test + fun create() { + RoleUpdateParams.builder() + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberPermission( + RoleUpdateParams.AddMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addAddMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberPermission( + RoleUpdateParams.RemoveMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addRemoveMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .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 = + RoleUpdateParams.builder() + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberPermission( + RoleUpdateParams.AddMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addAddMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberPermission( + RoleUpdateParams.RemoveMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addRemoveMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + + assertThat(body.addMemberPermissions().getOrNull()) + .containsExactly( + RoleUpdateParams.AddMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + assertThat(body.addMemberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.description()).contains("description") + assertThat(body.name()).contains("x") + assertThat(body.removeMemberPermissions().getOrNull()) + .containsExactly( + RoleUpdateParams.RemoveMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + assertThat(body.removeMemberRoles().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + RoleUpdateParams.builder().roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + val body = params._body() + } +} 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 new file mode 100755 index 00000000..163e2608 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ScoreSummaryTest.kt @@ -0,0 +1,50 @@ +// 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 ScoreSummaryTest { + + @Test + fun create() { + val scoreSummary = + ScoreSummary.builder() + .improvements(0L) + .name("name") + .regressions(0L) + .score(0.0) + .diff(-1.0) + .build() + + 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 new file mode 100644 index 00000000..30df044a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanAttributesTest.kt @@ -0,0 +1,33 @@ +// 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 SpanAttributesTest { + + @Test + fun create() { + val spanAttributes = SpanAttributes.builder().name("name").type(SpanType.LLM).build() + + 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 new file mode 100644 index 00000000..3c05ea3d --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIFrameTest.kt @@ -0,0 +1,64 @@ +// 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 SpanIFrameTest { + + @Test + fun create() { + 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() + + assertThat(spanIFrame.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(spanIFrame.name()).isEqualTo("name") + assertThat(spanIFrame.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(spanIFrame.url()).isEqualTo("url") + assertThat(spanIFrame.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(spanIFrame.deletedAt()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(spanIFrame.description()).contains("description") + 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 new file mode 100644 index 00000000..b95ed798 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeCreateParamsTest.kt @@ -0,0 +1,56 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SpanIframeCreateParamsTest { + + @Test + fun create() { + SpanIframeCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + } + + @Test + fun body() { + val params = + SpanIframeCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.url()).isEqualTo("url") + assertThat(body.description()).contains("description") + assertThat(body.postMessage()).contains(true) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + SpanIframeCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .build() + + val body = params._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 new file mode 100644 index 00000000..09ce2983 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeDeleteParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SpanIframeDeleteParamsTest { + + @Test + fun create() { + SpanIframeDeleteParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + SpanIframeDeleteParams.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("") + } +} 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/SpanIframeListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeListParamsTest.kt new file mode 100644 index 00000000..47aed4d6 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeListParamsTest.kt @@ -0,0 +1,58 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SpanIframeListParamsTest { + + @Test + fun create() { + SpanIframeListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .spanIframeName("span_iframe_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + SpanIframeListParams.builder() + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .spanIframeName("span_iframe_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("span_iframe_name", "span_iframe_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = SpanIframeListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100644 index 00000000..959f5fa4 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeReplaceParamsTest.kt @@ -0,0 +1,56 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SpanIframeReplaceParamsTest { + + @Test + fun create() { + SpanIframeReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + } + + @Test + fun body() { + val params = + SpanIframeReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.projectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.url()).isEqualTo("url") + assertThat(body.description()).contains("description") + assertThat(body.postMessage()).contains(true) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + SpanIframeReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .build() + + val body = params._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 new file mode 100644 index 00000000..885d2d46 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeRetrieveParamsTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SpanIframeRetrieveParamsTest { + + @Test + fun create() { + SpanIframeRetrieveParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun pathParams() { + val params = + SpanIframeRetrieveParams.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("") + } +} 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 new file mode 100644 index 00000000..4a255d60 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SpanIframeUpdateParamsTest.kt @@ -0,0 +1,61 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SpanIframeUpdateParamsTest { + + @Test + fun create() { + SpanIframeUpdateParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .postMessage(true) + .url("url") + .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 = + SpanIframeUpdateParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .postMessage(true) + .url("url") + .build() + + val body = params._body() + + assertThat(body.description()).contains("description") + assertThat(body.name()).contains("name") + assertThat(body.postMessage()).contains(true) + assertThat(body.url()).contains("url") + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + SpanIframeUpdateParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val body = params._body() + } +} 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 new file mode 100755 index 00000000..58021961 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeDatasetResponseTest.kt @@ -0,0 +1,51 @@ +// 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 SummarizeDatasetResponseTest { + + @Test + fun create() { + 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() + + assertThat(summarizeDatasetResponse.datasetName()).isEqualTo("dataset_name") + assertThat(summarizeDatasetResponse.datasetUrl()).isEqualTo("https://example.com") + assertThat(summarizeDatasetResponse.projectName()).isEqualTo("project_name") + assertThat(summarizeDatasetResponse.projectUrl()).isEqualTo("https://example.com") + 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 new file mode 100755 index 00000000..36badb29 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/SummarizeExperimentResponseTest.kt @@ -0,0 +1,153 @@ +// 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 org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class SummarizeExperimentResponseTest { + + @Test + fun create() { + 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() + + assertThat(summarizeExperimentResponse.experimentName()).isEqualTo("experiment_name") + assertThat(summarizeExperimentResponse.experimentUrl()).isEqualTo("https://example.com") + assertThat(summarizeExperimentResponse.projectName()).isEqualTo("project_name") + assertThat(summarizeExperimentResponse.projectUrl()).isEqualTo("https://example.com") + assertThat(summarizeExperimentResponse.comparisonExperimentName()) + .contains("comparison_experiment_name") + assertThat(summarizeExperimentResponse.metrics()) + .contains( + 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() + ) + assertThat(summarizeExperimentResponse.scores()) + .contains( + SummarizeExperimentResponse.Scores.builder() + .putAdditionalProperty( + "foo", + JsonValue.from( + mapOf( + "improvements" to 0, + "name" to "name", + "regressions" to 0, + "score" to 0, + "diff" to -1, + ) + ), + ) + .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/TopLevelHelloWorldParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParamsTest.kt old mode 100644 new mode 100755 index b059ced3..fa29626f --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParamsTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParamsTest.kt @@ -2,13 +2,12 @@ package com.braintrustdata.api.models -import com.braintrustdata.api.models.* import org.junit.jupiter.api.Test -class TopLevelHelloWorldParamsTest { +internal class TopLevelHelloWorldParamsTest { @Test - fun createTopLevelHelloWorldParams() { + fun create() { TopLevelHelloWorldParams.builder().build() } } 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/UserListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserListParamsTest.kt new file mode 100755 index 00000000..59ea68cd --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserListParamsTest.kt @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UserListParamsTest { + + @Test + fun create() { + UserListParams.builder() + .email("string") + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .familyName("string") + .givenName("string") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + } + + @Test + fun queryParams() { + val params = + UserListParams.builder() + .email("string") + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .familyName("string") + .givenName("string") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .orgName("org_name") + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("email", "string") + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("family_name", "string") + .put("given_name", "string") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("org_name", "org_name") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = UserListParams.builder().build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} 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 new file mode 100755 index 00000000..f684fdad --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class UserRetrieveParamsTest { + + @Test + fun create() { + UserRetrieveParams.builder().userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + } + + @Test + fun pathParams() { + val params = + UserRetrieveParams.builder().userId("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("") + } +} 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 new file mode 100755 index 00000000..49bab46a --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/UserTest.kt @@ -0,0 +1,51 @@ +// 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 UserTest { + + @Test + fun create() { + 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() + + 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")) + assertThat(user.email()).contains("email") + 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 new file mode 100755 index 00000000..e86fd560 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewCreateParamsTest.kt @@ -0,0 +1,155 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewCreateParamsTest { + + @Test + fun create() { + ViewCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewCreateParams.ViewType.PROJECTS) + .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 body() { + val params = + ViewCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewCreateParams.ViewType.PROJECTS) + .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 body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(body.viewType()).contains(ViewCreateParams.ViewType.PROJECTS) + assertThat(body.deletedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(body.options()) + .contains( + 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() + ) + assertThat(body.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.viewData()) + .contains( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ViewCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewCreateParams.ViewType.PROJECTS) + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(body.viewType()).contains(ViewCreateParams.ViewType.PROJECTS) + } +} 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 new file mode 100755 index 00000000..5a03bd80 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataSearchTest.kt @@ -0,0 +1,53 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewDataSearchTest { + + @Test + fun create() { + val viewDataSearch = + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + + assertThat(viewDataSearch.filter().getOrNull()) + .containsExactly(JsonValue.from(mapOf())) + assertThat(viewDataSearch.match().getOrNull()) + .containsExactly(JsonValue.from(mapOf())) + assertThat(viewDataSearch.sort().getOrNull()) + .containsExactly(JsonValue.from(mapOf())) + assertThat(viewDataSearch.tag().getOrNull()) + .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 new file mode 100755 index 00000000..28b304e1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDataTest.kt @@ -0,0 +1,61 @@ +// 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 org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewDataTest { + + @Test + fun create() { + 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() + + assertThat(viewData.search()) + .contains( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .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 new file mode 100755 index 00000000..e6224941 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewDeleteParamsTest.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewDeleteParamsTest { + + @Test + fun create() { + ViewDeleteParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + } + + @Test + fun pathParams() { + val params = + ViewDeleteParams.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 = + ViewDeleteParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + + val body = params._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/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/ViewListParamsTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewListParamsTest.kt new file mode 100755 index 00000000..05c283a8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewListParamsTest.kt @@ -0,0 +1,74 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewListParamsTest { + + @Test + fun create() { + ViewListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .viewName("view_name") + .viewType(ViewType.PROJECTS) + .build() + } + + @Test + fun queryParams() { + val params = + ViewListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .endingBefore("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .startingAfter("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .viewName("view_name") + .viewType(ViewType.PROJECTS) + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("object_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("object_type", "organization") + .put("ending_before", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("ids", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("limit", "0") + .put("starting_after", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("view_name", "view_name") + .put("view_type", "projects") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = + ViewListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .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() + ) + } +} 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 new file mode 100755 index 00000000..3407df7f --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewOptionsTest.kt @@ -0,0 +1,81 @@ +// 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 kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewOptionsTest { + + @Test + fun create() { + 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() + + assertThat(viewOptions.columnOrder().getOrNull()).containsExactly("string") + assertThat(viewOptions.columnSizing()) + .contains( + ViewOptions.ColumnSizing.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(viewOptions.columnVisibility()) + .contains( + ViewOptions.ColumnVisibility.builder() + .putAdditionalProperty("foo", JsonValue.from(true)) + .build() + ) + assertThat(viewOptions.grouping()).contains("grouping") + 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 new file mode 100755 index 00000000..7b715533 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewReplaceParamsTest.kt @@ -0,0 +1,155 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.JsonValue +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewReplaceParamsTest { + + @Test + fun create() { + ViewReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewReplaceParams.ViewType.PROJECTS) + .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 body() { + val params = + ViewReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewReplaceParams.ViewType.PROJECTS) + .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 body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(body.viewType()).contains(ViewReplaceParams.ViewType.PROJECTS) + assertThat(body.deletedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(body.options()) + .contains( + 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() + ) + assertThat(body.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.viewData()) + .contains( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + ) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ViewReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewReplaceParams.ViewType.PROJECTS) + .build() + + val body = params._body() + + assertThat(body.name()).isEqualTo("name") + assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(body.viewType()).contains(ViewReplaceParams.ViewType.PROJECTS) + } +} 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 new file mode 100755 index 00000000..84cc78de --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewRetrieveParamsTest.kt @@ -0,0 +1,53 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.models + +import com.braintrustdata.api.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewRetrieveParamsTest { + + @Test + fun create() { + ViewRetrieveParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + } + + @Test + fun pathParams() { + val params = + ViewRetrieveParams.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 queryParams() { + val params = + ViewRetrieveParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .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() + ) + } +} 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 new file mode 100755 index 00000000..7dca73f4 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewTest.kt @@ -0,0 +1,150 @@ +// 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 ViewTest { + + @Test + fun create() { + 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() + + assertThat(view.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(view.name()).isEqualTo("name") + assertThat(view.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(view.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(view.viewType()).contains(View.ViewType.PROJECTS) + assertThat(view.created()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(view.deletedAt()).contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(view.options()) + .contains( + 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() + ) + assertThat(view.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(view.viewData()) + .contains( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .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 new file mode 100755 index 00000000..f2e0332c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/ViewUpdateParamsTest.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 org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ViewUpdateParamsTest { + + @Test + fun create() { + ViewUpdateParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .name("name") + .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() + ) + .viewType(ViewUpdateParams.ViewType.PROJECTS) + .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 = + ViewUpdateParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .name("name") + .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() + ) + .viewType(ViewUpdateParams.ViewType.PROJECTS) + .build() + + val body = params._body() + + assertThat(body.objectId()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.objectType()).isEqualTo(AclObjectType.ORGANIZATION) + assertThat(body.name()).contains("name") + assertThat(body.options()) + .contains( + 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() + ) + assertThat(body.userId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(body.viewData()) + .contains( + ViewData.builder() + .search( + ViewDataSearch.builder() + .addFilter(JsonValue.from(mapOf())) + .addMatch(JsonValue.from(mapOf())) + .addSort(JsonValue.from(mapOf())) + .addTag(JsonValue.from(mapOf())) + .build() + ) + .build() + ) + assertThat(body.viewType()).contains(ViewUpdateParams.ViewType.PROJECTS) + } + + @Test + fun bodyWithoutOptionalFields() { + val params = + ViewUpdateParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + + val body = params._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/services/ErrorHandlingTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/ErrorHandlingTest.kt old mode 100644 new mode 100755 index b0e6ebef..7be04bf5 --- 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 @@ -4,10 +4,10 @@ package com.braintrustdata.api.services import com.braintrustdata.api.client.BraintrustClient import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient -import com.braintrustdata.api.core.JsonString +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 @@ -16,33 +16,36 @@ import com.braintrustdata.api.errors.RateLimitException import com.braintrustdata.api.errors.UnauthorizedException import com.braintrustdata.api.errors.UnexpectedStatusCodeException import com.braintrustdata.api.errors.UnprocessableEntityException -import com.braintrustdata.api.models.* -import com.fasterxml.jackson.databind.json.JsonMapper +import com.braintrustdata.api.models.ProjectCreateParams import com.github.tomakehurst.wiremock.client.WireMock.anyUrl -import com.github.tomakehurst.wiremock.client.WireMock.get -import com.github.tomakehurst.wiremock.client.WireMock.ok import com.github.tomakehurst.wiremock.client.WireMock.post import com.github.tomakehurst.wiremock.client.WireMock.status import com.github.tomakehurst.wiremock.client.WireMock.stubFor import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo import com.github.tomakehurst.wiremock.junit5.WireMockTest -import com.google.common.collect.ImmutableListMultimap -import com.google.common.collect.ListMultimap -import java.time.OffsetDateTime import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.Assertions.assertThatThrownBy -import org.assertj.core.api.InstanceOfAssertFactories -import org.assertj.guava.api.Assertions.assertThat +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 -class ErrorHandlingTest { +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class ErrorHandlingTest { - private val JSON_MAPPER: JsonMapper = jsonMapper() + companion object { - private val BRAINTRUST_ERROR: BraintrustError = - BraintrustError.builder().putAdditionalProperty("key", JsonString.of("value")).build() + private val ERROR_JSON: JsonValue = JsonValue.from(mapOf("errorProperty" to "42")) + + private val ERROR_JSON_BYTES: ByteArray = jsonMapper().writeValueAsBytes(ERROR_JSON) + + private const val HEADER_NAME: String = "Error-Header" + + private const val HEADER_VALUE: String = "42" + + private const val NOT_JSON: String = "Not JSON" + } private lateinit var client: BraintrustClient @@ -50,305 +53,383 @@ class ErrorHandlingTest { fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { client = BraintrustOkHttpClient.builder() - .baseUrl(wmRuntimeInfo.getHttpBaseUrl()) + .baseUrl(wmRuntimeInfo.httpBaseUrl) .apiKey("My API Key") .build() } @Test - fun projectsCreate200() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() - - val expected = - Project.builder() - .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") - .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() + fun projectsCreate400() { + val projectService = client.projects() + stubFor( + post(anyUrl()) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) - stubFor(post(anyUrl()).willReturn(ok().withBody(toJson(expected)))) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } - assertThat(client.project().create(params)).isEqualTo(expected) + assertThat(e.statusCode()).isEqualTo(400) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun projectsCreate400() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() - + fun projectsCreate400WithRawResponse() { + val projectService = client.projects().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(400).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(400).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertBadRequest(e, ImmutableListMultimap.of("Foo", "Bar"), BRAINTRUST_ERROR) - }) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(400) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test fun projectsCreate401() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() + val projectService = client.projects() + stubFor( + post(anyUrl()) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(401) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun projectsCreate401WithRawResponse() { + val projectService = client.projects().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(401).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(401).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertUnauthorized(e, ImmutableListMultimap.of("Foo", "Bar"), BRAINTRUST_ERROR) - }) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(401) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test fun projectsCreate403() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() + val projectService = client.projects() + stubFor( + post(anyUrl()) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(403) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun projectsCreate403WithRawResponse() { + val projectService = client.projects().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(403).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(403).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertPermissionDenied(e, ImmutableListMultimap.of("Foo", "Bar"), BRAINTRUST_ERROR) - }) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(403) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test fun projectsCreate404() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() + val projectService = client.projects() + stubFor( + post(anyUrl()) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) + + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + assertThat(e.statusCode()).isEqualTo(404) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) + } + + @Test + fun projectsCreate404WithRawResponse() { + val projectService = client.projects().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(404).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(404).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertNotFound(e, ImmutableListMultimap.of("Foo", "Bar"), BRAINTRUST_ERROR) - }) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(404) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test fun projectsCreate422() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() - + val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(422).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertUnprocessableEntity( - e, - ImmutableListMultimap.of("Foo", "Bar"), - BRAINTRUST_ERROR + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() ) - }) + } + + assertThat(e.statusCode()).isEqualTo(422) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun projectsCreate429() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() - + fun projectsCreate422WithRawResponse() { + val projectService = client.projects().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(429).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(422).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertRateLimit(e, ImmutableListMultimap.of("Foo", "Bar"), BRAINTRUST_ERROR) - }) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(422) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun projectsCreate500() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() - + fun projectsCreate429() { + val projectService = client.projects() stubFor( post(anyUrl()) - .willReturn(status(500).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertInternalServer(e, ImmutableListMultimap.of("Foo", "Bar"), BRAINTRUST_ERROR) - }) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } + + assertThat(e.statusCode()).isEqualTo(429) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun unexpectedStatusCode() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() - + fun projectsCreate429WithRawResponse() { + val projectService = client.projects().withRawResponse() stubFor( post(anyUrl()) - .willReturn(status(999).withHeader("Foo", "Bar").withBody(toJson(BRAINTRUST_ERROR))) + .willReturn( + status(429).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) ) - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertUnexpectedStatusCodeException( - e, - 999, - ImmutableListMultimap.of("Foo", "Bar"), - toJson(BRAINTRUST_ERROR) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() ) - }) + } + + assertThat(e.statusCode()).isEqualTo(429) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun invalidBody() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() + fun projectsCreate500() { + val projectService = client.projects() + stubFor( + post(anyUrl()) + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) - stubFor(post(anyUrl()).willReturn(status(200).withBody("Not JSON"))) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertThat(e) - .isInstanceOf(BraintrustException::class.java) - .hasMessage("Error reading response") - }) + assertThat(e.statusCode()).isEqualTo(500) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } @Test - fun invalidErrorBody() { - val params = ProjectCreateParams.builder().name("string").orgName("string").build() + fun projectsCreate500WithRawResponse() { + val projectService = client.projects().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(500).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) - stubFor(post(anyUrl()).willReturn(status(400).withBody("Not JSON"))) + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } - assertThatThrownBy({ client.project().create(params) }) - .satisfies({ e -> - assertBadRequest(e, ImmutableListMultimap.of(), BraintrustError.builder().build()) - }) + assertThat(e.statusCode()).isEqualTo(500) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } - private fun toJson(body: T): ByteArray { - return JSON_MAPPER.writeValueAsBytes(body) - } + @Test + fun projectsCreate999() { + val projectService = client.projects() + stubFor( + post(anyUrl()) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) - private fun assertUnexpectedStatusCodeException( - throwable: Throwable, - statusCode: Int, - headers: ListMultimap, - responseBody: ByteArray - ) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(UnexpectedStatusCodeException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(statusCode) - assertThat(e.body()).isEqualTo(String(responseBody)) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) - } + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } - private fun assertBadRequest( - throwable: Throwable, - headers: ListMultimap, - error: BraintrustError - ) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(BadRequestException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(400) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) + assertThat(e.statusCode()).isEqualTo(999) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } - private fun assertUnauthorized( - throwable: Throwable, - headers: ListMultimap, - error: BraintrustError - ) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(UnauthorizedException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(401) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) - } + @Test + fun projectsCreate999WithRawResponse() { + val projectService = client.projects().withRawResponse() + stubFor( + post(anyUrl()) + .willReturn( + status(999).withHeader(HEADER_NAME, HEADER_VALUE).withBody(ERROR_JSON_BYTES) + ) + ) - private fun assertPermissionDenied( - throwable: Throwable, - headers: ListMultimap, - error: BraintrustError - ) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(PermissionDeniedException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(403) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) - } + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } - private fun assertNotFound( - throwable: Throwable, - headers: ListMultimap, - error: BraintrustError - ) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(NotFoundException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(404) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) + assertThat(e.statusCode()).isEqualTo(999) + assertThat(e.headers().toMap()).contains(entry(HEADER_NAME, listOf(HEADER_VALUE))) + assertThat(e.body()).isEqualTo(ERROR_JSON) } - private fun assertUnprocessableEntity( - throwable: Throwable, - headers: ListMultimap, - error: BraintrustError - ) { - assertThat(throwable) - .asInstanceOf( - InstanceOfAssertFactories.throwable(UnprocessableEntityException::class.java) - ) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(422) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) - } + @Test + fun projectsCreateInvalidJsonBody() { + val projectService = client.projects() + stubFor( + post(anyUrl()) + .willReturn(status(200).withHeader(HEADER_NAME, HEADER_VALUE).withBody(NOT_JSON)) + ) - private fun assertRateLimit( - throwable: Throwable, - headers: ListMultimap, - error: BraintrustError - ) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(RateLimitException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(429) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) - } + val e = + assertThrows { + projectService.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + } - private fun assertInternalServer( - throwable: Throwable, - headers: ListMultimap, - error: BraintrustError - ) { - assertThat(throwable) - .asInstanceOf(InstanceOfAssertFactories.throwable(InternalServerException::class.java)) - .satisfies({ e -> - assertThat(e.statusCode()).isEqualTo(500) - assertThat(e.error()).isEqualTo(error) - assertThat(e.headers()).containsAllEntriesOf(headers) - }) + assertThat(e).hasMessage("Error reading response") } + + private fun Headers.toMap(): Map> = + mutableMapOf>().also { map -> + names().forEach { map[it] = values(it) } + } } 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 old mode 100644 new mode 100755 index 49da90c5..436926c8 --- 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 @@ -4,14 +4,10 @@ package com.braintrustdata.api.services import com.braintrustdata.api.client.BraintrustClient import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient -import com.braintrustdata.api.core.JsonString import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.core.jsonMapper -import com.braintrustdata.api.models.* -import com.fasterxml.jackson.databind.json.JsonMapper +import com.braintrustdata.api.models.ProjectCreateParams import com.github.tomakehurst.wiremock.client.WireMock.anyUrl import com.github.tomakehurst.wiremock.client.WireMock.equalTo -import com.github.tomakehurst.wiremock.client.WireMock.get import com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath import com.github.tomakehurst.wiremock.client.WireMock.ok import com.github.tomakehurst.wiremock.client.WireMock.post @@ -20,14 +16,13 @@ import com.github.tomakehurst.wiremock.client.WireMock.stubFor import com.github.tomakehurst.wiremock.client.WireMock.verify import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo import com.github.tomakehurst.wiremock.junit5.WireMockTest -import java.time.OffsetDateTime import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.junit.jupiter.api.parallel.ResourceLock @WireMockTest -class ServiceParamsTest { - - private val JSON_MAPPER: JsonMapper = jsonMapper() +@ResourceLock("https://github.com/wiremock/wiremock/issues/169") +internal class ServiceParamsTest { private lateinit var client: BraintrustClient @@ -35,54 +30,31 @@ class ServiceParamsTest { fun beforeEach(wmRuntimeInfo: WireMockRuntimeInfo) { client = BraintrustOkHttpClient.builder() + .baseUrl(wmRuntimeInfo.httpBaseUrl) .apiKey("My API Key") - .baseUrl(wmRuntimeInfo.getHttpBaseUrl()) .build() } @Test - fun projectsCreateWithAdditionalParams() { - val additionalHeaders = mutableMapOf>() - - additionalHeaders.put("x-test-header", listOf("abc1234")) - - val additionalQueryParams = mutableMapOf>() - - additionalQueryParams.put("test_query_param", listOf("def567")) - - val additionalBodyProperties = mutableMapOf() - - additionalBodyProperties.put("testBodyProperty", JsonString.of("ghi890")) + fun create() { + val projectService = client.projects() + stubFor(post(anyUrl()).willReturn(ok("{}"))) - val params = + projectService.create( ProjectCreateParams.builder() - .name("string") - .orgName("string") - .additionalHeaders(additionalHeaders) - .additionalBodyProperties(additionalBodyProperties) - .additionalQueryParams(additionalQueryParams) + .name("x") + .orgName("org_name") + .putAdditionalHeader("Secret-Header", "42") + .putAdditionalQueryParam("secret_query_param", "42") + .putAdditionalBodyProperty("secretProperty", JsonValue.from("42")) .build() - - val apiResponse = - Project.builder() - .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") - .orgId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .created(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .deletedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) - .userId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - - stubFor( - post(anyUrl()) - .withHeader("x-test-header", equalTo("abc1234")) - .withQueryParam("test_query_param", equalTo("def567")) - .withRequestBody(matchingJsonPath("$.testBodyProperty", equalTo("ghi890"))) - .willReturn(ok(JSON_MAPPER.writeValueAsString(apiResponse))) ) - client.project().create(params) - - verify(postRequestedFor(anyUrl())) + verify( + postRequestedFor(anyUrl()) + .withHeader("Secret-Header", equalTo("42")) + .withQueryParam("secret_query_param", equalTo("42")) + .withRequestBody(matchingJsonPath("$.secretProperty", equalTo("42"))) + ) } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncTest.kt new file mode 100644 index 00000000..0be8c044 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/AclServiceAsyncTest.kt @@ -0,0 +1,162 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.AclBatchUpdateParams +import com.braintrustdata.api.models.AclCreateParams +import com.braintrustdata.api.models.AclFindAndDeleteParams +import com.braintrustdata.api.models.AclListParams +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.Permission +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class AclServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclServiceAsync = client.acls() + + val aclFuture = + aclServiceAsync.create( + AclCreateParams.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() + ) + + val acl = aclFuture.get() + acl.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclServiceAsync = client.acls() + + val aclFuture = aclServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val acl = aclFuture.get() + acl.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclServiceAsync = client.acls() + + val pageFuture = + aclServiceAsync.list( + AclListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclServiceAsync = client.acls() + + val aclFuture = aclServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val acl = aclFuture.get() + acl.validate() + } + + @Test + fun batchUpdate() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclServiceAsync = client.acls() + + val aclBatchUpdateResponseFuture = + aclServiceAsync.batchUpdate( + AclBatchUpdateParams.builder() + .addAddAcl( + 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() + ) + .addRemoveAcl( + 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() + ) + .build() + ) + + val aclBatchUpdateResponse = aclBatchUpdateResponseFuture.get() + aclBatchUpdateResponse.validate() + } + + @Test + fun findAndDelete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclServiceAsync = client.acls() + + val aclFuture = + aclServiceAsync.findAndDelete( + AclFindAndDeleteParams.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() + ) + + val acl = aclFuture.get() + acl.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncTest.kt new file mode 100644 index 00000000..a4eed2d1 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/AiSecretServiceAsyncTest.kt @@ -0,0 +1,164 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.AiSecretCreateParams +import com.braintrustdata.api.models.AiSecretFindAndDeleteParams +import com.braintrustdata.api.models.AiSecretReplaceParams +import com.braintrustdata.api.models.AiSecretUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class AiSecretServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretServiceAsync = client.aiSecrets() + + val aISecretFuture = + aiSecretServiceAsync.create( + AiSecretCreateParams.builder() + .name("name") + .metadata( + AiSecretCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + ) + + val aISecret = aISecretFuture.get() + aISecret.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretServiceAsync = client.aiSecrets() + + val aISecretFuture = aiSecretServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val aISecret = aISecretFuture.get() + aISecret.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretServiceAsync = client.aiSecrets() + + val aISecretFuture = + aiSecretServiceAsync.update( + AiSecretUpdateParams.builder() + .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .metadata( + AiSecretUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") + .secret("secret") + .type("type") + .build() + ) + + val aISecret = aISecretFuture.get() + aISecret.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretServiceAsync = client.aiSecrets() + + val pageFuture = aiSecretServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretServiceAsync = client.aiSecrets() + + val aISecretFuture = aiSecretServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val aISecret = aISecretFuture.get() + aISecret.validate() + } + + @Test + fun findAndDelete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretServiceAsync = client.aiSecrets() + + val aISecretFuture = + aiSecretServiceAsync.findAndDelete( + AiSecretFindAndDeleteParams.builder().name("name").orgName("org_name").build() + ) + + val aISecret = aISecretFuture.get() + aISecret.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretServiceAsync = client.aiSecrets() + + val aISecretFuture = + aiSecretServiceAsync.replace( + AiSecretReplaceParams.builder() + .name("name") + .metadata( + AiSecretReplaceParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + ) + + val aISecret = aISecretFuture.get() + aISecret.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncTest.kt new file mode 100644 index 00000000..5b6ce107 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ApiKeyServiceAsyncTest.kt @@ -0,0 +1,76 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.ApiKeyCreateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ApiKeyServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyServiceAsync = client.apiKeys() + + val createApiKeyOutputFuture = + apiKeyServiceAsync.create( + ApiKeyCreateParams.builder().name("name").orgName("org_name").build() + ) + + val createApiKeyOutput = createApiKeyOutputFuture.get() + createApiKeyOutput.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyServiceAsync = client.apiKeys() + + val apiKeyFuture = apiKeyServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val apiKey = apiKeyFuture.get() + apiKey.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyServiceAsync = client.apiKeys() + + val pageFuture = apiKeyServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyServiceAsync = client.apiKeys() + + val apiKeyFuture = apiKeyServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val apiKey = apiKeyFuture.get() + apiKey.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsyncTest.kt new file mode 100644 index 00000000..abda8106 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/DatasetServiceAsyncTest.kt @@ -0,0 +1,272 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.DatasetCreateParams +import com.braintrustdata.api.models.DatasetFeedbackParams +import com.braintrustdata.api.models.DatasetFetchParams +import com.braintrustdata.api.models.DatasetFetchPostParams +import com.braintrustdata.api.models.DatasetInsertParams +import com.braintrustdata.api.models.DatasetSummarizeParams +import com.braintrustdata.api.models.DatasetUpdateParams +import com.braintrustdata.api.models.FeedbackDatasetItem +import com.braintrustdata.api.models.InsertDatasetEvent +import com.braintrustdata.api.models.ObjectReference +import java.time.OffsetDateTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class DatasetServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val datasetFuture = + datasetServiceAsync.create( + DatasetCreateParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .metadata( + DatasetCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + + val dataset = datasetFuture.get() + dataset.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val datasetFuture = datasetServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val dataset = datasetFuture.get() + dataset.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val datasetFuture = + datasetServiceAsync.update( + DatasetUpdateParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .metadata( + DatasetUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") + .build() + ) + + val dataset = datasetFuture.get() + dataset.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val pageFuture = datasetServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val datasetFuture = datasetServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val dataset = datasetFuture.get() + dataset.validate() + } + + @Test + fun feedback() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val feedbackResponseSchemaFuture = + datasetServiceAsync.feedback( + DatasetFeedbackParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback( + FeedbackDatasetItem.builder() + .id("id") + .comment("comment") + .metadata( + FeedbackDatasetItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .source(FeedbackDatasetItem.Source.APP) + .addTag("string") + .build() + ) + .build() + ) + + val feedbackResponseSchema = feedbackResponseSchemaFuture.get() + feedbackResponseSchema.validate() + } + + @Test + fun fetch() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val fetchDatasetEventsResponseFuture = + datasetServiceAsync.fetch( + DatasetFetchParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + val fetchDatasetEventsResponse = fetchDatasetEventsResponseFuture.get() + fetchDatasetEventsResponse.validate() + } + + @Test + fun fetchPost() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val fetchDatasetEventsResponseFuture = + datasetServiceAsync.fetchPost( + DatasetFetchPostParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + val fetchDatasetEventsResponse = fetchDatasetEventsResponseFuture.get() + fetchDatasetEventsResponse.validate() + } + + @Test + fun insert() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val insertEventsResponseFuture = + datasetServiceAsync.insert( + DatasetInsertParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addEvent( + 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() + ) + .build() + ) + + val insertEventsResponse = insertEventsResponseFuture.get() + insertEventsResponse.validate() + } + + @Test + fun summarize() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val datasetServiceAsync = client.datasets() + + val summarizeDatasetResponseFuture = + datasetServiceAsync.summarize( + DatasetSummarizeParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeData(true) + .build() + ) + + val summarizeDatasetResponse = summarizeDatasetResponseFuture.get() + summarizeDatasetResponse.validate() + } +} 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 new file mode 100644 index 00000000..eeb42915 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EnvVarServiceAsyncTest.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.EnvVarCreateParams +import com.braintrustdata.api.models.EnvVarListParams +import com.braintrustdata.api.models.EnvVarObjectType +import com.braintrustdata.api.models.EnvVarReplaceParams +import com.braintrustdata.api.models.EnvVarUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class EnvVarServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarServiceAsync = client.envVars() + + val envVarFuture = + envVarServiceAsync.create( + EnvVarCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarCreateParams.ObjectType.ORGANIZATION) + .value("value") + .build() + ) + + val envVar = envVarFuture.get() + envVar.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarServiceAsync = client.envVars() + + val envVarFuture = envVarServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val envVar = envVarFuture.get() + envVar.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarServiceAsync = client.envVars() + + val envVarFuture = + envVarServiceAsync.update( + EnvVarUpdateParams.builder() + .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .value("value") + .build() + ) + + val envVar = envVarFuture.get() + envVar.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarServiceAsync = client.envVars() + + val envVarsFuture = + envVarServiceAsync.list( + EnvVarListParams.builder() + .envVarName("env_var_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarObjectType.ORGANIZATION) + .build() + ) + + val envVars = envVarsFuture.get() + envVars.validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarServiceAsync = client.envVars() + + val envVarFuture = envVarServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val envVar = envVarFuture.get() + envVar.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarServiceAsync = client.envVars() + + val envVarFuture = + envVarServiceAsync.replace( + EnvVarReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarReplaceParams.ObjectType.ORGANIZATION) + .value("value") + .build() + ) + + val envVar = envVarFuture.get() + envVar.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncTest.kt new file mode 100644 index 00000000..965be9d0 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/EvalServiceAsyncTest.kt @@ -0,0 +1,110 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.EvalCreateParams +import com.braintrustdata.api.models.RepoInfo +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class EvalServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val evalServiceAsync = client.evals() + + val summarizeExperimentResponseFuture = + evalServiceAsync.create( + EvalCreateParams.builder() + .data( + EvalCreateParams.Data.DatasetId.builder() + .datasetId("dataset_id") + ._internalBtql( + EvalCreateParams.Data.DatasetId._InternalBtql + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .projectId("project_id") + .addScore( + EvalCreateParams.Score.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .task( + EvalCreateParams.Task.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .baseExperimentId("base_experiment_id") + .baseExperimentName("base_experiment_name") + .experimentName("experiment_name") + .gitMetadataSettings( + EvalCreateParams.GitMetadataSettings.builder() + .collect(EvalCreateParams.GitMetadataSettings.Collect.ALL) + .addField(EvalCreateParams.GitMetadataSettings.Field.COMMIT) + .build() + ) + .isPublic(true) + .maxConcurrency(0.0) + .metadata( + EvalCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .parent( + EvalCreateParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + EvalCreateParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + EvalCreateParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + EvalCreateParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .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() + ) + .stream(true) + .timeout(0.0) + .trialCount(0.0) + .build() + ) + + val summarizeExperimentResponse = summarizeExperimentResponseFuture.get() + summarizeExperimentResponse.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsyncTest.kt new file mode 100644 index 00000000..1c558edb --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ExperimentServiceAsyncTest.kt @@ -0,0 +1,349 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.ExperimentCreateParams +import com.braintrustdata.api.models.ExperimentFeedbackParams +import com.braintrustdata.api.models.ExperimentFetchParams +import com.braintrustdata.api.models.ExperimentFetchPostParams +import com.braintrustdata.api.models.ExperimentInsertParams +import com.braintrustdata.api.models.ExperimentSummarizeParams +import com.braintrustdata.api.models.ExperimentUpdateParams +import com.braintrustdata.api.models.FeedbackExperimentItem +import com.braintrustdata.api.models.InsertExperimentEvent +import com.braintrustdata.api.models.ObjectReference +import com.braintrustdata.api.models.RepoInfo +import com.braintrustdata.api.models.SpanAttributes +import com.braintrustdata.api.models.SpanType +import java.time.OffsetDateTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ExperimentServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val experimentFuture = + experimentServiceAsync.create( + ExperimentCreateParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetVersion("dataset_version") + .description("description") + .ensureNew(true) + .metadata( + ExperimentCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("x") + .public_(true) + .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() + ) + .build() + ) + + val experiment = experimentFuture.get() + experiment.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val experimentFuture = + experimentServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val experiment = experimentFuture.get() + experiment.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val experimentFuture = + experimentServiceAsync.update( + ExperimentUpdateParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .datasetVersion("dataset_version") + .description("description") + .metadata( + ExperimentUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") + .public_(true) + .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() + ) + .build() + ) + + val experiment = experimentFuture.get() + experiment.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val pageFuture = experimentServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val experimentFuture = experimentServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val experiment = experimentFuture.get() + experiment.validate() + } + + @Test + fun feedback() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val feedbackResponseSchemaFuture = + experimentServiceAsync.feedback( + ExperimentFeedbackParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback( + 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() + ) + .build() + ) + + val feedbackResponseSchema = feedbackResponseSchemaFuture.get() + feedbackResponseSchema.validate() + } + + @Test + fun fetch() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val fetchExperimentEventsResponseFuture = + experimentServiceAsync.fetch( + ExperimentFetchParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + val fetchExperimentEventsResponse = fetchExperimentEventsResponseFuture.get() + fetchExperimentEventsResponse.validate() + } + + @Test + fun fetchPost() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val fetchExperimentEventsResponseFuture = + experimentServiceAsync.fetchPost( + ExperimentFetchPostParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + val fetchExperimentEventsResponse = fetchExperimentEventsResponseFuture.get() + fetchExperimentEventsResponse.validate() + } + + @Test + fun insert() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val insertEventsResponseFuture = + experimentServiceAsync.insert( + ExperimentInsertParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addEvent( + 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() + ) + .build() + ) + + val insertEventsResponse = insertEventsResponseFuture.get() + insertEventsResponse.validate() + } + + @Test + fun summarize() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val experimentServiceAsync = client.experiments() + + val summarizeExperimentResponseFuture = + experimentServiceAsync.summarize( + ExperimentSummarizeParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeScores(true) + .build() + ) + + val summarizeExperimentResponse = summarizeExperimentResponseFuture.get() + summarizeExperimentResponse.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncTest.kt new file mode 100644 index 00000000..279f89c4 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/FunctionServiceAsyncTest.kt @@ -0,0 +1,485 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.FunctionCreateParams +import com.braintrustdata.api.models.FunctionInvokeParams +import com.braintrustdata.api.models.FunctionReplaceParams +import com.braintrustdata.api.models.FunctionUpdateParams +import com.braintrustdata.api.models.PromptData +import com.braintrustdata.api.models.PromptOptions +import kotlin.jvm.optionals.getOrNull +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FunctionServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionServiceAsync = client.functions() + + val functionFuture = + functionServiceAsync.create( + FunctionCreateParams.builder() + .functionData( + FunctionCreateParams.FunctionData.Prompt.builder() + .type(FunctionCreateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionCreateParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionCreateParams.FunctionType.LLM) + .origin( + FunctionCreateParams.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 function = functionFuture.get() + function.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionServiceAsync = client.functions() + + val functionFuture = functionServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val function = functionFuture.get() + function.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionServiceAsync = client.functions() + + val functionFuture = + functionServiceAsync.update( + FunctionUpdateParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .functionData( + FunctionUpdateParams.FunctionData.Prompt.builder() + .type(FunctionUpdateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("name") + .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 function = functionFuture.get() + function.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionServiceAsync = client.functions() + + val pageFuture = functionServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionServiceAsync = client.functions() + + val functionFuture = functionServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val function = functionFuture.get() + function.validate() + } + + @Test + fun invoke() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionServiceAsync = client.functions() + + val responseFuture = + functionServiceAsync.invoke( + FunctionInvokeParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .addMessage( + FunctionInvokeParams.Message.System.builder() + .role(FunctionInvokeParams.Message.System.Role.SYSTEM) + .content("content") + .name("name") + .build() + ) + .metadata( + FunctionInvokeParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .mode(FunctionInvokeParams.Mode.AUTO) + .parent( + FunctionInvokeParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + FunctionInvokeParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + FunctionInvokeParams.Parent.SpanParentStruct.PropagatedEvent + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + FunctionInvokeParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .build() + ) + .stream(true) + .version("version") + .build() + ) + + val response = responseFuture.get() + val unwrappedResponse = response.getOrNull() + unwrappedResponse?.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionServiceAsync = client.functions() + + val functionFuture = + functionServiceAsync.replace( + FunctionReplaceParams.builder() + .functionData( + FunctionReplaceParams.FunctionData.Prompt.builder() + .type(FunctionReplaceParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionReplaceParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionReplaceParams.FunctionType.LLM) + .origin( + FunctionReplaceParams.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 function = functionFuture.get() + function.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncTest.kt new file mode 100644 index 00000000..ea16d5e2 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/GroupServiceAsyncTest.kt @@ -0,0 +1,134 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.GroupCreateParams +import com.braintrustdata.api.models.GroupReplaceParams +import com.braintrustdata.api.models.GroupUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class GroupServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupServiceAsync = client.groups() + + val groupFuture = + groupServiceAsync.create( + GroupCreateParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + val group = groupFuture.get() + group.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupServiceAsync = client.groups() + + val groupFuture = groupServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val group = groupFuture.get() + group.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupServiceAsync = client.groups() + + val groupFuture = + groupServiceAsync.update( + GroupUpdateParams.builder() + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addRemoveMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + + val group = groupFuture.get() + group.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupServiceAsync = client.groups() + + val pageFuture = groupServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupServiceAsync = client.groups() + + val groupFuture = groupServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val group = groupFuture.get() + group.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupServiceAsync = client.groups() + + val groupFuture = + groupServiceAsync.replace( + GroupReplaceParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + val group = groupFuture.get() + group.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncTest.kt new file mode 100644 index 00000000..d25afe9f --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/OrganizationServiceAsyncTest.kt @@ -0,0 +1,85 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.OrganizationUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class OrganizationServiceAsyncTest { + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationServiceAsync = client.organizations() + + val organizationFuture = + organizationServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val organization = organizationFuture.get() + organization.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationServiceAsync = client.organizations() + + val organizationFuture = + organizationServiceAsync.update( + OrganizationUpdateParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .apiUrl("api_url") + .isUniversalApi(true) + .name("name") + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .build() + ) + + val organization = organizationFuture.get() + organization.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationServiceAsync = client.organizations() + + val pageFuture = organizationServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationServiceAsync = client.organizations() + + val organizationFuture = + organizationServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val organization = organizationFuture.get() + organization.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncTest.kt new file mode 100644 index 00000000..9114be85 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectScoreServiceAsyncTest.kt @@ -0,0 +1,201 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.OnlineScoreConfig +import com.braintrustdata.api.models.ProjectScoreCategory +import com.braintrustdata.api.models.ProjectScoreConfig +import com.braintrustdata.api.models.ProjectScoreCreateParams +import com.braintrustdata.api.models.ProjectScoreReplaceParams +import com.braintrustdata.api.models.ProjectScoreType +import com.braintrustdata.api.models.ProjectScoreUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ProjectScoreServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreServiceAsync = client.projectScores() + + val projectScoreFuture = + projectScoreServiceAsync.create( + ProjectScoreCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + ) + + val projectScore = projectScoreFuture.get() + projectScore.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreServiceAsync = client.projectScores() + + val projectScoreFuture = + projectScoreServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val projectScore = projectScoreFuture.get() + projectScore.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreServiceAsync = client.projectScores() + + val projectScoreFuture = + projectScoreServiceAsync.update( + ProjectScoreUpdateParams.builder() + .projectScoreId("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() + ) + .description("description") + .name("name") + .scoreType(ProjectScoreType.SLIDER) + .build() + ) + + val projectScore = projectScoreFuture.get() + projectScore.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreServiceAsync = client.projectScores() + + val pageFuture = projectScoreServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreServiceAsync = client.projectScores() + + val projectScoreFuture = + projectScoreServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val projectScore = projectScoreFuture.get() + projectScore.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreServiceAsync = client.projectScores() + + val projectScoreFuture = + projectScoreServiceAsync.replace( + ProjectScoreReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + ) + + val projectScore = projectScoreFuture.get() + projectScore.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsyncTest.kt new file mode 100644 index 00000000..9e476bd8 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectServiceAsyncTest.kt @@ -0,0 +1,113 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.ProjectCreateParams +import com.braintrustdata.api.models.ProjectSettings +import com.braintrustdata.api.models.ProjectUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ProjectServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectServiceAsync = client.projects() + + val projectFuture = + projectServiceAsync.create( + ProjectCreateParams.builder().name("x").orgName("org_name").build() + ) + + val project = projectFuture.get() + project.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectServiceAsync = client.projects() + + val projectFuture = projectServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val project = projectFuture.get() + project.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectServiceAsync = client.projects() + + val projectFuture = + projectServiceAsync.update( + ProjectUpdateParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .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() + ) + .build() + ) + + val project = projectFuture.get() + project.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectServiceAsync = client.projects() + + val pageFuture = projectServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectServiceAsync = client.projects() + + val projectFuture = projectServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val project = projectFuture.get() + project.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncTest.kt new file mode 100644 index 00000000..6513ddc2 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ProjectTagServiceAsyncTest.kt @@ -0,0 +1,130 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.ProjectTagCreateParams +import com.braintrustdata.api.models.ProjectTagReplaceParams +import com.braintrustdata.api.models.ProjectTagUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ProjectTagServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagServiceAsync = client.projectTags() + + val projectTagFuture = + projectTagServiceAsync.create( + ProjectTagCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + ) + + val projectTag = projectTagFuture.get() + projectTag.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagServiceAsync = client.projectTags() + + val projectTagFuture = + projectTagServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val projectTag = projectTagFuture.get() + projectTag.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagServiceAsync = client.projectTags() + + val projectTagFuture = + projectTagServiceAsync.update( + ProjectTagUpdateParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .name("name") + .build() + ) + + val projectTag = projectTagFuture.get() + projectTag.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagServiceAsync = client.projectTags() + + val pageFuture = projectTagServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagServiceAsync = client.projectTags() + + val projectTagFuture = projectTagServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val projectTag = projectTagFuture.get() + projectTag.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagServiceAsync = client.projectTags() + + val projectTagFuture = + projectTagServiceAsync.replace( + ProjectTagReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + ) + + val projectTag = projectTagFuture.get() + projectTag.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncTest.kt new file mode 100644 index 00000000..23704cdd --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/PromptServiceAsyncTest.kt @@ -0,0 +1,383 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.PromptCreateParams +import com.braintrustdata.api.models.PromptData +import com.braintrustdata.api.models.PromptOptions +import com.braintrustdata.api.models.PromptReplaceParams +import com.braintrustdata.api.models.PromptUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class PromptServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptServiceAsync = client.prompts() + + val promptFuture = + promptServiceAsync.create( + PromptCreateParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptCreateParams.FunctionType.LLM) + .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 prompt = promptFuture.get() + prompt.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptServiceAsync = client.prompts() + + val promptFuture = promptServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val prompt = promptFuture.get() + prompt.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptServiceAsync = client.prompts() + + val promptFuture = + promptServiceAsync.update( + PromptUpdateParams.builder() + .promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .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() + ) + .slug("slug") + .addTag("string") + .build() + ) + + val prompt = promptFuture.get() + prompt.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptServiceAsync = client.prompts() + + val pageFuture = promptServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptServiceAsync = client.prompts() + + val promptFuture = promptServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val prompt = promptFuture.get() + prompt.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptServiceAsync = client.prompts() + + val promptFuture = + promptServiceAsync.replace( + PromptReplaceParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptReplaceParams.FunctionType.LLM) + .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 prompt = promptFuture.get() + prompt.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncTest.kt new file mode 100644 index 00000000..ac57e006 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/RoleServiceAsyncTest.kt @@ -0,0 +1,156 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.Permission +import com.braintrustdata.api.models.RoleCreateParams +import com.braintrustdata.api.models.RoleReplaceParams +import com.braintrustdata.api.models.RoleUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class RoleServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleServiceAsync = client.roles() + + val roleFuture = + roleServiceAsync.create( + RoleCreateParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleCreateParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + val role = roleFuture.get() + role.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleServiceAsync = client.roles() + + val roleFuture = roleServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val role = roleFuture.get() + role.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleServiceAsync = client.roles() + + val roleFuture = + roleServiceAsync.update( + RoleUpdateParams.builder() + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberPermission( + RoleUpdateParams.AddMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addAddMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberPermission( + RoleUpdateParams.RemoveMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addRemoveMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + + val role = roleFuture.get() + role.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleServiceAsync = client.roles() + + val pageFuture = roleServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleServiceAsync = client.roles() + + val roleFuture = roleServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val role = roleFuture.get() + role.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleServiceAsync = client.roles() + + val roleFuture = + roleServiceAsync.replace( + RoleReplaceParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleReplaceParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + val role = roleFuture.get() + role.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncTest.kt new file mode 100644 index 00000000..1f3a44e0 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/SpanIframeServiceAsyncTest.kt @@ -0,0 +1,133 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.SpanIframeCreateParams +import com.braintrustdata.api.models.SpanIframeReplaceParams +import com.braintrustdata.api.models.SpanIframeUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class SpanIframeServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeServiceAsync = client.spanIframes() + + val spanIFrameFuture = + spanIframeServiceAsync.create( + SpanIframeCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + ) + + val spanIFrame = spanIFrameFuture.get() + spanIFrame.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeServiceAsync = client.spanIframes() + + val spanIFrameFuture = + spanIframeServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val spanIFrame = spanIFrameFuture.get() + spanIFrame.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeServiceAsync = client.spanIframes() + + val spanIFrameFuture = + spanIframeServiceAsync.update( + SpanIframeUpdateParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .postMessage(true) + .url("url") + .build() + ) + + val spanIFrame = spanIFrameFuture.get() + spanIFrame.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeServiceAsync = client.spanIframes() + + val pageFuture = spanIframeServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeServiceAsync = client.spanIframes() + + val spanIFrameFuture = spanIframeServiceAsync.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val spanIFrame = spanIFrameFuture.get() + spanIFrame.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeServiceAsync = client.spanIframes() + + val spanIFrameFuture = + spanIframeServiceAsync.replace( + SpanIframeReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + ) + + val spanIFrame = spanIFrameFuture.get() + spanIFrame.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsyncTest.kt new file mode 100644 index 00000000..08b3dbdf --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/TopLevelServiceAsyncTest.kt @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class TopLevelServiceAsyncTest { + + @Test + fun helloWorld() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val topLevelServiceAsync = client.topLevel() + + val responseFuture = topLevelServiceAsync.helloWorld() + + val response = responseFuture.get() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncTest.kt new file mode 100644 index 00000000..3352ae50 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/UserServiceAsyncTest.kt @@ -0,0 +1,42 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class UserServiceAsyncTest { + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val userServiceAsync = client.users() + + val userFuture = userServiceAsync.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val user = userFuture.get() + user.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val userServiceAsync = client.users() + + val pageFuture = userServiceAsync.list() + + val page = pageFuture.get() + page.response().validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncTest.kt new file mode 100644 index 00000000..829ac4ec --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/ViewServiceAsyncTest.kt @@ -0,0 +1,254 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.ViewCreateParams +import com.braintrustdata.api.models.ViewData +import com.braintrustdata.api.models.ViewDataSearch +import com.braintrustdata.api.models.ViewDeleteParams +import com.braintrustdata.api.models.ViewListParams +import com.braintrustdata.api.models.ViewOptions +import com.braintrustdata.api.models.ViewReplaceParams +import com.braintrustdata.api.models.ViewRetrieveParams +import com.braintrustdata.api.models.ViewUpdateParams +import java.time.OffsetDateTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ViewServiceAsyncTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewServiceAsync = client.views() + + val viewFuture = + viewServiceAsync.create( + ViewCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewCreateParams.ViewType.PROJECTS) + .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 view = viewFuture.get() + view.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewServiceAsync = client.views() + + val viewFuture = + viewServiceAsync.retrieve( + ViewRetrieveParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + val view = viewFuture.get() + view.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewServiceAsync = client.views() + + val viewFuture = + viewServiceAsync.update( + ViewUpdateParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .name("name") + .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() + ) + .viewType(ViewUpdateParams.ViewType.PROJECTS) + .build() + ) + + val view = viewFuture.get() + view.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewServiceAsync = client.views() + + val pageFuture = + viewServiceAsync.list( + ViewListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + val page = pageFuture.get() + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewServiceAsync = client.views() + + val viewFuture = + viewServiceAsync.delete( + ViewDeleteParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + val view = viewFuture.get() + view.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewServiceAsync = client.views() + + val viewFuture = + viewServiceAsync.replace( + ViewReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewReplaceParams.ViewType.PROJECTS) + .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 view = viewFuture.get() + view.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncTest.kt new file mode 100644 index 00000000..aad7f865 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/organizations/MemberServiceAsyncTest.kt @@ -0,0 +1,51 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async.organizations + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.models.OrganizationMemberUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class MemberServiceAsyncTest { + + @Test + fun update() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val memberServiceAsync = client.organizations().members() + + val patchOrganizationMembersOutputFuture = + memberServiceAsync.update( + OrganizationMemberUpdateParams.builder() + .inviteUsers( + OrganizationMemberUpdateParams.InviteUsers.builder() + .addEmail("string") + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addGroupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .groupName("group_name") + .addGroupName("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .sendInviteEmails(true) + .build() + ) + .orgId("org_id") + .orgName("org_name") + .removeUsers( + OrganizationMemberUpdateParams.RemoveUsers.builder() + .addEmail("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + ) + + val patchOrganizationMembersOutput = patchOrganizationMembersOutputFuture.get() + patchOrganizationMembersOutput.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncTest.kt new file mode 100644 index 00000000..035fda7e --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/async/projects/LogServiceAsyncTest.kt @@ -0,0 +1,188 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.async.projects + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClientAsync +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.FeedbackProjectLogsItem +import com.braintrustdata.api.models.InsertProjectLogsEvent +import com.braintrustdata.api.models.ObjectReference +import com.braintrustdata.api.models.ProjectLogFeedbackParams +import com.braintrustdata.api.models.ProjectLogFetchParams +import com.braintrustdata.api.models.ProjectLogFetchPostParams +import com.braintrustdata.api.models.ProjectLogInsertParams +import com.braintrustdata.api.models.SpanAttributes +import com.braintrustdata.api.models.SpanType +import java.time.OffsetDateTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class LogServiceAsyncTest { + + @Test + fun feedback() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logServiceAsync = client.projects().logs() + + val feedbackResponseSchemaFuture = + logServiceAsync.feedback( + ProjectLogFeedbackParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback( + 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() + ) + .build() + ) + + val feedbackResponseSchema = feedbackResponseSchemaFuture.get() + feedbackResponseSchema.validate() + } + + @Test + fun fetch() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logServiceAsync = client.projects().logs() + + val fetchProjectLogsEventsResponseFuture = + logServiceAsync.fetch( + ProjectLogFetchParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + val fetchProjectLogsEventsResponse = fetchProjectLogsEventsResponseFuture.get() + fetchProjectLogsEventsResponse.validate() + } + + @Test + fun fetchPost() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logServiceAsync = client.projects().logs() + + val fetchProjectLogsEventsResponseFuture = + logServiceAsync.fetchPost( + ProjectLogFetchPostParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + val fetchProjectLogsEventsResponse = fetchProjectLogsEventsResponseFuture.get() + fetchProjectLogsEventsResponse.validate() + } + + @Test + fun insert() { + val client = + BraintrustOkHttpClientAsync.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logServiceAsync = client.projects().logs() + + val insertEventsResponseFuture = + logServiceAsync.insert( + ProjectLogInsertParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addEvent( + 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() + ) + .build() + ) + + val insertEventsResponse = insertEventsResponseFuture.get() + insertEventsResponse.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/AclServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/AclServiceTest.kt new file mode 100755 index 00000000..7838f8f7 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/AclServiceTest.kt @@ -0,0 +1,156 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.AclBatchUpdateParams +import com.braintrustdata.api.models.AclCreateParams +import com.braintrustdata.api.models.AclFindAndDeleteParams +import com.braintrustdata.api.models.AclListParams +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.Permission +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class AclServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclService = client.acls() + + val acl = + aclService.create( + AclCreateParams.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() + ) + + acl.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclService = client.acls() + + val acl = aclService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + acl.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclService = client.acls() + + val page = + aclService.list( + AclListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclService = client.acls() + + val acl = aclService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + acl.validate() + } + + @Test + fun batchUpdate() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclService = client.acls() + + val aclBatchUpdateResponse = + aclService.batchUpdate( + AclBatchUpdateParams.builder() + .addAddAcl( + 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() + ) + .addRemoveAcl( + 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() + ) + .build() + ) + + aclBatchUpdateResponse.validate() + } + + @Test + fun findAndDelete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aclService = client.acls() + + val acl = + aclService.findAndDelete( + AclFindAndDeleteParams.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() + ) + + acl.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceTest.kt new file mode 100644 index 00000000..911cdcdb --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/AiSecretServiceTest.kt @@ -0,0 +1,157 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.AiSecretCreateParams +import com.braintrustdata.api.models.AiSecretFindAndDeleteParams +import com.braintrustdata.api.models.AiSecretReplaceParams +import com.braintrustdata.api.models.AiSecretUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class AiSecretServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretService = client.aiSecrets() + + val aISecret = + aiSecretService.create( + AiSecretCreateParams.builder() + .name("name") + .metadata( + AiSecretCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + ) + + aISecret.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretService = client.aiSecrets() + + val aISecret = aiSecretService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + aISecret.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretService = client.aiSecrets() + + val aISecret = + aiSecretService.update( + AiSecretUpdateParams.builder() + .aiSecretId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .metadata( + AiSecretUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") + .secret("secret") + .type("type") + .build() + ) + + aISecret.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretService = client.aiSecrets() + + val page = aiSecretService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretService = client.aiSecrets() + + val aISecret = aiSecretService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + aISecret.validate() + } + + @Test + fun findAndDelete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretService = client.aiSecrets() + + val aISecret = + aiSecretService.findAndDelete( + AiSecretFindAndDeleteParams.builder().name("name").orgName("org_name").build() + ) + + aISecret.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val aiSecretService = client.aiSecrets() + + val aISecret = + aiSecretService.replace( + AiSecretReplaceParams.builder() + .name("name") + .metadata( + AiSecretReplaceParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .orgName("org_name") + .secret("secret") + .type("type") + .build() + ) + + aISecret.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceTest.kt new file mode 100644 index 00000000..471eaa44 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ApiKeyServiceTest.kt @@ -0,0 +1,72 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.ApiKeyCreateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ApiKeyServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyService = client.apiKeys() + + val createApiKeyOutput = + apiKeyService.create( + ApiKeyCreateParams.builder().name("name").orgName("org_name").build() + ) + + createApiKeyOutput.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyService = client.apiKeys() + + val apiKey = apiKeyService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + apiKey.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyService = client.apiKeys() + + val page = apiKeyService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val apiKeyService = client.apiKeys() + + val apiKey = apiKeyService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + apiKey.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceTest.kt old mode 100644 new mode 100755 index 7f1becc0..b2f77a0b --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/DatasetServiceTest.kt @@ -5,235 +5,258 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.TestServerExtension import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* -import com.braintrustdata.api.models.DatasetListParams +import com.braintrustdata.api.models.DatasetCreateParams +import com.braintrustdata.api.models.DatasetFeedbackParams +import com.braintrustdata.api.models.DatasetFetchParams +import com.braintrustdata.api.models.DatasetFetchPostParams +import com.braintrustdata.api.models.DatasetInsertParams +import com.braintrustdata.api.models.DatasetSummarizeParams +import com.braintrustdata.api.models.DatasetUpdateParams +import com.braintrustdata.api.models.FeedbackDatasetItem +import com.braintrustdata.api.models.InsertDatasetEvent +import com.braintrustdata.api.models.ObjectReference +import java.time.OffsetDateTime import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class DatasetServiceTest { +internal class DatasetServiceTest { @Test - fun callCreate() { + fun create() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() + val datasetService = client.datasets() + val dataset = datasetService.create( DatasetCreateParams.builder() - .name("string") - .description("string") + .name("x") .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .metadata( + DatasetCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) .build() ) - println(dataset) + dataset.validate() } @Test - fun callRetrieve() { + fun retrieve() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - val dataset = - datasetService.retrieve( - DatasetRetrieveParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - println(dataset) + val datasetService = client.datasets() + + val dataset = datasetService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + dataset.validate() } @Test - fun callUpdate() { + fun update() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() + val datasetService = client.datasets() + val dataset = datasetService.update( DatasetUpdateParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") - .description("string") + .description("description") + .metadata( + DatasetUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") .build() ) - println(dataset) + dataset.validate() } @Test - fun callList() { + fun list() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - val response = datasetService.list(DatasetListParams.builder().build()) - println(response) - response.objects().forEach { it.validate() } + val datasetService = client.datasets() + + val page = datasetService.list() + + page.response().validate() } @Test - fun callDelete() { + fun delete() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - val dataset = - datasetService.delete( - DatasetDeleteParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - println(dataset) + val datasetService = client.datasets() + + val dataset = datasetService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + dataset.validate() } @Test - fun callFeedback() { + fun feedback() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - datasetService.feedback( - DatasetFeedbackParams.builder() - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - DatasetFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .metadata(DatasetFeedbackParams.Feedback.Metadata.builder().build()) - .source(DatasetFeedbackParams.Feedback.Source.APP) + val datasetService = client.datasets() + + val feedbackResponseSchema = + datasetService.feedback( + DatasetFeedbackParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback( + FeedbackDatasetItem.builder() + .id("id") + .comment("comment") + .metadata( + FeedbackDatasetItem.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .source(FeedbackDatasetItem.Source.APP) + .addTag("string") .build() ) - ) - .build() - ) + .build() + ) + + feedbackResponseSchema.validate() } @Test - fun callFetch() { + fun fetch() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - val datasetFetchResponse = + val datasetService = client.datasets() + + val fetchDatasetEventsResponse = datasetService.fetch( DatasetFetchParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() ) - println(datasetFetchResponse) - datasetFetchResponse.validate() + + fetchDatasetEventsResponse.validate() } @Test - fun callFetchPost() { + fun fetchPost() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - val datasetFetchPostResponse = + val datasetService = client.datasets() + + val fetchDatasetEventsResponse = datasetService.fetchPost( DatasetFetchPostParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - DatasetFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(DatasetFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() ) - println(datasetFetchPostResponse) - datasetFetchPostResponse.validate() + + fetchDatasetEventsResponse.validate() } @Test - fun callInsert() { + fun insert() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - val datasetInsertResponse = + val datasetService = client.datasets() + + val insertEventsResponse = datasetService.insert( DatasetInsertParams.builder() .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - DatasetInsertParams.Event.ofInsertDatasetEventReplace( - DatasetInsertParams.Event.InsertDatasetEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .input(JsonValue.from(mapOf())) - .metadata( - DatasetInsertParams.Event.InsertDatasetEventReplace.Metadata - .builder() - .build() - ) - .output(JsonValue.from(mapOf())) + .addEvent( + 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() ) .build() ) - println(datasetInsertResponse) - datasetInsertResponse.validate() + + insertEventsResponse.validate() } @Test - fun callReplace() { + fun summarize() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val datasetService = client.dataset() - val dataset = - datasetService.replace( - DatasetReplaceParams.builder() - .name("string") - .description("string") - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + val datasetService = client.datasets() + + val summarizeDatasetResponse = + datasetService.summarize( + DatasetSummarizeParams.builder() + .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeData(true) .build() ) - println(dataset) - dataset.validate() + + summarizeDatasetResponse.validate() } } 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 new file mode 100644 index 00000000..04d3edce --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EnvVarServiceTest.kt @@ -0,0 +1,133 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.EnvVarCreateParams +import com.braintrustdata.api.models.EnvVarListParams +import com.braintrustdata.api.models.EnvVarObjectType +import com.braintrustdata.api.models.EnvVarReplaceParams +import com.braintrustdata.api.models.EnvVarUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class EnvVarServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarService = client.envVars() + + val envVar = + envVarService.create( + EnvVarCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarCreateParams.ObjectType.ORGANIZATION) + .value("value") + .build() + ) + + envVar.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarService = client.envVars() + + val envVar = envVarService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + envVar.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarService = client.envVars() + + val envVar = + envVarService.update( + EnvVarUpdateParams.builder() + .envVarId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .name("name") + .value("value") + .build() + ) + + envVar.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarService = client.envVars() + + val envVars = + envVarService.list( + EnvVarListParams.builder() + .envVarName("env_var_name") + .ids("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarObjectType.ORGANIZATION) + .build() + ) + + envVars.validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarService = client.envVars() + + val envVar = envVarService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + envVar.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val envVarService = client.envVars() + + val envVar = + envVarService.replace( + EnvVarReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(EnvVarReplaceParams.ObjectType.ORGANIZATION) + .value("value") + .build() + ) + + envVar.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EvalServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EvalServiceTest.kt new file mode 100644 index 00000000..2409d221 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/EvalServiceTest.kt @@ -0,0 +1,109 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.EvalCreateParams +import com.braintrustdata.api.models.RepoInfo +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class EvalServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val evalService = client.evals() + + val summarizeExperimentResponse = + evalService.create( + EvalCreateParams.builder() + .data( + EvalCreateParams.Data.DatasetId.builder() + .datasetId("dataset_id") + ._internalBtql( + EvalCreateParams.Data.DatasetId._InternalBtql + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .build() + ) + .projectId("project_id") + .addScore( + EvalCreateParams.Score.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .task( + EvalCreateParams.Task.FunctionId.builder() + .functionId("function_id") + .version("version") + .build() + ) + .baseExperimentId("base_experiment_id") + .baseExperimentName("base_experiment_name") + .experimentName("experiment_name") + .gitMetadataSettings( + EvalCreateParams.GitMetadataSettings.builder() + .collect(EvalCreateParams.GitMetadataSettings.Collect.ALL) + .addField(EvalCreateParams.GitMetadataSettings.Field.COMMIT) + .build() + ) + .isPublic(true) + .maxConcurrency(0.0) + .metadata( + EvalCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .parent( + EvalCreateParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + EvalCreateParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + EvalCreateParams.Parent.SpanParentStruct.PropagatedEvent.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + EvalCreateParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .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() + ) + .stream(true) + .timeout(0.0) + .trialCount(0.0) + .build() + ) + + summarizeExperimentResponse.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceTest.kt old mode 100644 new mode 100755 index f035c002..cccec10d --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ExperimentServiceTest.kt @@ -5,331 +5,334 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.TestServerExtension import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* -import com.braintrustdata.api.models.ExperimentListParams +import com.braintrustdata.api.models.ExperimentCreateParams +import com.braintrustdata.api.models.ExperimentFeedbackParams +import com.braintrustdata.api.models.ExperimentFetchParams +import com.braintrustdata.api.models.ExperimentFetchPostParams +import com.braintrustdata.api.models.ExperimentInsertParams +import com.braintrustdata.api.models.ExperimentSummarizeParams +import com.braintrustdata.api.models.ExperimentUpdateParams +import com.braintrustdata.api.models.FeedbackExperimentItem +import com.braintrustdata.api.models.InsertExperimentEvent +import com.braintrustdata.api.models.ObjectReference +import com.braintrustdata.api.models.RepoInfo +import com.braintrustdata.api.models.SpanAttributes +import com.braintrustdata.api.models.SpanType +import java.time.OffsetDateTime import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ExperimentServiceTest { +internal class ExperimentServiceTest { @Test - fun callCreate() { + fun create() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() + val experimentService = client.experiments() + val experiment = experimentService.create( ExperimentCreateParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentCreateParams.Metadata.builder().build()) - .name("string") + .datasetVersion("dataset_version") + .description("description") + .ensureNew(true) + .metadata( + ExperimentCreateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("x") .public_(true) .repoInfo( - ExperimentCreateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) .build() ) - println(experiment) + experiment.validate() } @Test - fun callRetrieve() { + fun retrieve() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - val experiment = - experimentService.retrieve( - ExperimentRetrieveParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - println(experiment) + val experimentService = client.experiments() + + val experiment = experimentService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + experiment.validate() } @Test - fun callUpdate() { + fun update() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() + val experimentService = client.experiments() + val experiment = experimentService.update( ExperimentUpdateParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentUpdateParams.Metadata.builder().build()) - .name("string") + .datasetVersion("dataset_version") + .description("description") + .metadata( + ExperimentUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .name("name") .public_(true) .repoInfo( - ExperimentUpdateParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") + RepoInfo.builder() + .authorEmail("author_email") + .authorName("author_name") + .branch("branch") + .commit("commit") + .commitMessage("commit_message") + .commitTime("commit_time") .dirty(true) - .gitDiff("string") - .tag("string") + .gitDiff("git_diff") + .tag("tag") .build() ) .build() ) - println(experiment) + experiment.validate() } @Test - fun callList() { + fun list() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - val response = experimentService.list(ExperimentListParams.builder().build()) - println(response) - response.objects().forEach { it.validate() } + val experimentService = client.experiments() + + val page = experimentService.list() + + page.response().validate() } @Test - fun callDelete() { + fun delete() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - val experiment = - experimentService.delete( - ExperimentDeleteParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - println(experiment) + val experimentService = client.experiments() + + val experiment = experimentService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + experiment.validate() } @Test - fun callFeedback() { + fun feedback() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - experimentService.feedback( - ExperimentFeedbackParams.builder() - .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - ExperimentFeedbackParams.Feedback.builder() - .id("string") - .comment("string") + val experimentService = client.experiments() + + val feedbackResponseSchema = + experimentService.feedback( + ExperimentFeedbackParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback( + FeedbackExperimentItem.builder() + .id("id") + .comment("comment") .expected(JsonValue.from(mapOf())) - .metadata(ExperimentFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ExperimentFeedbackParams.Feedback.Scores.builder().build()) - .source(ExperimentFeedbackParams.Feedback.Source.APP) + .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() ) - ) - .build() - ) + .build() + ) + + feedbackResponseSchema.validate() } @Test - fun callFetch() { + fun fetch() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - val experimentFetchResponse = + val experimentService = client.experiments() + + val fetchExperimentEventsResponse = experimentService.fetch( ExperimentFetchParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() ) - println(experimentFetchResponse) - experimentFetchResponse.validate() + + fetchExperimentEventsResponse.validate() } @Test - fun callFetchPost() { + fun fetchPost() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - val experimentFetchPostResponse = + val experimentService = client.experiments() + + val fetchExperimentEventsResponse = experimentService.fetchPost( ExperimentFetchPostParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - ExperimentFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ExperimentFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") .build() ) - println(experimentFetchPostResponse) - experimentFetchPostResponse.validate() + + fetchExperimentEventsResponse.validate() } @Test - fun callInsert() { + fun insert() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - val experimentInsertResponse = + val experimentService = client.experiments() + + val insertEventsResponse = experimentService.insert( ExperimentInsertParams.builder() .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ExperimentInsertParams.Event.ofInsertExperimentEventReplace( - ExperimentInsertParams.Event.InsertExperimentEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .datasetRecordId("string") - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .Metadata - .builder() - .build() - ) - .metrics( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .Scores - .builder() - .build() - ) - .spanAttributes( - ExperimentInsertParams.Event.InsertExperimentEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ExperimentInsertParams.Event - .InsertExperimentEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) + .addEvent( + 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() ) .build() ) - println(experimentInsertResponse) - experimentInsertResponse.validate() + + insertEventsResponse.validate() } @Test - fun callReplace() { + fun summarize() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val experimentService = client.experiment() - val experiment = - experimentService.replace( - ExperimentReplaceParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .baseExpId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .datasetVersion("string") - .description("string") - .metadata(ExperimentReplaceParams.Metadata.builder().build()) - .name("string") - .public_(true) - .repoInfo( - ExperimentReplaceParams.RepoInfo.builder() - .authorEmail("string") - .authorName("string") - .branch("string") - .commit("string") - .commitMessage("string") - .commitTime("string") - .dirty(true) - .gitDiff("string") - .tag("string") - .build() - ) + val experimentService = client.experiments() + + val summarizeExperimentResponse = + experimentService.summarize( + ExperimentSummarizeParams.builder() + .experimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .comparisonExperimentId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .summarizeScores(true) .build() ) - println(experiment) - experiment.validate() + + summarizeExperimentResponse.validate() } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceTest.kt new file mode 100755 index 00000000..d22bb379 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/FunctionServiceTest.kt @@ -0,0 +1,478 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.FunctionCreateParams +import com.braintrustdata.api.models.FunctionInvokeParams +import com.braintrustdata.api.models.FunctionReplaceParams +import com.braintrustdata.api.models.FunctionUpdateParams +import com.braintrustdata.api.models.PromptData +import com.braintrustdata.api.models.PromptOptions +import kotlin.jvm.optionals.getOrNull +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class FunctionServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionService = client.functions() + + val function = + functionService.create( + FunctionCreateParams.builder() + .functionData( + FunctionCreateParams.FunctionData.Prompt.builder() + .type(FunctionCreateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionCreateParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionCreateParams.FunctionType.LLM) + .origin( + FunctionCreateParams.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() + ) + + function.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionService = client.functions() + + val function = functionService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + function.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionService = client.functions() + + val function = + functionService.update( + FunctionUpdateParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .functionData( + FunctionUpdateParams.FunctionData.Prompt.builder() + .type(FunctionUpdateParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("name") + .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() + ) + + function.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionService = client.functions() + + val page = functionService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionService = client.functions() + + val function = functionService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + function.validate() + } + + @Test + fun invoke() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionService = client.functions() + + val response = + functionService.invoke( + FunctionInvokeParams.builder() + .functionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .expected(JsonValue.from(mapOf())) + .input(JsonValue.from(mapOf())) + .addMessage( + FunctionInvokeParams.Message.System.builder() + .role(FunctionInvokeParams.Message.System.Role.SYSTEM) + .content("content") + .name("name") + .build() + ) + .metadata( + FunctionInvokeParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .mode(FunctionInvokeParams.Mode.AUTO) + .parent( + FunctionInvokeParams.Parent.SpanParentStruct.builder() + .objectId("object_id") + .objectType( + FunctionInvokeParams.Parent.SpanParentStruct.ObjectType.PROJECT_LOGS + ) + .propagatedEvent( + FunctionInvokeParams.Parent.SpanParentStruct.PropagatedEvent + .builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .rowIds( + FunctionInvokeParams.Parent.SpanParentStruct.RowIds.builder() + .id("id") + .rootSpanId("root_span_id") + .spanId("span_id") + .build() + ) + .build() + ) + .stream(true) + .version("version") + .build() + ) + + val unwrappedResponse = response.getOrNull() + unwrappedResponse?.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val functionService = client.functions() + + val function = + functionService.replace( + FunctionReplaceParams.builder() + .functionData( + FunctionReplaceParams.FunctionData.Prompt.builder() + .type(FunctionReplaceParams.FunctionData.Prompt.Type.PROMPT) + .build() + ) + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionSchema( + FunctionReplaceParams.FunctionSchema.builder() + .parameters(JsonValue.from(mapOf())) + .returns(JsonValue.from(mapOf())) + .build() + ) + .functionType(FunctionReplaceParams.FunctionType.LLM) + .origin( + FunctionReplaceParams.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() + ) + + function.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/GroupServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/GroupServiceTest.kt new file mode 100755 index 00000000..480533ef --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/GroupServiceTest.kt @@ -0,0 +1,128 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.GroupCreateParams +import com.braintrustdata.api.models.GroupReplaceParams +import com.braintrustdata.api.models.GroupUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class GroupServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupService = client.groups() + + val group = + groupService.create( + GroupCreateParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + group.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupService = client.groups() + + val group = groupService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + group.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupService = client.groups() + + val group = + groupService.update( + GroupUpdateParams.builder() + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addRemoveMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + + group.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupService = client.groups() + + val page = groupService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupService = client.groups() + + val group = groupService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + group.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val groupService = client.groups() + + val group = + groupService.replace( + GroupReplaceParams.builder() + .name("x") + .description("description") + .addMemberGroup("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addMemberUser("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + group.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceTest.kt new file mode 100755 index 00000000..c387c81b --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/OrganizationServiceTest.kt @@ -0,0 +1,79 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.OrganizationUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class OrganizationServiceTest { + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationService = client.organizations() + + val organization = organizationService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + organization.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationService = client.organizations() + + val organization = + organizationService.update( + OrganizationUpdateParams.builder() + .organizationId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .apiUrl("api_url") + .isUniversalApi(true) + .name("name") + .proxyUrl("proxy_url") + .realtimeUrl("realtime_url") + .build() + ) + + organization.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationService = client.organizations() + + val page = organizationService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val organizationService = client.organizations() + + val organization = organizationService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + organization.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceTest.kt new file mode 100755 index 00000000..16d8e5ef --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectScoreServiceTest.kt @@ -0,0 +1,193 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.OnlineScoreConfig +import com.braintrustdata.api.models.ProjectScoreCategory +import com.braintrustdata.api.models.ProjectScoreConfig +import com.braintrustdata.api.models.ProjectScoreCreateParams +import com.braintrustdata.api.models.ProjectScoreReplaceParams +import com.braintrustdata.api.models.ProjectScoreType +import com.braintrustdata.api.models.ProjectScoreUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ProjectScoreServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreService = client.projectScores() + + val projectScore = + projectScoreService.create( + ProjectScoreCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + ) + + projectScore.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreService = client.projectScores() + + val projectScore = projectScoreService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + projectScore.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreService = client.projectScores() + + val projectScore = + projectScoreService.update( + ProjectScoreUpdateParams.builder() + .projectScoreId("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() + ) + .description("description") + .name("name") + .scoreType(ProjectScoreType.SLIDER) + .build() + ) + + projectScore.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreService = client.projectScores() + + val page = projectScoreService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreService = client.projectScores() + + val projectScore = projectScoreService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + projectScore.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectScoreService = client.projectScores() + + val projectScore = + projectScoreService.replace( + ProjectScoreReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .scoreType(ProjectScoreType.SLIDER) + .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() + ) + .description("description") + .build() + ) + + projectScore.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceTest.kt old mode 100644 new mode 100755 index cbcc620d..b179eb69 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectServiceTest.kt @@ -4,111 +4,105 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.TestServerExtension import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient -import com.braintrustdata.api.models.* -import com.braintrustdata.api.models.ProjectListParams +import com.braintrustdata.api.models.ProjectCreateParams +import com.braintrustdata.api.models.ProjectSettings +import com.braintrustdata.api.models.ProjectUpdateParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class ProjectServiceTest { +internal class ProjectServiceTest { @Test - fun callCreate() { + fun create() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val projectService = client.project() + val projectService = client.projects() + val project = projectService.create( - ProjectCreateParams.builder().name("string").orgName("string").build() + ProjectCreateParams.builder().name("x").orgName("org_name").build() ) - println(project) + project.validate() } @Test - fun callRetrieve() { + fun retrieve() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val projectService = client.project() - val project = - projectService.retrieve( - ProjectRetrieveParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - println(project) + val projectService = client.projects() + + val project = projectService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + project.validate() } @Test - fun callUpdate() { + fun update() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val projectService = client.project() + val projectService = client.projects() + val project = projectService.update( ProjectUpdateParams.builder() .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .name("string") + .name("name") + .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() + ) .build() ) - println(project) + project.validate() } @Test - fun callList() { + fun list() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val projectService = client.project() - val response = projectService.list(ProjectListParams.builder().build()) - println(response) - response.objects().forEach { it.validate() } - } + val projectService = client.projects() - @Test - fun callDelete() { - val client = - BraintrustOkHttpClient.builder() - .baseUrl(TestServerExtension.BASE_URL) - .apiKey("My API Key") - .build() - val projectService = client.project() - val project = - projectService.delete( - ProjectDeleteParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .build() - ) - println(project) - project.validate() + val page = projectService.list() + + page.response().validate() } @Test - fun callReplace() { + fun delete() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() - val projectService = client.project() - val project = - projectService.replace( - ProjectReplaceParams.builder().name("string").orgName("string").build() - ) - println(project) + val projectService = client.projects() + + val project = projectService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + project.validate() } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceTest.kt new file mode 100755 index 00000000..4244bf41 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ProjectTagServiceTest.kt @@ -0,0 +1,123 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.ProjectTagCreateParams +import com.braintrustdata.api.models.ProjectTagReplaceParams +import com.braintrustdata.api.models.ProjectTagUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ProjectTagServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagService = client.projectTags() + + val projectTag = + projectTagService.create( + ProjectTagCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + ) + + projectTag.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagService = client.projectTags() + + val projectTag = projectTagService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + projectTag.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagService = client.projectTags() + + val projectTag = + projectTagService.update( + ProjectTagUpdateParams.builder() + .projectTagId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .name("name") + .build() + ) + + projectTag.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagService = client.projectTags() + + val page = projectTagService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagService = client.projectTags() + + val projectTag = projectTagService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + projectTag.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val projectTagService = client.projectTags() + + val projectTag = + projectTagService.replace( + ProjectTagReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .color("color") + .description("description") + .build() + ) + + projectTag.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/PromptServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/PromptServiceTest.kt new file mode 100755 index 00000000..3544ab5c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/PromptServiceTest.kt @@ -0,0 +1,377 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.PromptCreateParams +import com.braintrustdata.api.models.PromptData +import com.braintrustdata.api.models.PromptOptions +import com.braintrustdata.api.models.PromptReplaceParams +import com.braintrustdata.api.models.PromptUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class PromptServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptService = client.prompts() + + val prompt = + promptService.create( + PromptCreateParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptCreateParams.FunctionType.LLM) + .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() + ) + + prompt.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptService = client.prompts() + + val prompt = promptService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + prompt.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptService = client.prompts() + + val prompt = + promptService.update( + PromptUpdateParams.builder() + .promptId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .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() + ) + .slug("slug") + .addTag("string") + .build() + ) + + prompt.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptService = client.prompts() + + val page = promptService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptService = client.prompts() + + val prompt = promptService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + prompt.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val promptService = client.prompts() + + val prompt = + promptService.replace( + PromptReplaceParams.builder() + .name("x") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .slug("x") + .description("description") + .functionType(PromptReplaceParams.FunctionType.LLM) + .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() + ) + + prompt.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/RoleServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/RoleServiceTest.kt new file mode 100755 index 00000000..3bab9b17 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/RoleServiceTest.kt @@ -0,0 +1,150 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.Permission +import com.braintrustdata.api.models.RoleCreateParams +import com.braintrustdata.api.models.RoleReplaceParams +import com.braintrustdata.api.models.RoleUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class RoleServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleService = client.roles() + + val role = + roleService.create( + RoleCreateParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleCreateParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + role.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleService = client.roles() + + val role = roleService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + role.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleService = client.roles() + + val role = + roleService.update( + RoleUpdateParams.builder() + .roleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addAddMemberPermission( + RoleUpdateParams.AddMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addAddMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("x") + .addRemoveMemberPermission( + RoleUpdateParams.RemoveMemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addRemoveMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + + role.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleService = client.roles() + + val page = roleService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleService = client.roles() + + val role = roleService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + role.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val roleService = client.roles() + + val role = + roleService.replace( + RoleReplaceParams.builder() + .name("x") + .description("description") + .addMemberPermission( + RoleReplaceParams.MemberPermission.builder() + .permission(Permission.CREATE) + .restrictObjectType(AclObjectType.ORGANIZATION) + .build() + ) + .addMemberRole("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .orgName("org_name") + .build() + ) + + role.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceTest.kt new file mode 100644 index 00000000..1d2c51ae --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/SpanIframeServiceTest.kt @@ -0,0 +1,126 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.SpanIframeCreateParams +import com.braintrustdata.api.models.SpanIframeReplaceParams +import com.braintrustdata.api.models.SpanIframeUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class SpanIframeServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeService = client.spanIframes() + + val spanIFrame = + spanIframeService.create( + SpanIframeCreateParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + ) + + spanIFrame.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeService = client.spanIframes() + + val spanIFrame = spanIframeService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + spanIFrame.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeService = client.spanIframes() + + val spanIFrame = + spanIframeService.update( + SpanIframeUpdateParams.builder() + .spanIframeId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .description("description") + .name("name") + .postMessage(true) + .url("url") + .build() + ) + + spanIFrame.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeService = client.spanIframes() + + val page = spanIframeService.list() + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeService = client.spanIframes() + + val spanIFrame = spanIframeService.delete("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + spanIFrame.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val spanIframeService = client.spanIframes() + + val spanIFrame = + spanIframeService.replace( + SpanIframeReplaceParams.builder() + .name("name") + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .url("url") + .description("description") + .postMessage(true) + .build() + ) + + spanIFrame.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceTest.kt old mode 100644 new mode 100755 index ab277bdc..de7c1385 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceTest.kt +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/TopLevelServiceTest.kt @@ -4,25 +4,21 @@ package com.braintrustdata.api.services.blocking import com.braintrustdata.api.TestServerExtension import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient -import com.braintrustdata.api.models.* -import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) -class TopLevelServiceTest { +internal class TopLevelServiceTest { @Test - fun callHelloWorld() { + fun helloWorld() { val client = BraintrustOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val topLevelService = client.topLevel() - val topLevelHelloWorldResponse = - topLevelService.helloWorld(TopLevelHelloWorldParams.builder().build()) - println(topLevelHelloWorldResponse) - assertThat(topLevelHelloWorldResponse).isNotBlank() + + topLevelService.helloWorld() } } diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/UserServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/UserServiceTest.kt new file mode 100755 index 00000000..6376460c --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/UserServiceTest.kt @@ -0,0 +1,40 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class UserServiceTest { + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val userService = client.users() + + val user = userService.retrieve("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + user.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val userService = client.users() + + val page = userService.list() + + page.response().validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ViewServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ViewServiceTest.kt new file mode 100755 index 00000000..4019925d --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/ViewServiceTest.kt @@ -0,0 +1,248 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.ViewCreateParams +import com.braintrustdata.api.models.ViewData +import com.braintrustdata.api.models.ViewDataSearch +import com.braintrustdata.api.models.ViewDeleteParams +import com.braintrustdata.api.models.ViewListParams +import com.braintrustdata.api.models.ViewOptions +import com.braintrustdata.api.models.ViewReplaceParams +import com.braintrustdata.api.models.ViewRetrieveParams +import com.braintrustdata.api.models.ViewUpdateParams +import java.time.OffsetDateTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class ViewServiceTest { + + @Test + fun create() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewService = client.views() + + val view = + viewService.create( + ViewCreateParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewCreateParams.ViewType.PROJECTS) + .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() + ) + + view.validate() + } + + @Test + fun retrieve() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewService = client.views() + + val view = + viewService.retrieve( + ViewRetrieveParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + view.validate() + } + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewService = client.views() + + val view = + viewService.update( + ViewUpdateParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .name("name") + .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() + ) + .viewType(ViewUpdateParams.ViewType.PROJECTS) + .build() + ) + + view.validate() + } + + @Test + fun list() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewService = client.views() + + val page = + viewService.list( + ViewListParams.builder() + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + page.response().validate() + } + + @Test + fun delete() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewService = client.views() + + val view = + viewService.delete( + ViewDeleteParams.builder() + .viewId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .build() + ) + + view.validate() + } + + @Test + fun replace() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val viewService = client.views() + + val view = + viewService.replace( + ViewReplaceParams.builder() + .name("name") + .objectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .objectType(AclObjectType.ORGANIZATION) + .viewType(ViewReplaceParams.ViewType.PROJECTS) + .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() + ) + + view.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceTest.kt new file mode 100644 index 00000000..cf30ad12 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/organizations/MemberServiceTest.kt @@ -0,0 +1,50 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking.organizations + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.models.OrganizationMemberUpdateParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class MemberServiceTest { + + @Test + fun update() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val memberService = client.organizations().members() + + val patchOrganizationMembersOutput = + memberService.update( + OrganizationMemberUpdateParams.builder() + .inviteUsers( + OrganizationMemberUpdateParams.InviteUsers.builder() + .addEmail("string") + .groupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addGroupId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .groupName("group_name") + .addGroupName("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .sendInviteEmails(true) + .build() + ) + .orgId("org_id") + .orgName("org_name") + .removeUsers( + OrganizationMemberUpdateParams.RemoveUsers.builder() + .addEmail("string") + .addId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .build() + ) + .build() + ) + + patchOrganizationMembersOutput.validate() + } +} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/project/LogServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/project/LogServiceTest.kt deleted file mode 100644 index 171a234f..00000000 --- a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/project/LogServiceTest.kt +++ /dev/null @@ -1,170 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.braintrustdata.api.services.blocking.project - -import com.braintrustdata.api.TestServerExtension -import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient -import com.braintrustdata.api.core.JsonValue -import com.braintrustdata.api.models.* -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith - -@ExtendWith(TestServerExtension::class) -class LogServiceTest { - - @Test - fun callFeedback() { - val client = - BraintrustOkHttpClient.builder() - .baseUrl(TestServerExtension.BASE_URL) - .apiKey("My API Key") - .build() - val logService = client.project().logs() - logService.feedback( - ProjectLogFeedbackParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .feedback( - listOf( - ProjectLogFeedbackParams.Feedback.builder() - .id("string") - .comment("string") - .expected(JsonValue.from(mapOf())) - .metadata(ProjectLogFeedbackParams.Feedback.Metadata.builder().build()) - .scores(ProjectLogFeedbackParams.Feedback.Scores.builder().build()) - .source(ProjectLogFeedbackParams.Feedback.Source.APP) - .build() - ) - ) - .build() - ) - } - - @Test - fun callFetch() { - val client = - BraintrustOkHttpClient.builder() - .baseUrl(TestServerExtension.BASE_URL) - .apiKey("My API Key") - .build() - val logService = client.project().logs() - val projectLogFetchResponse = - logService.fetch( - ProjectLogFetchParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) - .build() - ) - println(projectLogFetchResponse) - projectLogFetchResponse.validate() - } - - @Test - fun callFetchPost() { - val client = - BraintrustOkHttpClient.builder() - .baseUrl(TestServerExtension.BASE_URL) - .apiKey("My API Key") - .build() - val logService = client.project().logs() - val projectLogFetchPostResponse = - logService.fetchPost( - ProjectLogFetchPostParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .filters( - listOf( - ProjectLogFetchPostParams.Filter.builder() - .path(listOf("string")) - .type(ProjectLogFetchPostParams.Filter.Type.PATH_LOOKUP) - .value(JsonValue.from(mapOf())) - .build() - ) - ) - .limit(123L) - .maxRootSpanId("string") - .maxXactId(123L) - .version(123L) - .build() - ) - println(projectLogFetchPostResponse) - projectLogFetchPostResponse.validate() - } - - @Test - fun callInsert() { - val client = - BraintrustOkHttpClient.builder() - .baseUrl(TestServerExtension.BASE_URL) - .apiKey("My API Key") - .build() - val logService = client.project().logs() - val projectLogInsertResponse = - logService.insert( - ProjectLogInsertParams.builder() - .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .events( - listOf( - ProjectLogInsertParams.Event.ofInsertProjectLogsEventReplace( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace.builder() - .id("string") - ._isMerge(true) - ._objectDelete(true) - ._parentId("string") - .context( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Context - .builder() - .callerFilename("string") - .callerFunctionname("string") - .callerLineno(123L) - .build() - ) - .expected(JsonValue.from(mapOf())) - .input(JsonValue.from(mapOf())) - .metadata( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Metadata - .builder() - .build() - ) - .metrics( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Metrics - .builder() - .end(42.23) - .start(42.23) - .build() - ) - .output(JsonValue.from(mapOf())) - .scores( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .Scores - .builder() - .build() - ) - .spanAttributes( - ProjectLogInsertParams.Event.InsertProjectLogsEventReplace - .SpanAttributes - .builder() - .name("string") - .type( - ProjectLogInsertParams.Event - .InsertProjectLogsEventReplace - .SpanAttributes - .Type - .LLM - ) - .build() - ) - .build() - ) - ) - ) - .build() - ) - println(projectLogInsertResponse) - projectLogInsertResponse.validate() - } -} diff --git a/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceTest.kt b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceTest.kt new file mode 100644 index 00000000..d0ccaad0 --- /dev/null +++ b/braintrust-java-core/src/test/kotlin/com/braintrustdata/api/services/blocking/projects/LogServiceTest.kt @@ -0,0 +1,184 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.services.blocking.projects + +import com.braintrustdata.api.TestServerExtension +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.core.JsonValue +import com.braintrustdata.api.models.FeedbackProjectLogsItem +import com.braintrustdata.api.models.InsertProjectLogsEvent +import com.braintrustdata.api.models.ObjectReference +import com.braintrustdata.api.models.ProjectLogFeedbackParams +import com.braintrustdata.api.models.ProjectLogFetchParams +import com.braintrustdata.api.models.ProjectLogFetchPostParams +import com.braintrustdata.api.models.ProjectLogInsertParams +import com.braintrustdata.api.models.SpanAttributes +import com.braintrustdata.api.models.SpanType +import java.time.OffsetDateTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +internal class LogServiceTest { + + @Test + fun feedback() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logService = client.projects().logs() + + val feedbackResponseSchema = + logService.feedback( + ProjectLogFeedbackParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addFeedback( + 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() + ) + .build() + ) + + feedbackResponseSchema.validate() + } + + @Test + fun fetch() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logService = client.projects().logs() + + val fetchProjectLogsEventsResponse = + logService.fetch( + ProjectLogFetchParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + fetchProjectLogsEventsResponse.validate() + } + + @Test + fun fetchPost() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logService = client.projects().logs() + + val fetchProjectLogsEventsResponse = + logService.fetchPost( + ProjectLogFetchPostParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .cursor("cursor") + .limit(0L) + .maxRootSpanId("max_root_span_id") + .maxXactId("max_xact_id") + .version("version") + .build() + ) + + fetchProjectLogsEventsResponse.validate() + } + + @Test + fun insert() { + val client = + BraintrustOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("My API Key") + .build() + val logService = client.projects().logs() + + val insertEventsResponse = + logService.insert( + ProjectLogInsertParams.builder() + .projectId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .addEvent( + 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() + ) + .build() + ) + + insertEventsResponse.validate() + } +} diff --git a/braintrust-java-example/build.gradle.kts b/braintrust-java-example/build.gradle.kts new file mode 100644 index 00000000..7c705e6e --- /dev/null +++ b/braintrust-java-example/build.gradle.kts @@ -0,0 +1,28 @@ +plugins { + id("braintrust.java") + application +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(project(":braintrust-java")) +} + +tasks.withType().configureEach { + // Allow using more modern APIs, like `List.of` and `Map.of`, in examples. + options.release.set(9) +} + +application { + // Use `./gradlew :braintrust-java-example:run` to run `Main` + // Use `./gradlew :braintrust-java-example:run -Pexample=Something` to run `SomethingExample` + mainClass = "com.braintrustdata.api.example.${ + if (project.hasProperty("example")) + "${project.property("example")}Example" + else + "Main" + }" +} diff --git a/braintrust-java-lib/.keep b/braintrust-java-lib/.keep old mode 100644 new mode 100755 diff --git a/braintrust-java-proguard-test/build.gradle.kts b/braintrust-java-proguard-test/build.gradle.kts new file mode 100644 index 00000000..d17b1a54 --- /dev/null +++ b/braintrust-java-proguard-test/build.gradle.kts @@ -0,0 +1,101 @@ +plugins { + id("braintrust.kotlin") + id("com.gradleup.shadow") version "8.3.8" +} + +buildscript { + repositories { + google() + } + + dependencies { + classpath("com.guardsquare:proguard-gradle:7.4.2") + classpath("com.android.tools:r8:8.3.37") + } +} + +dependencies { + testImplementation(project(":braintrust-java")) + testImplementation(kotlin("test")) + testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.3") + testImplementation("org.assertj:assertj-core:3.25.3") + testImplementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.4") +} + +tasks.shadowJar { + from(sourceSets.test.get().output) + configurations = listOf(project.configurations.testRuntimeClasspath.get()) +} + +val proguardJarPath = "${layout.buildDirectory.get()}/libs/${project.name}-${project.version}-proguard.jar" +val proguardJar by tasks.registering(proguard.gradle.ProGuardTask::class) { + group = "verification" + dependsOn(tasks.shadowJar) + notCompatibleWithConfigurationCache("ProGuard") + + injars(tasks.shadowJar) + outjars(proguardJarPath) + printmapping("${layout.buildDirectory.get()}/proguard-mapping.txt") + + val javaHome = System.getProperty("java.home") + if (System.getProperty("java.version").startsWith("1.")) { + // Before Java 9, the runtime classes were packaged in a single jar file. + libraryjars("$javaHome/lib/rt.jar") + } else { + // As of Java 9, the runtime classes are packaged in modular jmod files. + libraryjars( + // Filters must be specified first, as a map. + mapOf("jarfilter" to "!**.jar", "filter" to "!module-info.class"), + "$javaHome/jmods/java.base.jmod" + ) + } + + configuration("./test.pro") + configuration("../braintrust-java-core/src/main/resources/META-INF/proguard/braintrust-java-core.pro") +} + +val testProGuard by tasks.registering(JavaExec::class) { + group = "verification" + dependsOn(proguardJar) + notCompatibleWithConfigurationCache("ProGuard") + + mainClass.set("com.braintrustdata.api.proguard.ProGuardCompatibilityTest") + classpath = files(proguardJarPath) +} + +val r8JarPath = "${layout.buildDirectory.get()}/libs/${project.name}-${project.version}-r8.jar" +val r8Jar by tasks.registering(JavaExec::class) { + group = "verification" + dependsOn(tasks.shadowJar) + notCompatibleWithConfigurationCache("R8") + + mainClass.set("com.android.tools.r8.R8") + classpath = buildscript.configurations["classpath"] + + args = listOf( + "--release", + "--classfile", + "--output", r8JarPath, + "--lib", System.getProperty("java.home"), + "--pg-conf", "./test.pro", + "--pg-conf", "../braintrust-java-core/src/main/resources/META-INF/proguard/braintrust-java-core.pro", + "--pg-map-output", "${layout.buildDirectory.get()}/r8-mapping.txt", + tasks.shadowJar.get().archiveFile.get().asFile.absolutePath, + ) +} + +val testR8 by tasks.registering(JavaExec::class) { + group = "verification" + dependsOn(r8Jar) + notCompatibleWithConfigurationCache("R8") + + mainClass.set("com.braintrustdata.api.proguard.ProGuardCompatibilityTest") + classpath = files(r8JarPath) +} + +tasks.test { + dependsOn(testProGuard) + dependsOn(testR8) + // We defer to the tests run via the ProGuard JAR. + enabled = false +} diff --git a/braintrust-java-proguard-test/src/test/kotlin/com/braintrustdata/api/proguard/ProGuardCompatibilityTest.kt b/braintrust-java-proguard-test/src/test/kotlin/com/braintrustdata/api/proguard/ProGuardCompatibilityTest.kt new file mode 100644 index 00000000..a33fc6ed --- /dev/null +++ b/braintrust-java-proguard-test/src/test/kotlin/com/braintrustdata/api/proguard/ProGuardCompatibilityTest.kt @@ -0,0 +1,128 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.braintrustdata.api.proguard + +import com.braintrustdata.api.client.okhttp.BraintrustOkHttpClient +import com.braintrustdata.api.core.jsonMapper +import com.braintrustdata.api.models.AclObjectType +import com.braintrustdata.api.models.Project +import com.braintrustdata.api.models.ProjectListPageResponse +import com.braintrustdata.api.models.ProjectSettings +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.time.OffsetDateTime +import kotlin.reflect.full.memberFunctions +import kotlin.reflect.jvm.javaMethod +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class ProGuardCompatibilityTest { + + companion object { + + @JvmStatic + fun main(args: Array) { + // To debug that we're using the right JAR. + val jarPath = this::class.java.getProtectionDomain().codeSource.location + println("JAR being used: $jarPath") + + // We have to manually run the test methods instead of using the JUnit runner because it + // seems impossible to get working with R8. + val test = ProGuardCompatibilityTest() + test::class + .memberFunctions + .asSequence() + .filter { function -> + function.javaMethod?.isAnnotationPresent(Test::class.java) == true + } + .forEach { it.call(test) } + } + } + + @Test + fun proguardRules() { + val rulesFile = + javaClass.classLoader.getResourceAsStream("META-INF/proguard/braintrust-java-core.pro") + + assertThat(rulesFile).isNotNull() + } + + @Test + fun client() { + val client = BraintrustOkHttpClient.builder().apiKey("My API Key").build() + + assertThat(client).isNotNull() + assertThat(client.topLevel()).isNotNull() + assertThat(client.projects()).isNotNull() + assertThat(client.experiments()).isNotNull() + assertThat(client.datasets()).isNotNull() + assertThat(client.prompts()).isNotNull() + assertThat(client.roles()).isNotNull() + assertThat(client.groups()).isNotNull() + assertThat(client.acls()).isNotNull() + assertThat(client.users()).isNotNull() + assertThat(client.projectScores()).isNotNull() + assertThat(client.projectTags()).isNotNull() + assertThat(client.spanIframes()).isNotNull() + assertThat(client.functions()).isNotNull() + assertThat(client.views()).isNotNull() + assertThat(client.organizations()).isNotNull() + assertThat(client.apiKeys()).isNotNull() + assertThat(client.aiSecrets()).isNotNull() + assertThat(client.envVars()).isNotNull() + assertThat(client.evals()).isNotNull() + } + + @Test + fun projectListPageResponseRoundtrip() { + 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) + } + + @Test + fun aclObjectTypeRoundtrip() { + val jsonMapper = jsonMapper() + val aclObjectType = AclObjectType.ORGANIZATION + + val roundtrippedAclObjectType = + jsonMapper.readValue( + jsonMapper.writeValueAsString(aclObjectType), + jacksonTypeRef(), + ) + + assertThat(roundtrippedAclObjectType).isEqualTo(aclObjectType) + } +} diff --git a/braintrust-java-proguard-test/test.pro b/braintrust-java-proguard-test/test.pro new file mode 100644 index 00000000..a55227f1 --- /dev/null +++ b/braintrust-java-proguard-test/test.pro @@ -0,0 +1,9 @@ +# Specify the entrypoint where ProGuard starts to determine what's reachable. +-keep class com.braintrustdata.api.proguard.** { *; } + +# For the testing framework. +-keep class org.junit.** { *; } + +# Many warnings don't apply for our testing purposes. +-dontnote +-dontwarn \ No newline at end of file diff --git a/braintrust-java/build.gradle.kts b/braintrust-java/build.gradle.kts old mode 100644 new mode 100755 index ccb65cda..2f936950 --- a/braintrust-java/build.gradle.kts +++ b/braintrust-java/build.gradle.kts @@ -6,3 +6,24 @@ plugins { dependencies { api(project(":braintrust-java-client-okhttp")) } + +// Redefine `dokkaJavadoc` to: +// - Depend on the root project's task for merging the docs of all the projects +// - Forward that task's output to this task's output +tasks.named("dokkaJavadoc").configure { + actions.clear() + + val dokkaJavadocCollector = rootProject.tasks["dokkaJavadocCollector"] + dependsOn(dokkaJavadocCollector) + + val outputDirectory = project.layout.buildDirectory.dir("dokka/javadoc") + doLast { + copy { + from(dokkaJavadocCollector.outputs.files) + into(outputDirectory) + duplicatesStrategy = DuplicatesStrategy.INCLUDE + } + } + + outputs.dir(outputDirectory) +} diff --git a/build.gradle.kts b/build.gradle.kts index 79951bc7..30ce5a5e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,20 +1,36 @@ -//plugins { -// id("io.github.gradle-nexus.publish-plugin") version "1.1.0" -//} -// +plugins { + id("org.jetbrains.dokka") version "2.0.0" +} + +repositories { + mavenCentral() +} + allprojects { group = "com.braintrustdata.api" - version = "0.2.0" // x-release-please-version + version = "0.9.0" // x-release-please-version +} + +subprojects { + // These are populated with dependencies by `buildSrc` scripts. + tasks.register("format") { + group = "Verification" + description = "Formats all source files." + } + tasks.register("lint") { + group = "Verification" + description = "Verifies all source files are formatted." + } + apply(plugin = "org.jetbrains.dokka") +} + +subprojects { + apply(plugin = "org.jetbrains.dokka") +} + +// Avoid race conditions between `dokkaJavadocCollector` and `dokkaJavadocJar` tasks +tasks.named("dokkaJavadocCollector").configure { + subprojects.flatMap { it.tasks } + .filter { it.project.name != "braintrust-java" && it.name == "dokkaJavadocJar" } + .forEach { mustRunAfter(it) } } -// -//nexusPublishing { -// repositories { -// sonatype { -// nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) -// snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) -// -// username.set(System.getenv("SONATYPE_USERNAME")) -// password.set(System.getenv("SONATYPE_PASSWORD")) -// } -// } -//} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 4fa7f6bf..c6dc92ec 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -1,12 +1,15 @@ plugins { `kotlin-dsl` + kotlin("jvm") version "1.9.20" + id("com.vanniktech.maven.publish") version "0.28.0" } repositories { gradlePluginPortal() + mavenCentral() } dependencies { - implementation("com.diffplug.spotless:spotless-plugin-gradle:6.12.0") - implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20") + 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 old mode 100644 new mode 100755 index 0a33327c..70fc33f4 --- a/buildSrc/src/main/kotlin/braintrust.java.gradle.kts +++ b/buildSrc/src/main/kotlin/braintrust.java.gradle.kts @@ -1,45 +1,28 @@ -import com.diffplug.gradle.spotless.SpotlessExtension import org.gradle.api.tasks.testing.logging.TestExceptionFormat -import java.util.Locale plugins { `java-library` - id("com.diffplug.spotless") } repositories { mavenCentral() } -configure { - withJavadocJar() - withSourcesJar() -} - -configure { - java { - importOrder() - removeUnusedImports() - palantirJavaFormat() - } -} - java { toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } -tasks.withType { +tasks.withType().configureEach { options.compilerArgs.add("-Werror") options.release.set(8) } -tasks.named("javadocJar") { - setZip64(true) -} - -tasks.jar { +tasks.named("jar") { manifest { attributes(mapOf( "Implementation-Title" to project.name, @@ -48,10 +31,97 @@ tasks.jar { } } -tasks.test { +tasks.withType().configureEach { useJUnitPlatform() + // Run tests in parallel to some degree. + maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).coerceAtLeast(1) + forkEvery = 100 + testLogging { exceptionFormat = TestExceptionFormat.FULL } } + +val palantir by configurations.creating +dependencies { + palantir("com.palantir.javaformat:palantir-java-format:2.73.0") +} + +fun registerPalantir( + name: String, + description: String, +) { + val javaName = "${name}Java" + tasks.register(javaName) { + group = "Verification" + this.description = description + + classpath = palantir + mainClass = "com.palantir.javaformat.java.Main" + + // Avoid an `IllegalAccessError` on Java 9+. + jvmArgs( + "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", + "--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", + ) + + // Use paths relative to the current module. + val argumentFile = + project.layout.buildDirectory.file("palantir-$name-args.txt").get().asFile + val lastRunTimeFile = + project.layout.buildDirectory.file("palantir-$name-last-run.txt").get().asFile + + // Read the time when this task was last executed for this module (if ever). + val lastRunTime = lastRunTimeFile.takeIf { it.exists() }?.readText()?.toLongOrNull() ?: 0L + + // Use a `fileTree` relative to the module's source directory. + val javaFiles = project.fileTree("src") { include("**/*.java") } + + // Determine if any files need to be formatted or linted and continue only if there is at least + // one file. + onlyIf { javaFiles.any { it.lastModified() > lastRunTime } } + + inputs.files(javaFiles) + + doFirst { + // Create the argument file and set the preferred formatting style. + argumentFile.parentFile.mkdirs() + argumentFile.writeText("--palantir\n") + + if (name == "lint") { + // For lint, do a dry run, so no files are modified. Set the exit code to 1 (instead of + // the default 0) if any files need to be formatted, indicating that linting has failed. + argumentFile.appendText("--dry-run\n") + argumentFile.appendText("--set-exit-if-changed\n") + } else { + // `--dry-run` and `--replace` (for in-place formatting) are mutually exclusive. + argumentFile.appendText("--replace\n") + } + + // Write the modified files to the argument file. + javaFiles.filter { it.lastModified() > lastRunTime } + .forEach { argumentFile.appendText("${it.absolutePath}\n") } + } + + doLast { + // Record the last execution time for later up-to-date checking. + lastRunTimeFile.writeText(System.currentTimeMillis().toString()) + } + + // Pass the argument file using the @ symbol + args = listOf("@${argumentFile.absolutePath}") + + outputs.upToDateWhen { javaFiles.none { it.lastModified() > lastRunTime } } + } + + tasks.named(name) { + dependsOn(tasks.named(javaName)) + } +} + +registerPalantir(name = "format", description = "Formats all Java source files.") +registerPalantir(name = "lint", description = "Verifies all Java source files are formatted.") diff --git a/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts b/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts old mode 100644 new mode 100755 index bd86e6cc..832189a3 --- a/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts +++ b/buildSrc/src/main/kotlin/braintrust.kotlin.gradle.kts @@ -1,27 +1,106 @@ -import com.diffplug.gradle.spotless.SpotlessExtension -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion plugins { id("braintrust.java") kotlin("jvm") } +repositories { + mavenCentral() +} + kotlin { jvmToolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } -} -configure { - kotlin { - ktfmt().kotlinlangStyle() + compilerOptions { + freeCompilerArgs = listOf( + "-Xjvm-default=all", + "-Xjdk-release=1.8", + // Suppress deprecation warnings because we may still reference and test deprecated members. + // TODO: Replace with `-Xsuppress-warning=DEPRECATION` once we use Kotlin compiler 2.1.0+. + "-nowarn", + ) + jvmTarget.set(JvmTarget.JVM_1_8) + languageVersion.set(KotlinVersion.KOTLIN_1_8) + apiVersion.set(KotlinVersion.KOTLIN_1_8) + coreLibrariesVersion = "1.8.0" } } -tasks.withType { - kotlinOptions { - allWarningsAsErrors = true - freeCompilerArgs = listOf("-Xjvm-default=all", "-Xjdk-release=1.8") - jvmTarget = "1.8" +tasks.withType().configureEach { + systemProperty("junit.jupiter.execution.parallel.enabled", true) + systemProperty("junit.jupiter.execution.parallel.mode.default", "concurrent") +} + +val ktfmt by configurations.creating +dependencies { + ktfmt("com.facebook:ktfmt:0.56") +} + +fun registerKtfmt( + name: String, + description: String, +) { + val kotlinName = "${name}Kotlin" + tasks.register(kotlinName) { + group = "Verification" + this.description = description + + classpath = ktfmt + mainClass = "com.facebook.ktfmt.cli.Main" + + // Use paths relative to the current module. + val argumentFile = project.layout.buildDirectory.file("ktfmt-$name-args.txt").get().asFile + val lastRunTimeFile = + project.layout.buildDirectory.file("ktfmt-$name-last-run.txt").get().asFile + + // Read the time when this task was last executed for this module (if ever). + val lastRunTime = lastRunTimeFile.takeIf { it.exists() }?.readText()?.toLongOrNull() ?: 0L + + // Use a `fileTree` relative to the module's source directory. + val kotlinFiles = project.fileTree("src") { include("**/*.kt") } + + // Determine if any files need to be formatted or linted and continue only if there is at least + // one file (otherwise Ktfmt will fail). + onlyIf { kotlinFiles.any { it.lastModified() > lastRunTime } } + + inputs.files(kotlinFiles) + + doFirst { + // Create the argument file and set the preferred formatting style. + argumentFile.parentFile.mkdirs() + argumentFile.writeText("--kotlinlang-style\n") + + if (name == "lint") { + // For lint, do a dry run, so no files are modified. Set the exit code to 1 (instead of + // the default 0) if any files need to be formatted, indicating that linting has failed. + argumentFile.appendText("--dry-run\n") + argumentFile.appendText("--set-exit-if-changed\n") + } + + // Write the modified files to the argument file. + kotlinFiles.filter { it.lastModified() > lastRunTime } + .forEach { argumentFile.appendText("${it.absolutePath}\n") } + } + + doLast { + // Record the last execution time for later up-to-date checking. + lastRunTimeFile.writeText(System.currentTimeMillis().toString()) + } + + // Pass the argument file using the @ symbol + args = listOf("@${argumentFile.absolutePath}") + + outputs.upToDateWhen { kotlinFiles.none { it.lastModified() > lastRunTime } } + } + + tasks.named(name) { + dependsOn(tasks.named(kotlinName)) } } + +registerKtfmt(name = "format", description = "Formats all Kotlin source files.") +registerKtfmt(name = "lint", description = "Verifies all Kotlin source files are formatted.") diff --git a/buildSrc/src/main/kotlin/braintrust.publish.gradle.kts b/buildSrc/src/main/kotlin/braintrust.publish.gradle.kts old mode 100644 new mode 100755 index 3f9c308a..747be62d --- a/buildSrc/src/main/kotlin/braintrust.publish.gradle.kts +++ b/buildSrc/src/main/kotlin/braintrust.publish.gradle.kts @@ -1,80 +1,59 @@ -import org.gradle.api.publish.PublishingExtension -import org.gradle.api.publish.maven.MavenPublication -import org.gradle.kotlin.dsl.configure -import org.gradle.kotlin.dsl.create -import org.gradle.kotlin.dsl.get +import com.vanniktech.maven.publish.JavadocJar +import com.vanniktech.maven.publish.KotlinJvm +import com.vanniktech.maven.publish.MavenPublishBaseExtension +import com.vanniktech.maven.publish.SonatypeHost plugins { - `maven-publish` - `signing` + id("com.vanniktech.maven.publish") } -configure { - publications { - create("maven") { - from(components["java"]) - - pom { - name.set("Braintrust Data API") - description.set("API specification for the backend data server. The API is hosted globally at\nhttps://api.braintrustdata.com or in your own environment. The v1 API is\ncurrently in preview mode and unstable until March 1, 2024. We may make\nbackwards incompatible changes before then, as we learn from our users.") - url.set("https://www.braintrustdata.com/docs/api/spec") - - licenses { - license { - name.set("Apache-2.0") - } - } - - developers { - developer { - name.set("Braintrust") - email.set("info@braintrustdata.com") - } - } +repositories { + gradlePluginPortal() + mavenCentral() +} - scm { - connection.set("scm:git:git://github.com/braintrustdata/braintrust-java.git") - developerConnection.set("scm:git:git://github.com/braintrustdata/braintrust-java.git") - url.set("https://github.com/braintrustdata/braintrust-java") - } +extra["signingInMemoryKey"] = System.getenv("GPG_SIGNING_KEY") +extra["signingInMemoryKeyId"] = System.getenv("GPG_SIGNING_KEY_ID") +extra["signingInMemoryKeyPassword"] = System.getenv("GPG_SIGNING_PASSWORD") + +configure { + signAllPublications() + publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) + + coordinates(project.group.toString(), project.name, project.version.toString()) + configure( + KotlinJvm( + javadocJar = JavadocJar.Dokka("dokkaJavadoc"), + sourcesJar = true, + ) + ) + + pom { + name.set("Braintrust API") + description.set("API specification for the backend data server. The API is hosted globally at\nhttps://api.braintrust.dev or in your own environment.\n\nYou can access the OpenAPI spec for this API at\nhttps://github.com/braintrustdata/braintrust-openapi.") + url.set("https://www.braintrustdata.com/docs/api/spec") + + licenses { + license { + name.set("Apache-2.0") + } + } - versionMapping { - allVariants { - fromResolutionResult() - } - } + developers { + developer { + name.set("Braintrust") + email.set("info@braintrustdata.com") } } + + scm { + connection.set("scm:git:git://github.com/braintrustdata/braintrust-java.git") + developerConnection.set("scm:git:git://github.com/braintrustdata/braintrust-java.git") + url.set("https://github.com/braintrustdata/braintrust-java") + } } } -//signing { -// val signingKeyId = System.getenv("GPG_SIGNING_KEY_ID")?.ifBlank { null } -// val signingKey = System.getenv("GPG_SIGNING_KEY")?.ifBlank { null } -// val signingPassword = System.getenv("GPG_SIGNING_PASSWORD")?.ifBlank { null } -// if (signingKey != null && signingPassword != null) { -// useInMemoryPgpKeys( -// signingKeyId, -// signingKey, -// signingPassword, -// ) -// sign(publishing.publications["maven"]) -// } -//} -// -//tasks.publish { -// dependsOn(":closeAndReleaseSonatypeStagingRepository") -//} - -publishing { - repositories { - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/braintrustdata/braintrust-java") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } - } +tasks.withType().configureEach { + isZip64 = true } diff --git a/examples/.keep b/examples/.keep old mode 100644 new mode 100755 diff --git a/gradle.properties b/gradle.properties index a3bc58f2..6680f9ce 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,18 @@ org.gradle.caching=true -org.gradle.jvmargs=-Xmx4g +org.gradle.configuration-cache=true org.gradle.parallel=true -kotlin.daemon.jvmargs=-Xmx4g +org.gradle.daemon=false +# These options improve our compilation and test performance. They are inherited by the Kotlin daemon. +org.gradle.jvmargs=\ + -Xms2g \ + -Xmx8g \ + -XX:+UseParallelGC \ + -XX:InitialCodeCacheSize=256m \ + -XX:ReservedCodeCacheSize=1G \ + -XX:MetaspaceSize=512m \ + -XX:MaxMetaspaceSize=2G \ + -XX:TieredStopAtLevel=1 \ + -XX:GCTimeRatio=4 \ + -XX:CICompilerCount=4 \ + -XX:+OptimizeStringConcat \ + -XX:+UseStringDeduplication diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 41d9927a..a4b76b95 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e1bef7e8..cea7a793 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c7873..f3b75f3b 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +82,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,22 +133,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -193,11 +200,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ @@ -205,6 +216,12 @@ set -- \ org.gradle.wrapper.GradleWrapperMain \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index 107acd32..9d21a218 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/release-please-config.json b/release-please-config.json old mode 100644 new mode 100755 diff --git a/scripts/build b/scripts/build new file mode 100755 index 00000000..f4063482 --- /dev/null +++ b/scripts/build @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +echo "==> Building classes" +./gradlew build testClasses -x test diff --git a/scripts/fast-format b/scripts/fast-format new file mode 100755 index 00000000..1b3bc473 --- /dev/null +++ b/scripts/fast-format @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +set -euo pipefail + +echo "Script started with $# arguments" +echo "Arguments: $*" +echo "Script location: $(dirname "$0")" + +cd "$(dirname "$0")/.." +echo "Changed to directory: $(pwd)" + +if [ $# -eq 0 ]; then + echo "Usage: $0 [additional-formatter-args...]" + echo "The file should contain one file path per line" + exit 1 +fi + +FILE_LIST="$1" + +echo "Looking for file: $FILE_LIST" + +if [ ! -f "$FILE_LIST" ]; then + echo "Error: File '$FILE_LIST' not found" + exit 1 +fi + +if ! command -v ktfmt-fast-format &> /dev/null; then + echo "Error: ktfmt-fast-format not found" + exit 1 +fi + +# Process Kotlin files +echo "==> Looking for Kotlin files" +kt_files=$(grep -E '\.kt$' "$FILE_LIST" | grep -v './buildSrc/build/' || true) +echo "==> Done looking for Kotlin files" + +if [[ -n "$kt_files" ]]; then + echo "==> will format Kotlin files" + echo "$kt_files" | tr '\n' '\0' | xargs -0 ktfmt-fast-format --kotlinlang-style "$@" +else + echo "No Kotlin files to format -- expected outcome during incremental formatting" +fi + +# TODO(mbudayr): support palantir-java-format +# Process Java files +# grep -E '\.java$' "$FILE_LIST" | grep -v './buildSrc/build/' | tr '\n' '\0' | xargs -0 -r palantir-java-format --palantir --replace "$@" diff --git a/scripts/format b/scripts/format new file mode 100755 index 00000000..65db1769 --- /dev/null +++ b/scripts/format @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if command -v ktfmt &> /dev/null; then + echo "==> Running ktfmt" + ./scripts/kotlin-format +else + echo "==> Running gradlew formatKotlin" + ./gradlew formatKotlin +fi + +if command -v palantir-java-format &> /dev/null; then + echo "==> Running palantir-java-format" + ./scripts/java-format +else + echo "==> Running gradlew formatJava" + ./gradlew formatJava +fi diff --git a/scripts/java-format b/scripts/java-format new file mode 100755 index 00000000..ad5febce --- /dev/null +++ b/scripts/java-format @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +find . -name "*.java" -not -path "./buildSrc/build/*" -print0 | xargs -0 -r palantir-java-format --palantir --replace "$@" diff --git a/scripts/kotlin-format b/scripts/kotlin-format new file mode 100755 index 00000000..3b8be9ea --- /dev/null +++ b/scripts/kotlin-format @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +find . -name "*.kt" -not -path "./buildSrc/build/*" -print0 | xargs -0 -r ktfmt --kotlinlang-style "$@" diff --git a/scripts/lint b/scripts/lint new file mode 100755 index 00000000..dbc8f776 --- /dev/null +++ b/scripts/lint @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +echo "==> Running lints" + +if command -v ktfmt &> /dev/null; then + echo "==> Checking ktfmt" + ./scripts/kotlin-format --dry-run --set-exit-if-changed +else + echo "==> Running gradlew lintKotlin" + ./gradlew lintKotlin +fi + +if command -v palantir-java-format &> /dev/null; then + echo "==> Checking palantir-java-format" + ./scripts/java-format --dry-run --set-exit-if-changed +else + echo "==> Running gradlew lintJava" + ./gradlew lintJava +fi diff --git a/scripts/mock b/scripts/mock new file mode 100755 index 00000000..0b28f6ea --- /dev/null +++ b/scripts/mock @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if [[ -n "$1" && "$1" != '--'* ]]; then + URL="$1" + shift +else + URL="$(grep 'openapi_spec_url' .stats.yml | cut -d' ' -f2)" +fi + +# Check if the URL is empty +if [ -z "$URL" ]; then + echo "Error: No OpenAPI spec path/url provided or found in .stats.yml" + exit 1 +fi + +echo "==> Starting mock server with URL ${URL}" + +# Run prism mock on the given spec +if [ "$1" == "--daemon" ]; then + npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log & + + # Wait for server to come online + echo -n "Waiting for server" + while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do + echo -n "." + sleep 0.1 + done + + if grep -q "✖ fatal" ".prism.log"; then + cat .prism.log + exit 1 + fi + + echo +else + npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" +fi diff --git a/scripts/test b/scripts/test new file mode 100755 index 00000000..047bc1db --- /dev/null +++ b/scripts/test @@ -0,0 +1,56 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +NC='\033[0m' # No Color + +function prism_is_running() { + curl --silent "http://localhost:4010" >/dev/null 2>&1 +} + +kill_server_on_port() { + pids=$(lsof -t -i tcp:"$1" || echo "") + if [ "$pids" != "" ]; then + kill "$pids" + echo "Stopped $pids." + fi +} + +function is_overriding_api_base_url() { + [ -n "$TEST_API_BASE_URL" ] +} + +if ! is_overriding_api_base_url && ! prism_is_running ; then + # When we exit this script, make sure to kill the background mock server process + trap 'kill_server_on_port 4010' EXIT + + # Start the dev server + ./scripts/mock --daemon +fi + +if is_overriding_api_base_url ; then + echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" + echo +elif ! prism_is_running ; then + echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" + echo -e "running against your OpenAPI spec." + echo + echo -e "To run the server, pass in the path or url of your OpenAPI" + echo -e "spec to the prism command:" + echo + echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}" + echo + + exit 1 +else + echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" + echo +fi + +echo "==> Running tests" +./gradlew test "$@" diff --git a/settings.gradle.kts b/settings.gradle.kts index be7364dc..dce7cbbe 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,6 +1,14 @@ rootProject.name = "braintrust-java-root" -include("braintrust-java") -include("braintrust-java-client-okhttp") -include("braintrust-java-core") -include("braintrust-java-example") +val projectNames = rootDir.listFiles() + ?.asSequence() + .orEmpty() + .filter { file -> + file.isDirectory && + file.name.startsWith("braintrust-java") && + file.listFiles()?.asSequence().orEmpty().any { it.name == "build.gradle.kts" } + } + .map { it.name } + .toList() +println("projects: $projectNames") +projectNames.forEach { include(it) }