diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..9b09257 --- /dev/null +++ b/.env.example @@ -0,0 +1,9 @@ +# Langfuse API credentials for integration tests. +# Copy this file to .env and fill in your values. +# +# Required prompts in the Langfuse project: +# - "test-chat-prompt" : chat type, at least one message with role + content +# - "test-text-prompt" : text type, non-empty prompt text +LANGFUSE_PUBLIC_KEY=pk-lf-... +LANGFUSE_SECRET_KEY=sk-lf-... +LANGFUSE_HOST=https://cloud.langfuse.com diff --git a/.gitignore b/.gitignore index ae8516b..cb37348 100644 --- a/.gitignore +++ b/.gitignore @@ -36,4 +36,7 @@ build/ .vscode/ ### Mac OS ### -.DS_Store \ No newline at end of file +.DS_Store + +### Environment ### +.env \ No newline at end of file diff --git a/README.md b/README.md index e014735..c9b5a0f 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,41 @@ try { } ``` +## Testing + +### Unit tests + +Unit tests (deserialization, query string mapping) run without any credentials: + +```bash +mvn test +``` + +### Integration tests + +Integration tests connect to a real Langfuse project. They require credentials and are excluded from `mvn test`. + +1. Copy `.env.example` to `.env` and fill in your API keys: + ```bash + cp .env.example .env + ``` + +2. Ensure your Langfuse project contains the following prompts: + - `test-chat-prompt` — chat type, at least one message with `role` and `content` + - `test-text-prompt` — text type, non-empty prompt text + +3. Run all tests (unit + integration): + ```bash + mvn verify + ``` + + Or run only integration tests: + ```bash + mvn failsafe:integration-test + ``` + +Integration tests skip gracefully when credentials are absent. + ## Drafting a Release Run `./mvnw release:prepare -DreleaseVersion=` with the version you want to create. @@ -78,6 +113,6 @@ To publish to Maven Central, you need to configure the following secrets in your ``` 3. Generate the new client code using `npx fern-api generate --api server`. 4. Manually set the `package` across all files to `com.langfuse.client`. -5. Overwrite `this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + encodedToken);` to `Basic` in LangfuseClientBuilder.java. +5. Overwrite `this.clientOptionsBuilder.addHeader("Authorization", "Basic " + encodedToken);` to `Basic` in com.langfuse.client.LangfuseClientBuilder.java. 6. Adjust Javadoc strings with HTML properties as the apidocs package does not support them. 7. Commit the changes in langfuse-java and push them to the repository. diff --git a/pom.xml b/pom.xml index e16e668..28944e8 100644 --- a/pom.xml +++ b/pom.xml @@ -118,6 +118,37 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + integration + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.2.5 + + integration + + **/*Test.java + + + + + + integration-test + verify + + + + @@ -157,5 +188,29 @@ junit-jupiter-api ${junit.version} + + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + test + + + + + org.assertj + assertj-core + 3.25.3 + test + + + + + io.github.cdimascio + dotenv-java + 3.0.2 + test + diff --git a/src/main/java/com/langfuse/client/.fern/metadata.json b/src/main/java/com/langfuse/client/.fern/metadata.json new file mode 100644 index 0000000..166c4b3 --- /dev/null +++ b/src/main/java/com/langfuse/client/.fern/metadata.json @@ -0,0 +1,8 @@ +{ + "cliVersion": "3.88.0", + "generatorName": "fernapi/fern-java-sdk", + "generatorVersion": "3.38.1", + "generatorConfig": { + "client-class-name": "LangfuseClient" + } +} \ No newline at end of file diff --git a/src/main/java/com/langfuse/client/AsyncLangfuseClient.java b/src/main/java/com/langfuse/client/AsyncLangfuseClient.java new file mode 100644 index 0000000..bde0858 --- /dev/null +++ b/src/main/java/com/langfuse/client/AsyncLangfuseClient.java @@ -0,0 +1,227 @@ +package com.langfuse.client; /** + * This file was auto-generated by Fern from our API Definition. + */ + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.Suppliers; +import java.util.function.Supplier; +import com.langfuse.client.resources.annotationqueues.AsyncAnnotationQueuesClient; +import com.langfuse.client.resources.blobstorageintegrations.AsyncBlobStorageIntegrationsClient; +import com.langfuse.client.resources.comments.AsyncCommentsClient; +import com.langfuse.client.resources.datasetitems.AsyncDatasetItemsClient; +import com.langfuse.client.resources.datasetrunitems.AsyncDatasetRunItemsClient; +import com.langfuse.client.resources.datasets.AsyncDatasetsClient; +import com.langfuse.client.resources.health.AsyncHealthClient; +import com.langfuse.client.resources.ingestion.AsyncIngestionClient; +import com.langfuse.client.resources.llmconnections.AsyncLlmConnectionsClient; +import com.langfuse.client.resources.media.AsyncMediaClient; +import com.langfuse.client.resources.metrics.AsyncMetricsClient; +import com.langfuse.client.resources.metricsv2.AsyncMetricsV2Client; +import com.langfuse.client.resources.models.AsyncModelsClient; +import com.langfuse.client.resources.observations.AsyncObservationsClient; +import com.langfuse.client.resources.observationsv2.AsyncObservationsV2Client; +import com.langfuse.client.resources.opentelemetry.AsyncOpentelemetryClient; +import com.langfuse.client.resources.organizations.AsyncOrganizationsClient; +import com.langfuse.client.resources.projects.AsyncProjectsClient; +import com.langfuse.client.resources.prompts.AsyncPromptsClient; +import com.langfuse.client.resources.promptversion.AsyncPromptVersionClient; +import com.langfuse.client.resources.scim.AsyncScimClient; +import com.langfuse.client.resources.score.AsyncScoreClient; +import com.langfuse.client.resources.scoreconfigs.AsyncScoreConfigsClient; +import com.langfuse.client.resources.scorev2.AsyncScoreV2Client; +import com.langfuse.client.resources.sessions.AsyncSessionsClient; +import com.langfuse.client.resources.trace.AsyncTraceClient; + +public class AsyncLangfuseClient { + protected final ClientOptions clientOptions; + + protected final Supplier annotationQueuesClient; + + protected final Supplier blobStorageIntegrationsClient; + + protected final Supplier commentsClient; + + protected final Supplier datasetItemsClient; + + protected final Supplier datasetRunItemsClient; + + protected final Supplier datasetsClient; + + protected final Supplier healthClient; + + protected final Supplier ingestionClient; + + protected final Supplier llmConnectionsClient; + + protected final Supplier mediaClient; + + protected final Supplier metricsV2Client; + + protected final Supplier metricsClient; + + protected final Supplier modelsClient; + + protected final Supplier observationsV2Client; + + protected final Supplier observationsClient; + + protected final Supplier opentelemetryClient; + + protected final Supplier organizationsClient; + + protected final Supplier projectsClient; + + protected final Supplier promptVersionClient; + + protected final Supplier promptsClient; + + protected final Supplier scimClient; + + protected final Supplier scoreConfigsClient; + + protected final Supplier scoreV2Client; + + protected final Supplier scoreClient; + + protected final Supplier sessionsClient; + + protected final Supplier traceClient; + + public AsyncLangfuseClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.annotationQueuesClient = Suppliers.memoize(() -> new AsyncAnnotationQueuesClient(clientOptions)); + this.blobStorageIntegrationsClient = Suppliers.memoize(() -> new AsyncBlobStorageIntegrationsClient(clientOptions)); + this.commentsClient = Suppliers.memoize(() -> new AsyncCommentsClient(clientOptions)); + this.datasetItemsClient = Suppliers.memoize(() -> new AsyncDatasetItemsClient(clientOptions)); + this.datasetRunItemsClient = Suppliers.memoize(() -> new AsyncDatasetRunItemsClient(clientOptions)); + this.datasetsClient = Suppliers.memoize(() -> new AsyncDatasetsClient(clientOptions)); + this.healthClient = Suppliers.memoize(() -> new AsyncHealthClient(clientOptions)); + this.ingestionClient = Suppliers.memoize(() -> new AsyncIngestionClient(clientOptions)); + this.llmConnectionsClient = Suppliers.memoize(() -> new AsyncLlmConnectionsClient(clientOptions)); + this.mediaClient = Suppliers.memoize(() -> new AsyncMediaClient(clientOptions)); + this.metricsV2Client = Suppliers.memoize(() -> new AsyncMetricsV2Client(clientOptions)); + this.metricsClient = Suppliers.memoize(() -> new AsyncMetricsClient(clientOptions)); + this.modelsClient = Suppliers.memoize(() -> new AsyncModelsClient(clientOptions)); + this.observationsV2Client = Suppliers.memoize(() -> new AsyncObservationsV2Client(clientOptions)); + this.observationsClient = Suppliers.memoize(() -> new AsyncObservationsClient(clientOptions)); + this.opentelemetryClient = Suppliers.memoize(() -> new AsyncOpentelemetryClient(clientOptions)); + this.organizationsClient = Suppliers.memoize(() -> new AsyncOrganizationsClient(clientOptions)); + this.projectsClient = Suppliers.memoize(() -> new AsyncProjectsClient(clientOptions)); + this.promptVersionClient = Suppliers.memoize(() -> new AsyncPromptVersionClient(clientOptions)); + this.promptsClient = Suppliers.memoize(() -> new AsyncPromptsClient(clientOptions)); + this.scimClient = Suppliers.memoize(() -> new AsyncScimClient(clientOptions)); + this.scoreConfigsClient = Suppliers.memoize(() -> new AsyncScoreConfigsClient(clientOptions)); + this.scoreV2Client = Suppliers.memoize(() -> new AsyncScoreV2Client(clientOptions)); + this.scoreClient = Suppliers.memoize(() -> new AsyncScoreClient(clientOptions)); + this.sessionsClient = Suppliers.memoize(() -> new AsyncSessionsClient(clientOptions)); + this.traceClient = Suppliers.memoize(() -> new AsyncTraceClient(clientOptions)); + } + + public AsyncAnnotationQueuesClient annotationQueues() { + return this.annotationQueuesClient.get(); + } + + public AsyncBlobStorageIntegrationsClient blobStorageIntegrations() { + return this.blobStorageIntegrationsClient.get(); + } + + public AsyncCommentsClient comments() { + return this.commentsClient.get(); + } + + public AsyncDatasetItemsClient datasetItems() { + return this.datasetItemsClient.get(); + } + + public AsyncDatasetRunItemsClient datasetRunItems() { + return this.datasetRunItemsClient.get(); + } + + public AsyncDatasetsClient datasets() { + return this.datasetsClient.get(); + } + + public AsyncHealthClient health() { + return this.healthClient.get(); + } + + public AsyncIngestionClient ingestion() { + return this.ingestionClient.get(); + } + + public AsyncLlmConnectionsClient llmConnections() { + return this.llmConnectionsClient.get(); + } + + public AsyncMediaClient media() { + return this.mediaClient.get(); + } + + public AsyncMetricsV2Client metricsV2() { + return this.metricsV2Client.get(); + } + + public AsyncMetricsClient metrics() { + return this.metricsClient.get(); + } + + public AsyncModelsClient models() { + return this.modelsClient.get(); + } + + public AsyncObservationsV2Client observationsV2() { + return this.observationsV2Client.get(); + } + + public AsyncObservationsClient observations() { + return this.observationsClient.get(); + } + + public AsyncOpentelemetryClient opentelemetry() { + return this.opentelemetryClient.get(); + } + + public AsyncOrganizationsClient organizations() { + return this.organizationsClient.get(); + } + + public AsyncProjectsClient projects() { + return this.projectsClient.get(); + } + + public AsyncPromptVersionClient promptVersion() { + return this.promptVersionClient.get(); + } + + public AsyncPromptsClient prompts() { + return this.promptsClient.get(); + } + + public AsyncScimClient scim() { + return this.scimClient.get(); + } + + public AsyncScoreConfigsClient scoreConfigs() { + return this.scoreConfigsClient.get(); + } + + public AsyncScoreV2Client scoreV2() { + return this.scoreV2Client.get(); + } + + public AsyncScoreClient score() { + return this.scoreClient.get(); + } + + public AsyncSessionsClient sessions() { + return this.sessionsClient.get(); + } + + public AsyncTraceClient trace() { + return this.traceClient.get(); + } + + public static AsyncLangfuseClientBuilder builder() { + return new AsyncLangfuseClientBuilder(); + } +} diff --git a/src/main/java/com/langfuse/client/AsyncLangfuseClientBuilder.java b/src/main/java/com/langfuse/client/AsyncLangfuseClientBuilder.java new file mode 100644 index 0000000..fc92d63 --- /dev/null +++ b/src/main/java/com/langfuse/client/AsyncLangfuseClientBuilder.java @@ -0,0 +1,261 @@ +package com.langfuse.client; /** + * This file was auto-generated by Fern from our API Definition. + */ + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.Environment; +import java.lang.Integer; +import java.lang.String; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import okhttp3.OkHttpClient; + +public class AsyncLangfuseClientBuilder { + private Optional timeout = Optional.empty(); + + private Optional maxRetries = Optional.empty(); + + private final Map customHeaders = new HashMap<>(); + + private String username = null; + + private String password = null; + + private String xLangfuseSdkName = null; + + private String xLangfuseSdkVersion = null; + + private String xLangfusePublicKey = null; + + private Environment environment; + + private OkHttpClient httpClient; + + public AsyncLangfuseClientBuilder credentials(String username, String password) { + this.username = username; + this.password = password; + return this; + } + + /** + * Sets xLangfuseSdkName + */ + public AsyncLangfuseClientBuilder xLangfuseSdkName(String xLangfuseSdkName) { + this.xLangfuseSdkName = xLangfuseSdkName; + return this; + } + + /** + * Sets xLangfuseSdkVersion + */ + public AsyncLangfuseClientBuilder xLangfuseSdkVersion(String xLangfuseSdkVersion) { + this.xLangfuseSdkVersion = xLangfuseSdkVersion; + return this; + } + + /** + * Sets xLangfusePublicKey + */ + public AsyncLangfuseClientBuilder xLangfusePublicKey(String xLangfusePublicKey) { + this.xLangfusePublicKey = xLangfusePublicKey; + return this; + } + + public AsyncLangfuseClientBuilder url(String url) { + this.environment = Environment.custom(url); + return this; + } + + /** + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. + */ + public AsyncLangfuseClientBuilder timeout(int timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public AsyncLangfuseClientBuilder maxRetries(int maxRetries) { + this.maxRetries = Optional.of(maxRetries); + return this; + } + + /** + * Sets the underlying OkHttp client + */ + public AsyncLangfuseClientBuilder httpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Add a custom header to be sent with all requests. + * For headers that need to be computed dynamically or conditionally, use the setAdditional() method override instead. + * + * @param name The header name + * @param value The header value + * @return This builder for method chaining + */ + public AsyncLangfuseClientBuilder addHeader(String name, String value) { + this.customHeaders.put(name, value); + return this; + } + + protected ClientOptions buildClientOptions() { + ClientOptions.Builder builder = ClientOptions.builder(); + setEnvironment(builder); + setAuthentication(builder); + setCustomHeaders(builder); + setHttpClient(builder); + setTimeouts(builder); + setRetries(builder); + for (Map.Entry header : this.customHeaders.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + setAdditional(builder); + return builder.build(); + } + + /** + * Sets the environment configuration for the client. + * Override this method to modify URLs or add environment-specific logic. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setEnvironment(ClientOptions.Builder builder) { + builder.environment(this.environment); + } + + /** + * Override this method to customize authentication. + * This method is called during client options construction to set up authentication headers. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+   * @Override
+   * protected void setAuthentication(ClientOptions.Builder builder) {
+   *     super.setAuthentication(builder); // Keep existing auth
+   *     builder.addHeader("X-API-Key", this.apiKey);
+   * }
+   * }
+ */ + protected void setAuthentication(ClientOptions.Builder builder) { + if (this.username != null && this.password != null) { + String unencodedToken = this.username + ":" + this.password; + String encodedToken = Base64.getEncoder().encodeToString(unencodedToken.getBytes()); + builder.addHeader("Authorization", "Basic " + encodedToken); + } + } + + /** + * Override this method to add or modify custom headers. + * This method is called during client options construction to set up custom headers defined in the API. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+   * @Override
+   * protected void setCustomHeaders(ClientOptions.Builder builder) {
+   *     super.setCustomHeaders(builder); // Keep existing headers
+   *     builder.addHeader("X-Trace-ID", generateTraceId());
+   * }
+   * }
+ */ + protected void setCustomHeaders(ClientOptions.Builder builder) { + if (this.xLangfuseSdkName != null) { + builder.addHeader("X-Langfuse-Sdk-Name", this.xLangfuseSdkName); + } + if (this.xLangfuseSdkVersion != null) { + builder.addHeader("X-Langfuse-Sdk-Version", this.xLangfuseSdkVersion); + } + if (this.xLangfusePublicKey != null) { + builder.addHeader("X-Langfuse-Public-Key", this.xLangfusePublicKey); + } + } + + /** + * Sets the request timeout configuration. + * Override this method to customize timeout behavior. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setTimeouts(ClientOptions.Builder builder) { + if (this.timeout.isPresent()) { + builder.timeout(this.timeout.get()); + } + } + + /** + * Sets the retry configuration for failed requests. + * Override this method to implement custom retry strategies. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setRetries(ClientOptions.Builder builder) { + if (this.maxRetries.isPresent()) { + builder.maxRetries(this.maxRetries.get()); + } + } + + /** + * Sets the OkHttp client configuration. + * Override this method to customize HTTP client behavior (interceptors, connection pools, etc). + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setHttpClient(ClientOptions.Builder builder) { + if (this.httpClient != null) { + builder.httpClient(this.httpClient); + } + } + + /** + * Override this method to add any additional configuration to the client. + * This method is called at the end of the configuration chain, allowing you to add + * custom headers, modify settings, or perform any other client customization. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+   * @Override
+   * protected void setAdditional(ClientOptions.Builder builder) {
+   *     builder.addHeader("X-Request-ID", () -> UUID.randomUUID().toString());
+   *     builder.addHeader("X-Client-Version", "1.0.0");
+   * }
+   * }
+ */ + protected void setAdditional(ClientOptions.Builder builder) { + } + + /** + * Override this method to add custom validation logic before the client is built. + * This method is called at the beginning of the build() method to ensure the configuration is valid. + * Throw an exception to prevent client creation if validation fails. + * + * Example: + *
{@code
+   * @Override
+   * protected void validateConfiguration() {
+   *     super.validateConfiguration(); // Run parent validations
+   *     if (tenantId == null || tenantId.isEmpty()) {
+   *         throw new IllegalStateException("tenantId is required");
+   *     }
+   * }
+   * }
+ */ + protected void validateConfiguration() { + } + + public AsyncLangfuseClient build() { + validateConfiguration(); + return new AsyncLangfuseClient(buildClientOptions()); + } +} diff --git a/src/main/java/com/langfuse/client/LangfuseClientBuilder.java b/src/main/java/com/langfuse/client/LangfuseClientBuilder.java index 4a3ce8f..1b9cdbb 100644 --- a/src/main/java/com/langfuse/client/LangfuseClientBuilder.java +++ b/src/main/java/com/langfuse/client/LangfuseClientBuilder.java @@ -6,12 +6,20 @@ import com.langfuse.client.core.ClientOptions; import com.langfuse.client.core.Environment; +import java.lang.Integer; import java.lang.String; import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import okhttp3.OkHttpClient; -public final class LangfuseClientBuilder { - private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); +public class LangfuseClientBuilder { + private Optional timeout = Optional.empty(); + + private Optional maxRetries = Optional.empty(); + + private final Map customHeaders = new HashMap<>(); private String username = null; @@ -25,6 +33,8 @@ public final class LangfuseClientBuilder { private Environment environment; + private OkHttpClient httpClient; + public LangfuseClientBuilder credentials(String username, String password) { this.username = username; this.password = password; @@ -61,10 +71,18 @@ public LangfuseClientBuilder url(String url) { } /** - * Sets the timeout (in seconds) for the client + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. */ public LangfuseClientBuilder timeout(int timeout) { - this.clientOptionsBuilder.timeout(timeout); + this.timeout = Optional.of(timeout); + return this; + } + + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public LangfuseClientBuilder maxRetries(int maxRetries) { + this.maxRetries = Optional.of(maxRetries); return this; } @@ -72,24 +90,174 @@ public LangfuseClientBuilder timeout(int timeout) { * Sets the underlying OkHttp client */ public LangfuseClientBuilder httpClient(OkHttpClient httpClient) { - this.clientOptionsBuilder.httpClient(httpClient); + this.httpClient = httpClient; return this; } - public LangfuseClient build() { - String unencodedToken = username + ":" + password; - String encodedToken = Base64.getEncoder().encodeToString(unencodedToken.getBytes()); - this.clientOptionsBuilder.addHeader("Authorization", "Basic " + encodedToken); - if (xLangfuseSdkName != null) { - this.clientOptionsBuilder.addHeader("X-Langfuse-Sdk-Name", this.xLangfuseSdkName); + /** + * Add a custom header to be sent with all requests. + * For headers that need to be computed dynamically or conditionally, use the setAdditional() method override instead. + * + * @param name The header name + * @param value The header value + * @return This builder for method chaining + */ + public LangfuseClientBuilder addHeader(String name, String value) { + this.customHeaders.put(name, value); + return this; + } + + protected ClientOptions buildClientOptions() { + ClientOptions.Builder builder = ClientOptions.builder(); + setEnvironment(builder); + setAuthentication(builder); + setCustomHeaders(builder); + setHttpClient(builder); + setTimeouts(builder); + setRetries(builder); + for (Map.Entry header : this.customHeaders.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + setAdditional(builder); + return builder.build(); + } + + /** + * Sets the environment configuration for the client. + * Override this method to modify URLs or add environment-specific logic. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setEnvironment(ClientOptions.Builder builder) { + builder.environment(this.environment); + } + + /** + * Override this method to customize authentication. + * This method is called during client options construction to set up authentication headers. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+   * @Override
+   * protected void setAuthentication(ClientOptions.Builder builder) {
+   *     super.setAuthentication(builder); // Keep existing auth
+   *     builder.addHeader("X-API-Key", this.apiKey);
+   * }
+   * }
+ */ + protected void setAuthentication(ClientOptions.Builder builder) { + if (this.username != null && this.password != null) { + String unencodedToken = this.username + ":" + this.password; + String encodedToken = Base64.getEncoder().encodeToString(unencodedToken.getBytes()); + builder.addHeader("Authorization", "Basic " + encodedToken); + } + } + + /** + * Override this method to add or modify custom headers. + * This method is called during client options construction to set up custom headers defined in the API. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+   * @Override
+   * protected void setCustomHeaders(ClientOptions.Builder builder) {
+   *     super.setCustomHeaders(builder); // Keep existing headers
+   *     builder.addHeader("X-Trace-ID", generateTraceId());
+   * }
+   * }
+ */ + protected void setCustomHeaders(ClientOptions.Builder builder) { + if (this.xLangfuseSdkName != null) { + builder.addHeader("X-Langfuse-Sdk-Name", this.xLangfuseSdkName); + } + if (this.xLangfuseSdkVersion != null) { + builder.addHeader("X-Langfuse-Sdk-Version", this.xLangfuseSdkVersion); } - if (xLangfuseSdkVersion != null) { - this.clientOptionsBuilder.addHeader("X-Langfuse-Sdk-Version", this.xLangfuseSdkVersion); + if (this.xLangfusePublicKey != null) { + builder.addHeader("X-Langfuse-Public-Key", this.xLangfusePublicKey); + } + } + + /** + * Sets the request timeout configuration. + * Override this method to customize timeout behavior. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setTimeouts(ClientOptions.Builder builder) { + if (this.timeout.isPresent()) { + builder.timeout(this.timeout.get()); } - if (xLangfusePublicKey != null) { - this.clientOptionsBuilder.addHeader("X-Langfuse-Public-Key", this.xLangfusePublicKey); + } + + /** + * Sets the retry configuration for failed requests. + * Override this method to implement custom retry strategies. + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setRetries(ClientOptions.Builder builder) { + if (this.maxRetries.isPresent()) { + builder.maxRetries(this.maxRetries.get()); } - clientOptionsBuilder.environment(this.environment); - return new LangfuseClient(clientOptionsBuilder.build()); + } + + /** + * Sets the OkHttp client configuration. + * Override this method to customize HTTP client behavior (interceptors, connection pools, etc). + * + * @param builder The ClientOptions.Builder to configure + */ + protected void setHttpClient(ClientOptions.Builder builder) { + if (this.httpClient != null) { + builder.httpClient(this.httpClient); + } + } + + /** + * Override this method to add any additional configuration to the client. + * This method is called at the end of the configuration chain, allowing you to add + * custom headers, modify settings, or perform any other client customization. + * + * @param builder The ClientOptions.Builder to configure + * + * Example: + *
{@code
+   * @Override
+   * protected void setAdditional(ClientOptions.Builder builder) {
+   *     builder.addHeader("X-Request-ID", () -> UUID.randomUUID().toString());
+   *     builder.addHeader("X-Client-Version", "1.0.0");
+   * }
+   * }
+ */ + protected void setAdditional(ClientOptions.Builder builder) { + } + + /** + * Override this method to add custom validation logic before the client is built. + * This method is called at the beginning of the build() method to ensure the configuration is valid. + * Throw an exception to prevent client creation if validation fails. + * + * Example: + *
{@code
+   * @Override
+   * protected void validateConfiguration() {
+   *     super.validateConfiguration(); // Run parent validations
+   *     if (tenantId == null || tenantId.isEmpty()) {
+   *         throw new IllegalStateException("tenantId is required");
+   *     }
+   * }
+   * }
+ */ + protected void validateConfiguration() { + } + + public LangfuseClient build() { + validateConfiguration(); + return new LangfuseClient(buildClientOptions()); } } diff --git a/src/main/java/com/langfuse/client/core/ClientOptions.java b/src/main/java/com/langfuse/client/core/ClientOptions.java index b67fe34..258c653 100644 --- a/src/main/java/com/langfuse/client/core/ClientOptions.java +++ b/src/main/java/com/langfuse/client/core/ClientOptions.java @@ -4,9 +4,11 @@ package com.langfuse.client.core; +import java.lang.Integer; import java.lang.String; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import okhttp3.OkHttpClient; @@ -22,15 +24,19 @@ public final class ClientOptions { private final int timeout; + private final int maxRetries; + private ClientOptions(Environment environment, Map headers, - Map> headerSuppliers, OkHttpClient httpClient, int timeout) { + Map> headerSuppliers, OkHttpClient httpClient, int timeout, + int maxRetries) { this.environment = environment; this.headers = new HashMap<>(); this.headers.putAll(headers); - this.headers.putAll(new HashMap() {{put("X-Fern-Language", "JAVA");put("X-Fern-SDK-Name", "com.langfuse.fern:langfuse-sdk");put("X-Fern-SDK-Version", "0.0.2841");}}); + this.headers.putAll(new HashMap() {{put("X-Fern-Language", "JAVA");put("X-Fern-SDK-Name", "com.langfuse.fern:langfuse-sdk");put("X-Fern-SDK-Version", "0.0.3585");}}); this.headerSuppliers = headerSuppliers; this.httpClient = httpClient; this.timeout = timeout; + this.maxRetries = maxRetries; } public Environment environment() { @@ -48,6 +54,13 @@ public Map headers(RequestOptions requestOptions) { return values; } + public int timeout(RequestOptions requestOptions) { + if (requestOptions == null) { + return this.timeout; + } + return requestOptions.getTimeout().orElse(this.timeout); + } + public OkHttpClient httpClient() { return this.httpClient; } @@ -59,23 +72,26 @@ public OkHttpClient httpClientWithTimeout(RequestOptions requestOptions) { return this.httpClient.newBuilder().callTimeout(requestOptions.getTimeout().get(), requestOptions.getTimeoutTimeUnit()).connectTimeout(0, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS).readTimeout(0, TimeUnit.SECONDS).build(); } + public int maxRetries() { + return this.maxRetries; + } + public static Builder builder() { return new Builder(); } - public static final class Builder { + public static class Builder { private Environment environment; private final Map headers = new HashMap<>(); private final Map> headerSuppliers = new HashMap<>(); - private int timeout = 60; + private int maxRetries = 2; - private OkHttpClient httpClient = new OkHttpClient.Builder() - .addInterceptor(new RetryInterceptor(3)) - .callTimeout(this.timeout, TimeUnit.SECONDS) - .build(); + private Optional timeout = Optional.empty(); + + private OkHttpClient httpClient = null; public Builder environment(Environment environment) { this.environment = environment; @@ -96,17 +112,59 @@ public Builder addHeader(String key, Supplier value) { * Override the timeout in seconds. Defaults to 60 seconds. */ public Builder timeout(int timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(Optional timeout) { this.timeout = timeout; return this; } + /** + * Override the maximum number of retries. Defaults to 2 retries. + */ + public Builder maxRetries(int maxRetries) { + this.maxRetries = maxRetries; + return this; + } + public Builder httpClient(OkHttpClient httpClient) { this.httpClient = httpClient; return this; } public ClientOptions build() { - return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout); + OkHttpClient.Builder httpClientBuilder = this.httpClient != null ? this.httpClient.newBuilder() : new OkHttpClient.Builder(); + + if (this.httpClient != null) { + timeout.ifPresent(timeout -> httpClientBuilder.callTimeout(timeout, TimeUnit.SECONDS).connectTimeout(0, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS).readTimeout(0, TimeUnit.SECONDS)); + } + else { + httpClientBuilder.callTimeout(this.timeout.orElse(60), TimeUnit.SECONDS).connectTimeout(0, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS).readTimeout(0, TimeUnit.SECONDS).addInterceptor(new RetryInterceptor(this.maxRetries)); + } + + this.httpClient = httpClientBuilder.build(); + this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); + + return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get(), this.maxRetries); + } + + /** + * Create a new Builder initialized with values from an existing ClientOptions + */ + public static Builder from(ClientOptions clientOptions) { + Builder builder = new Builder(); + builder.environment = clientOptions.environment(); + builder.timeout = Optional.of(clientOptions.timeout(null)); + builder.httpClient = clientOptions.httpClient(); + builder.headers.putAll(clientOptions.headers); + builder.headerSuppliers.putAll(clientOptions.headerSuppliers); + builder.maxRetries = clientOptions.maxRetries(); + return builder; } } } diff --git a/src/main/java/com/langfuse/client/core/InputStreamRequestBody.java b/src/main/java/com/langfuse/client/core/InputStreamRequestBody.java index 07dd285..88ce922 100644 --- a/src/main/java/com/langfuse/client/core/InputStreamRequestBody.java +++ b/src/main/java/com/langfuse/client/core/InputStreamRequestBody.java @@ -9,7 +9,6 @@ import java.util.Objects; import okhttp3.MediaType; import okhttp3.RequestBody; -import okhttp3.internal.Util; import okio.BufferedSink; import okio.Okio; import okio.Source; @@ -69,12 +68,8 @@ public long contentLength() throws IOException { */ @Override public void writeTo(BufferedSink sink) throws IOException { - Source source = null; - try { - source = Okio.source(inputStream); + try (Source source = Okio.source(inputStream)) { sink.writeAll(source); - } finally { - Util.closeQuietly(Objects.requireNonNull(source)); } } } \ No newline at end of file diff --git a/src/main/java/com/langfuse/client/core/LangfuseClientApiException.java b/src/main/java/com/langfuse/client/core/LangfuseClientApiException.java index fb0aa7f..f948211 100644 --- a/src/main/java/com/langfuse/client/core/LangfuseClientApiException.java +++ b/src/main/java/com/langfuse/client/core/LangfuseClientApiException.java @@ -5,7 +5,13 @@ package com.langfuse.client.core; import java.lang.Object; +import java.lang.Override; import java.lang.String; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; /** * This exception type will be thrown for any non-2XX API responses. @@ -21,10 +27,26 @@ public class LangfuseClientApiException extends LangfuseClientException { */ private final Object body; + private final Map> headers; + public LangfuseClientApiException(String message, int statusCode, Object body) { super(message); this.statusCode = statusCode; this.body = body; + this.headers = new HashMap<>(); + } + + public LangfuseClientApiException(String message, int statusCode, Object body, + Response rawResponse) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + this.headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); } /** @@ -41,8 +63,15 @@ public Object body() { return this.body; } - @java.lang.Override + /** + * @return the headers + */ + public Map> headers() { + return this.headers; + } + + @Override public String toString() { - return "LangfuseClientApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body + "}"; + return "LangfuseClientApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + ObjectMappers.stringify(body) + "}"; } } diff --git a/src/main/java/com/langfuse/client/core/LangfuseClientHttpResponse.java b/src/main/java/com/langfuse/client/core/LangfuseClientHttpResponse.java new file mode 100644 index 0000000..0252a4b --- /dev/null +++ b/src/main/java/com/langfuse/client/core/LangfuseClientHttpResponse.java @@ -0,0 +1,38 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.core; + +import okhttp3.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class LangfuseClientHttpResponse { + + private final T body; + + private final Map> headers; + + public LangfuseClientHttpResponse(T body, Response rawResponse) { + this.body = body; + + Map> headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + this.headers = headers; + } + + public T body() { + return this.body; + } + + public Map> headers() { + return headers; + } +} \ No newline at end of file diff --git a/src/main/java/com/langfuse/client/core/Nullable.java b/src/main/java/com/langfuse/client/core/Nullable.java new file mode 100644 index 0000000..3f7bd8e --- /dev/null +++ b/src/main/java/com/langfuse/client/core/Nullable.java @@ -0,0 +1,141 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.core; + +import java.util.Optional; +import java.util.function.Function; + +public final class Nullable { + + private final Either, Null> value; + + private Nullable() { + this.value = Either.left(Optional.empty()); + } + + private Nullable(T value) { + if (value == null) { + this.value = Either.right(Null.INSTANCE); + } else { + this.value = Either.left(Optional.of(value)); + } + } + + public static Nullable ofNull() { + return new Nullable<>(null); + } + + public static Nullable of(T value) { + return new Nullable<>(value); + } + + public static Nullable empty() { + return new Nullable<>(); + } + + public static Nullable ofOptional(Optional value) { + if (value.isPresent()) { + return of(value.get()); + } else { + return empty(); + } + } + + public boolean isNull() { + return this.value.isRight(); + } + + public boolean isEmpty() { + return this.value.isLeft() && !this.value.getLeft().isPresent(); + } + + public T get() { + if (this.isNull()) { + return null; + } + + return this.value.getLeft().get(); + } + + public Nullable map(Function mapper) { + if (this.isNull()) { + return Nullable.ofNull(); + } + + return Nullable.ofOptional(this.value.getLeft().map(mapper)); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof Nullable)) { + return false; + } + + if (((Nullable) other).isNull() && this.isNull()) { + return true; + } + + return this.value.getLeft().equals(((Nullable) other).value.getLeft()); + } + + private static final class Either { + private L left = null; + private R right = null; + + private Either(L left, R right) { + if (left != null && right != null) { + throw new IllegalArgumentException("Left and right argument cannot both be non-null."); + } + + if (left == null && right == null) { + throw new IllegalArgumentException("Left and right argument cannot both be null."); + } + + if (left != null) { + this.left = left; + } + + if (right != null) { + this.right = right; + } + } + + public static Either left(L left) { + return new Either<>(left, null); + } + + public static Either right(R right) { + return new Either<>(null, right); + } + + public boolean isLeft() { + return this.left != null; + } + + public boolean isRight() { + return this.right != null; + } + + public L getLeft() { + if (!this.isLeft()) { + throw new IllegalArgumentException("Cannot get left from right Either."); + } + return this.left; + } + + public R getRight() { + if (!this.isRight()) { + throw new IllegalArgumentException("Cannot get right from left Either."); + } + return this.right; + } + } + + private static final class Null { + private static final Null INSTANCE = new Null(); + + private Null() {} + } +} diff --git a/src/main/java/com/langfuse/client/core/NullableNonemptyFilter.java b/src/main/java/com/langfuse/client/core/NullableNonemptyFilter.java new file mode 100644 index 0000000..6cc4060 --- /dev/null +++ b/src/main/java/com/langfuse/client/core/NullableNonemptyFilter.java @@ -0,0 +1,25 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.core; + +import java.lang.Object; +import java.lang.Override; +import java.util.Optional; + +public final class NullableNonemptyFilter { + @Override + public boolean equals(Object o) { + boolean isOptionalEmpty = isOptionalEmpty(o); + + return isOptionalEmpty; + } + + private boolean isOptionalEmpty(Object o) { + if (o instanceof Optional) { + return !((Optional) o).isPresent(); + } + return false; + } +} diff --git a/src/main/java/com/langfuse/client/core/ObjectMappers.java b/src/main/java/com/langfuse/client/core/ObjectMappers.java index 437a1a8..09e4b4a 100644 --- a/src/main/java/com/langfuse/client/core/ObjectMappers.java +++ b/src/main/java/com/langfuse/client/core/ObjectMappers.java @@ -5,6 +5,7 @@ package com.langfuse.client.core; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -38,4 +39,13 @@ public static String stringify(Object o) { return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); } } + + public static Object parseErrorBody(String responseBodyString) { + try { + return JSON_MAPPER.readValue(responseBodyString, Object.class); + } + catch (JsonProcessingException ignored) { + return responseBodyString; + } + } } diff --git a/src/main/java/com/langfuse/client/core/RequestOptions.java b/src/main/java/com/langfuse/client/core/RequestOptions.java index 2862b38..1da732d 100644 --- a/src/main/java/com/langfuse/client/core/RequestOptions.java +++ b/src/main/java/com/langfuse/client/core/RequestOptions.java @@ -27,9 +27,14 @@ public final class RequestOptions { private final Map> headerSuppliers; + private final Map queryParameters; + + private final Map> queryParameterSuppliers; + private RequestOptions(String xLangfuseSdkName, String xLangfuseSdkVersion, String xLangfusePublicKey, Optional timeout, TimeUnit timeoutTimeUnit, - Map headers, Map> headerSuppliers) { + Map headers, Map> headerSuppliers, + Map queryParameters, Map> queryParameterSuppliers) { this.xLangfuseSdkName = xLangfuseSdkName; this.xLangfuseSdkVersion = xLangfuseSdkVersion; this.xLangfusePublicKey = xLangfusePublicKey; @@ -37,6 +42,8 @@ private RequestOptions(String xLangfuseSdkName, String xLangfuseSdkVersion, this.timeoutTimeUnit = timeoutTimeUnit; this.headers = headers; this.headerSuppliers = headerSuppliers; + this.queryParameters = queryParameters; + this.queryParameterSuppliers = queryParameterSuppliers; } public Optional getTimeout() { @@ -65,11 +72,19 @@ public Map getHeaders() { return headers; } + public Map getQueryParameters() { + Map queryParameters = new HashMap<>(this.queryParameters); + this.queryParameterSuppliers.forEach((key, supplier) -> { + queryParameters.put(key, supplier.get()); + } ); + return queryParameters; + } + public static Builder builder() { return new Builder(); } - public static final class Builder { + public static class Builder { private String xLangfuseSdkName = null; private String xLangfuseSdkVersion = null; @@ -84,6 +99,10 @@ public static final class Builder { private final Map> headerSuppliers = new HashMap<>(); + private final Map queryParameters = new HashMap<>(); + + private final Map> queryParameterSuppliers = new HashMap<>(); + public Builder xLangfuseSdkName(String xLangfuseSdkName) { this.xLangfuseSdkName = xLangfuseSdkName; return this; @@ -120,8 +139,18 @@ public Builder addHeader(String key, Supplier value) { return this; } + public Builder addQueryParameter(String key, String value) { + this.queryParameters.put(key, value); + return this; + } + + public Builder addQueryParameter(String key, Supplier value) { + this.queryParameterSuppliers.put(key, value); + return this; + } + public RequestOptions build() { - return new RequestOptions(xLangfuseSdkName, xLangfuseSdkVersion, xLangfusePublicKey, timeout, timeoutTimeUnit, headers, headerSuppliers); + return new RequestOptions(xLangfuseSdkName, xLangfuseSdkVersion, xLangfusePublicKey, timeout, timeoutTimeUnit, headers, headerSuppliers, queryParameters, queryParameterSuppliers); } } } diff --git a/src/main/java/com/langfuse/client/core/RetryInterceptor.java b/src/main/java/com/langfuse/client/core/RetryInterceptor.java index af8de59..e6ad817 100644 --- a/src/main/java/com/langfuse/client/core/RetryInterceptor.java +++ b/src/main/java/com/langfuse/client/core/RetryInterceptor.java @@ -6,6 +6,9 @@ import java.io.IOException; import java.time.Duration; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.Optional; import java.util.Random; import okhttp3.Interceptor; @@ -13,7 +16,10 @@ public class RetryInterceptor implements Interceptor { - private static final Duration ONE_SECOND = Duration.ofSeconds(1); + private static final Duration INITIAL_RETRY_DELAY = Duration.ofMillis(1000); + private static final Duration MAX_RETRY_DELAY = Duration.ofMillis(60000); + private static final double JITTER_FACTOR = 0.2; + private final ExponentialBackoff backoff; private final Random random = new Random(); @@ -33,7 +39,7 @@ public Response intercept(Chain chain) throws IOException { } private Response retryChain(Response response, Chain chain) throws IOException { - Optional nextBackoff = this.backoff.nextBackoff(); + Optional nextBackoff = this.backoff.nextBackoff(response); while (nextBackoff.isPresent()) { try { Thread.sleep(nextBackoff.get().toMillis()); @@ -43,7 +49,7 @@ private Response retryChain(Response response, Chain chain) throws IOException { response.close(); response = chain.proceed(chain.request()); if (shouldRetry(response.code())) { - nextBackoff = this.backoff.nextBackoff(); + nextBackoff = this.backoff.nextBackoff(response); } else { return response; } @@ -52,8 +58,104 @@ private Response retryChain(Response response, Chain chain) throws IOException { return response; } + /** + * Calculates the retry delay from response headers, with fallback to exponential backoff. + * Priority: Retry-After > X-RateLimit-Reset > Exponential Backoff + */ + private Duration getRetryDelayFromHeaders(Response response, int retryAttempt) { + // Check for Retry-After header first (RFC 7231), with no jitter + String retryAfter = response.header("Retry-After"); + if (retryAfter != null) { + // Parse as number of seconds... + Optional secondsDelay = tryParseLong(retryAfter) + .map(seconds -> seconds * 1000) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis())) + .map(Duration::ofMillis); + if (secondsDelay.isPresent()) { + return secondsDelay.get(); + } + + // ...or as an HTTP date; both are valid + Optional dateDelay = tryParseHttpDate(retryAfter) + .map(resetTime -> resetTime.toInstant().toEpochMilli() - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis())) + .map(Duration::ofMillis); + if (dateDelay.isPresent()) { + return dateDelay.get(); + } + } + + // Then check for industry-standard X-RateLimit-Reset header, with positive jitter + String rateLimitReset = response.header("X-RateLimit-Reset"); + if (rateLimitReset != null) { + // Assume Unix timestamp in epoch seconds + Optional rateLimitDelay = tryParseLong(rateLimitReset) + .map(resetTimeSeconds -> (resetTimeSeconds * 1000) - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis())) + .map(this::addPositiveJitter) + .map(Duration::ofMillis); + if (rateLimitDelay.isPresent()) { + return rateLimitDelay.get(); + } + } + + // Fall back to exponential backoff, with symmetric jitter + long baseDelay = INITIAL_RETRY_DELAY.toMillis() * (1L << retryAttempt); // 2^retryAttempt + long cappedDelay = Math.min(baseDelay, MAX_RETRY_DELAY.toMillis()); + return Duration.ofMillis(addSymmetricJitter(cappedDelay)); + } + + /** + * Attempts to parse a string as a long, returning empty Optional on failure. + */ + private Optional tryParseLong(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(Long.parseLong(value)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + /** + * Attempts to parse a string as an HTTP date (RFC 1123), returning empty Optional on failure. + */ + private Optional tryParseHttpDate(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME)); + } catch (DateTimeParseException e) { + return Optional.empty(); + } + } + + /** + * Adds positive jitter (100-120% of original value) to prevent thundering herd. + * Used for X-RateLimit-Reset header delays. + */ + private long addPositiveJitter(long delayMs) { + double jitterMultiplier = 1.0 + (random.nextDouble() * JITTER_FACTOR); + return (long) (delayMs * jitterMultiplier); + } + + /** + * Adds symmetric jitter (90-110% of original value) to prevent thundering herd. + * Used for exponential backoff delays. + */ + private long addSymmetricJitter(long delayMs) { + double jitterMultiplier = 1.0 + ((random.nextDouble() - 0.5) * JITTER_FACTOR); + return (long) (delayMs * jitterMultiplier); + } + private static boolean shouldRetry(int statusCode) { - return statusCode == 408 || statusCode == 409 || statusCode == 429 || statusCode >= 500; + return statusCode == 408 || statusCode == 429 || statusCode >= 500; } private final class ExponentialBackoff { @@ -66,14 +168,14 @@ private final class ExponentialBackoff { this.maxNumRetries = maxNumRetries; } - public Optional nextBackoff() { - retryNumber += 1; - if (retryNumber > maxNumRetries) { + public Optional nextBackoff(Response response) { + if (retryNumber >= maxNumRetries) { return Optional.empty(); } - int upperBound = (int) Math.pow(2, retryNumber); - return Optional.of(ONE_SECOND.multipliedBy(random.nextInt(upperBound))); + Duration delay = getRetryDelayFromHeaders(response, retryNumber); + retryNumber += 1; + return Optional.of(delay); } } } diff --git a/src/main/java/com/langfuse/client/core/SseEvent.java b/src/main/java/com/langfuse/client/core/SseEvent.java new file mode 100644 index 0000000..5adc4af --- /dev/null +++ b/src/main/java/com/langfuse/client/core/SseEvent.java @@ -0,0 +1,116 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.core; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; +import java.util.Optional; + +/** + * Represents a Server-Sent Event with all standard fields. + * Used for event-level discrimination where the discriminator is at the SSE envelope level. + * + * @param The type of the data field + */ +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonIgnoreProperties(ignoreUnknown = true) +public final class SseEvent { + private final String event; + private final T data; + private final String id; + private final Long retry; + + private SseEvent(String event, T data, String id, Long retry) { + this.event = event; + this.data = data; + this.id = id; + this.retry = retry; + } + + @JsonProperty("event") + public Optional getEvent() { + return Optional.ofNullable(event); + } + + @JsonProperty("data") + public T getData() { + return data; + } + + @JsonProperty("id") + public Optional getId() { + return Optional.ofNullable(id); + } + + @JsonProperty("retry") + public Optional getRetry() { + return Optional.ofNullable(retry); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SseEvent sseEvent = (SseEvent) o; + return Objects.equals(event, sseEvent.event) + && Objects.equals(data, sseEvent.data) + && Objects.equals(id, sseEvent.id) + && Objects.equals(retry, sseEvent.retry); + } + + @Override + public int hashCode() { + return Objects.hash(event, data, id, retry); + } + + @Override + public String toString() { + return "SseEvent{" + + "event='" + event + '\'' + + ", data=" + data + + ", id='" + id + '\'' + + ", retry=" + retry + + '}'; + } + + public static Builder builder() { + return new Builder<>(); + } + + public static final class Builder { + private String event; + private T data; + private String id; + private Long retry; + + private Builder() {} + + public Builder event(String event) { + this.event = event; + return this; + } + + public Builder data(T data) { + this.data = data; + return this; + } + + public Builder id(String id) { + this.id = id; + return this; + } + + public Builder retry(Long retry) { + this.retry = retry; + return this; + } + + public SseEvent build() { + return new SseEvent<>(event, data, id, retry); + } + } +} diff --git a/src/main/java/com/langfuse/client/core/SseEventParser.java b/src/main/java/com/langfuse/client/core/SseEventParser.java new file mode 100644 index 0000000..73b43cd --- /dev/null +++ b/src/main/java/com/langfuse/client/core/SseEventParser.java @@ -0,0 +1,236 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.core; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.core.type.TypeReference; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Utility class for parsing Server-Sent Events with support for discriminated unions. + *

+ * Handles two discrimination patterns: + *

    + *
  1. Data-level discrimination: The discriminator (e.g., 'type') is inside the JSON data payload. + * Jackson's polymorphic deserialization handles this automatically.
  2. + *
  3. Event-level discrimination: The discriminator (e.g., 'event') is at the SSE envelope level. + * This requires constructing the full SSE envelope for Jackson to process.
  4. + *
+ */ +public final class SseEventParser { + + private static final Set SSE_ENVELOPE_FIELDS = new HashSet<>(Arrays.asList("event", "data", "id", "retry")); + + private SseEventParser() { + // Utility class + } + + /** + * Parse an SSE event using event-level discrimination. + *

+ * Constructs the full SSE envelope object with event, data, id, and retry fields, + * then deserializes it to the target union type. + * + * @param eventType The SSE event type (from event: field) + * @param data The SSE data content (from data: field) + * @param id The SSE event ID (from id: field), may be null + * @param retry The SSE retry value (from retry: field), may be null + * @param unionClass The target union class + * @param discriminatorProperty The property name used for discrimination (e.g., "event") + * @param The target type + * @return The deserialized object + */ + public static T parseEventLevelUnion( + String eventType, + String data, + String id, + Long retry, + Class unionClass, + String discriminatorProperty) { + try { + // Determine if data should be parsed as JSON based on the variant's expected type + Object parsedData = parseDataForVariant(eventType, data, unionClass, discriminatorProperty); + + // Construct the SSE envelope object + Map envelope = new HashMap<>(); + envelope.put(discriminatorProperty, eventType); + envelope.put("data", parsedData); + if (id != null) { + envelope.put("id", id); + } + if (retry != null) { + envelope.put("retry", retry); + } + + // Serialize to JSON and deserialize to target type + String envelopeJson = ObjectMappers.JSON_MAPPER.writeValueAsString(envelope); + return ObjectMappers.JSON_MAPPER.readValue(envelopeJson, unionClass); + } catch (Exception e) { + throw new RuntimeException("Failed to parse SSE event with event-level discrimination", e); + } + } + + /** + * Parse an SSE event using data-level discrimination. + *

+ * Simply parses the data field as JSON and deserializes it to the target type. + * Jackson's polymorphic deserialization handles the discrimination automatically. + * + * @param data The SSE data content (from data: field) + * @param valueType The target type + * @param The target type + * @return The deserialized object + */ + public static T parseDataLevelUnion(String data, Class valueType) { + try { + return ObjectMappers.JSON_MAPPER.readValue(data, valueType); + } catch (Exception e) { + throw new RuntimeException("Failed to parse SSE data with data-level discrimination", e); + } + } + + /** + * Determines if the given discriminator property indicates event-level discrimination. + * Event-level discrimination occurs when the discriminator is an SSE envelope field. + * + * @param discriminatorProperty The discriminator property name + * @return true if event-level discrimination, false otherwise + */ + public static boolean isEventLevelDiscrimination(String discriminatorProperty) { + return SSE_ENVELOPE_FIELDS.contains(discriminatorProperty); + } + + /** + * Attempts to find the discriminator property from the union class's Jackson annotations. + * + * @param unionClass The union class to inspect + * @return The discriminator property name, or empty if not found + */ + public static Optional findDiscriminatorProperty(Class unionClass) { + try { + // Look for JsonTypeInfo on the class itself + JsonTypeInfo typeInfo = unionClass.getAnnotation(JsonTypeInfo.class); + if (typeInfo != null && !typeInfo.property().isEmpty()) { + return Optional.of(typeInfo.property()); + } + + // Look for inner Value interface with JsonTypeInfo + for (Class innerClass : unionClass.getDeclaredClasses()) { + typeInfo = innerClass.getAnnotation(JsonTypeInfo.class); + if (typeInfo != null && !typeInfo.property().isEmpty()) { + return Optional.of(typeInfo.property()); + } + } + } catch (Exception e) { + // Ignore reflection errors + } + return Optional.empty(); + } + + /** + * Parse the data field based on what the matching variant expects. + * If the variant expects a String for its data field, returns the raw string. + * Otherwise, parses the data as JSON. + */ + private static Object parseDataForVariant( + String eventType, + String data, + Class unionClass, + String discriminatorProperty) { + if (data == null || data.isEmpty()) { + return data; + } + + try { + // Try to find the variant class that matches this event type + Class variantClass = findVariantClass(unionClass, eventType, discriminatorProperty); + if (variantClass != null) { + // Check if the variant expects a String for the data field + Field dataField = findField(variantClass, "data"); + if (dataField != null && String.class.equals(dataField.getType())) { + // Variant expects String - return raw data + return data; + } + } + + // Try to parse as JSON + return ObjectMappers.JSON_MAPPER.readValue(data, new TypeReference>() {}); + } catch (Exception e) { + // If JSON parsing fails, return as string + return data; + } + } + + /** + * Find the variant class that matches the given discriminator value. + */ + private static Class findVariantClass(Class unionClass, String discriminatorValue, String discriminatorProperty) { + try { + // Look for JsonSubTypes annotation + JsonSubTypes subTypes = findJsonSubTypes(unionClass); + if (subTypes == null) { + return null; + } + + for (JsonSubTypes.Type subType : subTypes.value()) { + JsonTypeName typeName = subType.value().getAnnotation(JsonTypeName.class); + if (typeName != null && typeName.value().equals(discriminatorValue)) { + return subType.value(); + } + // Also check the name attribute of @JsonSubTypes.Type + if (subType.name().equals(discriminatorValue)) { + return subType.value(); + } + } + } catch (Exception e) { + // Ignore reflection errors + } + return null; + } + + /** + * Find JsonSubTypes annotation on the class or its inner classes. + */ + private static JsonSubTypes findJsonSubTypes(Class unionClass) { + // Check the class itself + JsonSubTypes subTypes = unionClass.getAnnotation(JsonSubTypes.class); + if (subTypes != null) { + return subTypes; + } + + // Check inner classes (for Fern-style unions with inner Value interface) + for (Class innerClass : unionClass.getDeclaredClasses()) { + subTypes = innerClass.getAnnotation(JsonSubTypes.class); + if (subTypes != null) { + return subTypes; + } + } + return null; + } + + /** + * Find a field by name in a class, including private fields. + */ + private static Field findField(Class clazz, String fieldName) { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + // Check superclass + Class superClass = clazz.getSuperclass(); + if (superClass != null && superClass != Object.class) { + return findField(superClass, fieldName); + } + return null; + } + } +} diff --git a/src/main/java/com/langfuse/client/core/Stream.java b/src/main/java/com/langfuse/client/core/Stream.java index fbccca5..319d33d 100644 --- a/src/main/java/com/langfuse/client/core/Stream.java +++ b/src/main/java/com/langfuse/client/core/Stream.java @@ -4,9 +4,11 @@ package com.langfuse.client.core; +import java.io.Closeable; +import java.io.IOException; +import java.io.Reader; import java.util.Iterator; import java.util.NoSuchElementException; -import java.io.Reader; import java.util.Scanner; /** @@ -15,18 +17,30 @@ *

* {@code Stream} assumes that data is being pushed to the provided {@link Reader} asynchronously and utilizes a * {@code Scanner} to block during iteration if the next object is not available. + * Iterable stream for parsing JSON and Server-Sent Events (SSE) data. + * Supports both newline-delimited JSON and SSE with optional stream termination. * * @param The type of objects in the stream. */ -public final class Stream implements Iterable { - /** - * The {@link Class} of the objects in the stream. - */ +public final class Stream implements Iterable, Closeable { + + private static final String NEWLINE = "\n"; + private static final String DATA_PREFIX = "data:"; + + public enum StreamType { + JSON, + SSE, + SSE_EVENT_DISCRIMINATED + } + private final Class valueType; - /** - * The {@link Scanner} used for reading from the input stream and blocking when needed during iteration. - */ private final Scanner scanner; + private final StreamType streamType; + private final String messageTerminator; + private final String streamTerminator; + private final Reader sseReader; + private final String discriminatorProperty; + private boolean isClosed = false; /** * Constructs a new {@code Stream} with the specified value type, reader, and delimiter. @@ -36,8 +50,98 @@ public final class Stream implements Iterable { * @param delimiter The delimiter used to separate elements in the stream. */ public Stream(Class valueType, Reader reader, String delimiter) { + this.valueType = valueType; this.scanner = new Scanner(reader).useDelimiter(delimiter); + this.streamType = StreamType.JSON; + this.messageTerminator = delimiter; + this.streamTerminator = null; + this.sseReader = null; + this.discriminatorProperty = null; + } + + private Stream(Class valueType, StreamType type, Reader reader, String terminator) { + this(valueType, type, reader, terminator, null); + } + + private Stream(Class valueType, StreamType type, Reader reader, String terminator, String discriminatorProperty) { this.valueType = valueType; + this.streamType = type; + this.discriminatorProperty = discriminatorProperty; + if (type == StreamType.JSON) { + this.scanner = new Scanner(reader).useDelimiter(terminator); + this.messageTerminator = terminator; + this.streamTerminator = null; + this.sseReader = null; + } else { + this.scanner = null; + this.messageTerminator = NEWLINE; + this.streamTerminator = terminator; + this.sseReader = reader; + } + } + + public static Stream fromJson(Class valueType, Reader reader, String delimiter) { + return new Stream<>(valueType, reader, delimiter); + } + + public static Stream fromJson(Class valueType, Reader reader) { + return new Stream<>(valueType, reader, NEWLINE); + } + + public static Stream fromSse(Class valueType, Reader sseReader) { + return new Stream<>(valueType, StreamType.SSE, sseReader, null); + } + + public static Stream fromSse(Class valueType, Reader sseReader, String streamTerminator) { + return new Stream<>(valueType, StreamType.SSE, sseReader, streamTerminator); + } + + /** + * Creates a stream from SSE data with event-level discrimination support. + * Use this when the SSE payload is a discriminated union where the discriminator + * is an SSE envelope field (e.g., 'event'). + * + * @param valueType The class of the objects in the stream. + * @param sseReader The reader that provides the SSE data. + * @param discriminatorProperty The property name used for discrimination (e.g., "event"). + * @param The type of objects in the stream. + * @return A new Stream instance configured for SSE with event-level discrimination. + */ + public static Stream fromSseWithEventDiscrimination( + Class valueType, Reader sseReader, String discriminatorProperty) { + return new Stream<>(valueType, StreamType.SSE_EVENT_DISCRIMINATED, sseReader, null, discriminatorProperty); + } + + /** + * Creates a stream from SSE data with event-level discrimination support and a stream terminator. + * + * @param valueType The class of the objects in the stream. + * @param sseReader The reader that provides the SSE data. + * @param discriminatorProperty The property name used for discrimination (e.g., "event"). + * @param streamTerminator The terminator string that signals end of stream (e.g., "[DONE]"). + * @param The type of objects in the stream. + * @return A new Stream instance configured for SSE with event-level discrimination. + */ + public static Stream fromSseWithEventDiscrimination( + Class valueType, Reader sseReader, String discriminatorProperty, String streamTerminator) { + return new Stream<>(valueType, StreamType.SSE_EVENT_DISCRIMINATED, sseReader, streamTerminator, discriminatorProperty); + } + + @Override + public void close() throws IOException { + if (!isClosed) { + isClosed = true; + if (scanner != null) { + scanner.close(); + } + if (sseReader != null) { + sseReader.close(); + } + } + } + + private boolean isStreamClosed() { + return isClosed; } /** @@ -48,51 +152,360 @@ public Stream(Class valueType, Reader reader, String delimiter) { */ @Override public Iterator iterator() { - return new Iterator() { - /** - * Returns {@code true} if there are more elements in the stream. - *

- * Will block and wait for input if the stream has not ended and the next object is not yet available. - * - * @return {@code true} if there are more elements, {@code false} otherwise. - */ - @Override - public boolean hasNext() { - return scanner.hasNext(); - } - - /** - * Returns the next element in the stream. - *

- * Will block and wait for input if the stream has not ended and the next object is not yet available. - * - * @return The next element in the stream. - * @throws NoSuchElementException If there are no more elements in the stream. - */ - @Override - public T next() { - if (!scanner.hasNext()) { - throw new NoSuchElementException(); - } else { + switch (streamType) { + case SSE: + return new SSEIterator(); + case SSE_EVENT_DISCRIMINATED: + return new SSEEventDiscriminatedIterator(); + case JSON: + default: + return new JsonIterator(); + } + } + + private final class JsonIterator implements Iterator { + + /** + * Returns {@code true} if there are more elements in the stream. + *

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return {@code true} if there are more elements, {@code false} otherwise. + */ + @Override + public boolean hasNext() { + if (isStreamClosed()) { + return false; + } + return scanner.hasNext(); + } + + /** + * Returns the next element in the stream. + *

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return The next element in the stream. + * @throws NoSuchElementException If there are no more elements in the stream. + */ + @Override + public T next() { + if (isStreamClosed()) { + throw new NoSuchElementException("Stream is closed"); + } + + if (!scanner.hasNext()) { + throw new NoSuchElementException(); + } else { + try { + T parsedResponse = + ObjectMappers.JSON_MAPPER.readValue(scanner.next().trim(), valueType); + return parsedResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + } + + private final class SSEIterator implements Iterator { + private Scanner sseScanner; + private T nextItem; + private boolean hasNextItem = false; + private boolean endOfStream = false; + private StringBuilder eventDataBuffer = new StringBuilder(); + private String currentEventType = null; + + private SSEIterator() { + if (sseReader != null && !isStreamClosed()) { + this.sseScanner = new Scanner(sseReader); + } else { + this.endOfStream = true; + } + } + + @Override + public boolean hasNext() { + if (isStreamClosed() || endOfStream) { + return false; + } + + if (hasNextItem) { + return true; + } + + return readNextMessage(); + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException("No more elements in stream"); + } + + T result = nextItem; + nextItem = null; + hasNextItem = false; + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + private boolean readNextMessage() { + if (sseScanner == null || isStreamClosed()) { + endOfStream = true; + return false; + } + + try { + while (sseScanner.hasNextLine()) { + String line = sseScanner.nextLine(); + + if (line.trim().isEmpty()) { + if (eventDataBuffer.length() > 0) { + try { + nextItem = ObjectMappers.JSON_MAPPER.readValue( + eventDataBuffer.toString(), valueType); + hasNextItem = true; + eventDataBuffer.setLength(0); + currentEventType = null; + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse SSE event: " + parseEx.getMessage()); + eventDataBuffer.setLength(0); + currentEventType = null; + continue; + } + } + continue; + } + + if (line.startsWith(DATA_PREFIX)) { + String dataContent = line.substring(DATA_PREFIX.length()); + if (dataContent.startsWith(" ")) { + dataContent = dataContent.substring(1); + } + + if (eventDataBuffer.length() == 0 && streamTerminator != null && dataContent.trim().equals(streamTerminator)) { + endOfStream = true; + return false; + } + + if (eventDataBuffer.length() > 0) { + eventDataBuffer.append('\n'); + } + eventDataBuffer.append(dataContent); + } else if (line.startsWith("event:")) { + String eventValue = line.length() > 6 ? line.substring(6) : ""; + if (eventValue.startsWith(" ")) { + eventValue = eventValue.substring(1); + } + currentEventType = eventValue; + } else if (line.startsWith("id:")) { + // Event ID field (ignored) + } else if (line.startsWith("retry:")) { + // Retry field (ignored) + } else if (line.startsWith(":")) { + // Comment line (ignored) + } + } + + if (eventDataBuffer.length() > 0) { try { - T parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(scanner.next().trim(), valueType); - return parsedResponse; - } catch (Exception e) { - throw new RuntimeException(e); + nextItem = ObjectMappers.JSON_MAPPER.readValue( + eventDataBuffer.toString(), valueType); + hasNextItem = true; + eventDataBuffer.setLength(0); + currentEventType = null; + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse final SSE event: " + parseEx.getMessage()); + eventDataBuffer.setLength(0); + currentEventType = null; } } + + endOfStream = true; + return false; + + } catch (Exception e) { + System.err.println("Failed to parse SSE stream: " + e.getMessage()); + endOfStream = true; + return false; + } + } + + } + + /** + * Iterator for SSE streams with event-level discrimination. + * Uses SseEventParser to construct the full SSE envelope for Jackson deserialization. + */ + private final class SSEEventDiscriminatedIterator implements Iterator { + private Scanner sseScanner; + private T nextItem; + private boolean hasNextItem = false; + private boolean endOfStream = false; + private StringBuilder eventDataBuffer = new StringBuilder(); + private String currentEventType = null; + private String currentEventId = null; + private Long currentRetry = null; + + private SSEEventDiscriminatedIterator() { + if (sseReader != null && !isStreamClosed()) { + this.sseScanner = new Scanner(sseReader); + } else { + this.endOfStream = true; + } + } + + @Override + public boolean hasNext() { + if (isStreamClosed() || endOfStream) { + return false; + } + + if (hasNextItem) { + return true; + } + + return readNextMessage(); + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException("No more elements in stream"); } - /** - * Removing elements from {@code Stream} is not supported. - * - * @throws UnsupportedOperationException Always, as removal is not supported. - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); + T result = nextItem; + nextItem = null; + hasNextItem = false; + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + private boolean readNextMessage() { + if (sseScanner == null || isStreamClosed()) { + endOfStream = true; + return false; } - }; + + try { + while (sseScanner.hasNextLine()) { + String line = sseScanner.nextLine(); + + if (line.trim().isEmpty()) { + if (eventDataBuffer.length() > 0 || currentEventType != null) { + try { + // Use SseEventParser for event-level discrimination + nextItem = SseEventParser.parseEventLevelUnion( + currentEventType, + eventDataBuffer.toString(), + currentEventId, + currentRetry, + valueType, + discriminatorProperty); + hasNextItem = true; + resetEventState(); + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse SSE event: " + parseEx.getMessage()); + resetEventState(); + continue; + } + } + continue; + } + + if (line.startsWith(DATA_PREFIX)) { + String dataContent = line.substring(DATA_PREFIX.length()); + if (dataContent.startsWith(" ")) { + dataContent = dataContent.substring(1); + } + + if (eventDataBuffer.length() == 0 && streamTerminator != null && dataContent.trim().equals(streamTerminator)) { + endOfStream = true; + return false; + } + + if (eventDataBuffer.length() > 0) { + eventDataBuffer.append('\n'); + } + eventDataBuffer.append(dataContent); + } else if (line.startsWith("event:")) { + String eventValue = line.length() > 6 ? line.substring(6) : ""; + if (eventValue.startsWith(" ")) { + eventValue = eventValue.substring(1); + } + currentEventType = eventValue; + } else if (line.startsWith("id:")) { + String idValue = line.length() > 3 ? line.substring(3) : ""; + if (idValue.startsWith(" ")) { + idValue = idValue.substring(1); + } + currentEventId = idValue; + } else if (line.startsWith("retry:")) { + String retryValue = line.length() > 6 ? line.substring(6) : ""; + if (retryValue.startsWith(" ")) { + retryValue = retryValue.substring(1); + } + try { + currentRetry = Long.parseLong(retryValue.trim()); + } catch (NumberFormatException e) { + // Ignore invalid retry values + } + } else if (line.startsWith(":")) { + // Comment line (ignored) + } + } + + // Handle any remaining buffered data at end of stream + if (eventDataBuffer.length() > 0 || currentEventType != null) { + try { + nextItem = SseEventParser.parseEventLevelUnion( + currentEventType, + eventDataBuffer.toString(), + currentEventId, + currentRetry, + valueType, + discriminatorProperty); + hasNextItem = true; + resetEventState(); + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse final SSE event: " + parseEx.getMessage()); + resetEventState(); + } + } + + endOfStream = true; + return false; + + } catch (Exception e) { + System.err.println("Failed to parse SSE stream: " + e.getMessage()); + endOfStream = true; + return false; + } + } + + private void resetEventState() { + eventDataBuffer.setLength(0); + currentEventType = null; + currentEventId = null; + currentRetry = null; + } } -} \ No newline at end of file +} diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/AnnotationQueuesClient.java b/src/main/java/com/langfuse/client/resources/annotationqueues/AnnotationQueuesClient.java index db6eb50..e3027de 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/AnnotationQueuesClient.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/AnnotationQueuesClient.java @@ -4,24 +4,9 @@ package com.langfuse.client.resources.annotationqueues; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueueItemsRequest; import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueuesRequest; import com.langfuse.client.resources.annotationqueues.types.AnnotationQueue; @@ -35,31 +20,43 @@ import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueueItems; import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueues; import com.langfuse.client.resources.annotationqueues.types.UpdateAnnotationQueueItemRequest; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; public class AnnotationQueuesClient { protected final ClientOptions clientOptions; + private final RawAnnotationQueuesClient rawClient; + public AnnotationQueuesClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawAnnotationQueuesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawAnnotationQueuesClient withRawResponse() { + return this.rawClient; } /** * Get all annotation queues */ public PaginatedAnnotationQueues listQueues() { - return listQueues(GetAnnotationQueuesRequest.builder().build()); + return this.rawClient.listQueues().body(); + } + + /** + * Get all annotation queues + */ + public PaginatedAnnotationQueues listQueues(RequestOptions requestOptions) { + return this.rawClient.listQueues(requestOptions).body(); } /** * Get all annotation queues */ public PaginatedAnnotationQueues listQueues(GetAnnotationQueuesRequest request) { - return listQueues(request,null); + return this.rawClient.listQueues(request).body(); } /** @@ -67,593 +64,175 @@ public PaginatedAnnotationQueues listQueues(GetAnnotationQueuesRequest request) */ public PaginatedAnnotationQueues listQueues(GetAnnotationQueuesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedAnnotationQueues.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Create an annotation queue - */ - public AnnotationQueue createQueue(CreateAnnotationQueueRequest request) { - return createQueue(request,null); - } - - /** - * Create an annotation queue - */ - public AnnotationQueue createQueue(CreateAnnotationQueueRequest request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AnnotationQueue.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Get an annotation queue by ID - */ - public AnnotationQueue getQueue(String queueId) { - return getQueue(queueId,null); - } - - /** - * Get an annotation queue by ID - */ - public AnnotationQueue getQueue(String queueId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AnnotationQueue.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Get items for a specific annotation queue - */ - public PaginatedAnnotationQueueItems listQueueItems(String queueId) { - return listQueueItems(queueId,GetAnnotationQueueItemsRequest.builder().build()); - } - - /** - * Get items for a specific annotation queue - */ - public PaginatedAnnotationQueueItems listQueueItems(String queueId, - GetAnnotationQueueItemsRequest request) { - return listQueueItems(queueId,request,null); - } - - /** - * Get items for a specific annotation queue - */ - public PaginatedAnnotationQueueItems listQueueItems(String queueId, - GetAnnotationQueueItemsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .addPathSegments("items");if (request.getStatus().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "status", request.getStatus().get().toString(), false); - } - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedAnnotationQueueItems.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Get a specific item from an annotation queue - */ - public AnnotationQueueItem getQueueItem(String queueId, String itemId) { - return getQueueItem(queueId,itemId,null); - } - - /** - * Get a specific item from an annotation queue - */ - public AnnotationQueueItem getQueueItem(String queueId, String itemId, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .addPathSegments("items") - .addPathSegment(itemId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AnnotationQueueItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Add an item to an annotation queue - */ - public AnnotationQueueItem createQueueItem(String queueId, - CreateAnnotationQueueItemRequest request) { - return createQueueItem(queueId,request,null); - } - - /** - * Add an item to an annotation queue - */ - public AnnotationQueueItem createQueueItem(String queueId, - CreateAnnotationQueueItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .addPathSegments("items") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AnnotationQueueItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Update an annotation queue item - */ - public AnnotationQueueItem updateQueueItem(String queueId, String itemId) { - return updateQueueItem(queueId,itemId,UpdateAnnotationQueueItemRequest.builder().build()); - } - - /** - * Update an annotation queue item - */ - public AnnotationQueueItem updateQueueItem(String queueId, String itemId, - UpdateAnnotationQueueItemRequest request) { - return updateQueueItem(queueId,itemId,request,null); - } - - /** - * Update an annotation queue item - */ - public AnnotationQueueItem updateQueueItem(String queueId, String itemId, - UpdateAnnotationQueueItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .addPathSegments("items") - .addPathSegment(itemId) - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), AnnotationQueueItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Remove an item from an annotation queue - */ - public DeleteAnnotationQueueItemResponse deleteQueueItem(String queueId, String itemId) { - return deleteQueueItem(queueId,itemId,null); - } - - /** - * Remove an item from an annotation queue - */ - public DeleteAnnotationQueueItemResponse deleteQueueItem(String queueId, String itemId, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .addPathSegments("items") - .addPathSegment(itemId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeleteAnnotationQueueItemResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Create an assignment for a user to an annotation queue - */ - public CreateAnnotationQueueAssignmentResponse createQueueAssignment(String queueId, - AnnotationQueueAssignmentRequest request) { - return createQueueAssignment(queueId,request,null); - } - - /** - * Create an assignment for a user to an annotation queue - */ - public CreateAnnotationQueueAssignmentResponse createQueueAssignment(String queueId, - AnnotationQueueAssignmentRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .addPathSegments("assignments") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateAnnotationQueueAssignmentResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - - /** - * Delete an assignment for a user to an annotation queue - */ - public DeleteAnnotationQueueAssignmentResponse deleteQueueAssignment(String queueId, - AnnotationQueueAssignmentRequest request) { - return deleteQueueAssignment(queueId,request,null); - } - - /** - * Delete an assignment for a user to an annotation queue - */ - public DeleteAnnotationQueueAssignmentResponse deleteQueueAssignment(String queueId, - AnnotationQueueAssignmentRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("annotation-queues") - .addPathSegment(queueId) - .addPathSegments("assignments") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeleteAnnotationQueueAssignmentResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - } + return this.rawClient.listQueues(request, requestOptions).body(); + } + + /** + * Create an annotation queue + */ + public AnnotationQueue createQueue(CreateAnnotationQueueRequest request) { + return this.rawClient.createQueue(request).body(); + } + + /** + * Create an annotation queue + */ + public AnnotationQueue createQueue(CreateAnnotationQueueRequest request, + RequestOptions requestOptions) { + return this.rawClient.createQueue(request, requestOptions).body(); + } + + /** + * Get an annotation queue by ID + */ + public AnnotationQueue getQueue(String queueId) { + return this.rawClient.getQueue(queueId).body(); + } + + /** + * Get an annotation queue by ID + */ + public AnnotationQueue getQueue(String queueId, RequestOptions requestOptions) { + return this.rawClient.getQueue(queueId, requestOptions).body(); + } + + /** + * Get items for a specific annotation queue + */ + public PaginatedAnnotationQueueItems listQueueItems(String queueId) { + return this.rawClient.listQueueItems(queueId).body(); + } + + /** + * Get items for a specific annotation queue + */ + public PaginatedAnnotationQueueItems listQueueItems(String queueId, + RequestOptions requestOptions) { + return this.rawClient.listQueueItems(queueId, requestOptions).body(); + } + + /** + * Get items for a specific annotation queue + */ + public PaginatedAnnotationQueueItems listQueueItems(String queueId, + GetAnnotationQueueItemsRequest request) { + return this.rawClient.listQueueItems(queueId, request).body(); + } + + /** + * Get items for a specific annotation queue + */ + public PaginatedAnnotationQueueItems listQueueItems(String queueId, + GetAnnotationQueueItemsRequest request, RequestOptions requestOptions) { + return this.rawClient.listQueueItems(queueId, request, requestOptions).body(); + } + + /** + * Get a specific item from an annotation queue + */ + public AnnotationQueueItem getQueueItem(String queueId, String itemId) { + return this.rawClient.getQueueItem(queueId, itemId).body(); + } + + /** + * Get a specific item from an annotation queue + */ + public AnnotationQueueItem getQueueItem(String queueId, String itemId, + RequestOptions requestOptions) { + return this.rawClient.getQueueItem(queueId, itemId, requestOptions).body(); + } + + /** + * Add an item to an annotation queue + */ + public AnnotationQueueItem createQueueItem(String queueId, + CreateAnnotationQueueItemRequest request) { + return this.rawClient.createQueueItem(queueId, request).body(); + } + + /** + * Add an item to an annotation queue + */ + public AnnotationQueueItem createQueueItem(String queueId, + CreateAnnotationQueueItemRequest request, RequestOptions requestOptions) { + return this.rawClient.createQueueItem(queueId, request, requestOptions).body(); + } + + /** + * Update an annotation queue item + */ + public AnnotationQueueItem updateQueueItem(String queueId, String itemId) { + return this.rawClient.updateQueueItem(queueId, itemId).body(); + } + + /** + * Update an annotation queue item + */ + public AnnotationQueueItem updateQueueItem(String queueId, String itemId, + RequestOptions requestOptions) { + return this.rawClient.updateQueueItem(queueId, itemId, requestOptions).body(); + } + + /** + * Update an annotation queue item + */ + public AnnotationQueueItem updateQueueItem(String queueId, String itemId, + UpdateAnnotationQueueItemRequest request) { + return this.rawClient.updateQueueItem(queueId, itemId, request).body(); + } + + /** + * Update an annotation queue item + */ + public AnnotationQueueItem updateQueueItem(String queueId, String itemId, + UpdateAnnotationQueueItemRequest request, RequestOptions requestOptions) { + return this.rawClient.updateQueueItem(queueId, itemId, request, requestOptions).body(); + } + + /** + * Remove an item from an annotation queue + */ + public DeleteAnnotationQueueItemResponse deleteQueueItem(String queueId, String itemId) { + return this.rawClient.deleteQueueItem(queueId, itemId).body(); + } + + /** + * Remove an item from an annotation queue + */ + public DeleteAnnotationQueueItemResponse deleteQueueItem(String queueId, String itemId, + RequestOptions requestOptions) { + return this.rawClient.deleteQueueItem(queueId, itemId, requestOptions).body(); + } + + /** + * Create an assignment for a user to an annotation queue + */ + public CreateAnnotationQueueAssignmentResponse createQueueAssignment(String queueId, + AnnotationQueueAssignmentRequest request) { + return this.rawClient.createQueueAssignment(queueId, request).body(); + } + + /** + * Create an assignment for a user to an annotation queue + */ + public CreateAnnotationQueueAssignmentResponse createQueueAssignment(String queueId, + AnnotationQueueAssignmentRequest request, RequestOptions requestOptions) { + return this.rawClient.createQueueAssignment(queueId, request, requestOptions).body(); + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public DeleteAnnotationQueueAssignmentResponse deleteQueueAssignment(String queueId, + AnnotationQueueAssignmentRequest request) { + return this.rawClient.deleteQueueAssignment(queueId, request).body(); + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public DeleteAnnotationQueueAssignmentResponse deleteQueueAssignment(String queueId, + AnnotationQueueAssignmentRequest request, RequestOptions requestOptions) { + return this.rawClient.deleteQueueAssignment(queueId, request, requestOptions).body(); + } +} diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/AsyncAnnotationQueuesClient.java b/src/main/java/com/langfuse/client/resources/annotationqueues/AsyncAnnotationQueuesClient.java new file mode 100644 index 0000000..0f88d14 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/AsyncAnnotationQueuesClient.java @@ -0,0 +1,242 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.annotationqueues; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueueItemsRequest; +import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueuesRequest; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueue; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueueAssignmentRequest; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueueItem; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueAssignmentResponse; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueItemRequest; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueRequest; +import com.langfuse.client.resources.annotationqueues.types.DeleteAnnotationQueueAssignmentResponse; +import com.langfuse.client.resources.annotationqueues.types.DeleteAnnotationQueueItemResponse; +import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueueItems; +import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueues; +import com.langfuse.client.resources.annotationqueues.types.UpdateAnnotationQueueItemRequest; + +public class AsyncAnnotationQueuesClient { + protected final ClientOptions clientOptions; + + private final AsyncRawAnnotationQueuesClient rawClient; + + public AsyncAnnotationQueuesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawAnnotationQueuesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawAnnotationQueuesClient withRawResponse() { + return this.rawClient; + } + + /** + * Get all annotation queues + */ + public CompletableFuture listQueues() { + return this.rawClient.listQueues().thenApply(response -> response.body()); + } + + /** + * Get all annotation queues + */ + public CompletableFuture listQueues(RequestOptions requestOptions) { + return this.rawClient.listQueues(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all annotation queues + */ + public CompletableFuture listQueues( + GetAnnotationQueuesRequest request) { + return this.rawClient.listQueues(request).thenApply(response -> response.body()); + } + + /** + * Get all annotation queues + */ + public CompletableFuture listQueues(GetAnnotationQueuesRequest request, + RequestOptions requestOptions) { + return this.rawClient.listQueues(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create an annotation queue + */ + public CompletableFuture createQueue(CreateAnnotationQueueRequest request) { + return this.rawClient.createQueue(request).thenApply(response -> response.body()); + } + + /** + * Create an annotation queue + */ + public CompletableFuture createQueue(CreateAnnotationQueueRequest request, + RequestOptions requestOptions) { + return this.rawClient.createQueue(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get an annotation queue by ID + */ + public CompletableFuture getQueue(String queueId) { + return this.rawClient.getQueue(queueId).thenApply(response -> response.body()); + } + + /** + * Get an annotation queue by ID + */ + public CompletableFuture getQueue(String queueId, + RequestOptions requestOptions) { + return this.rawClient.getQueue(queueId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture listQueueItems(String queueId) { + return this.rawClient.listQueueItems(queueId).thenApply(response -> response.body()); + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture listQueueItems(String queueId, + RequestOptions requestOptions) { + return this.rawClient.listQueueItems(queueId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture listQueueItems(String queueId, + GetAnnotationQueueItemsRequest request) { + return this.rawClient.listQueueItems(queueId, request).thenApply(response -> response.body()); + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture listQueueItems(String queueId, + GetAnnotationQueueItemsRequest request, RequestOptions requestOptions) { + return this.rawClient.listQueueItems(queueId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a specific item from an annotation queue + */ + public CompletableFuture getQueueItem(String queueId, String itemId) { + return this.rawClient.getQueueItem(queueId, itemId).thenApply(response -> response.body()); + } + + /** + * Get a specific item from an annotation queue + */ + public CompletableFuture getQueueItem(String queueId, String itemId, + RequestOptions requestOptions) { + return this.rawClient.getQueueItem(queueId, itemId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Add an item to an annotation queue + */ + public CompletableFuture createQueueItem(String queueId, + CreateAnnotationQueueItemRequest request) { + return this.rawClient.createQueueItem(queueId, request).thenApply(response -> response.body()); + } + + /** + * Add an item to an annotation queue + */ + public CompletableFuture createQueueItem(String queueId, + CreateAnnotationQueueItemRequest request, RequestOptions requestOptions) { + return this.rawClient.createQueueItem(queueId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Update an annotation queue item + */ + public CompletableFuture updateQueueItem(String queueId, String itemId) { + return this.rawClient.updateQueueItem(queueId, itemId).thenApply(response -> response.body()); + } + + /** + * Update an annotation queue item + */ + public CompletableFuture updateQueueItem(String queueId, String itemId, + RequestOptions requestOptions) { + return this.rawClient.updateQueueItem(queueId, itemId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Update an annotation queue item + */ + public CompletableFuture updateQueueItem(String queueId, String itemId, + UpdateAnnotationQueueItemRequest request) { + return this.rawClient.updateQueueItem(queueId, itemId, request).thenApply(response -> response.body()); + } + + /** + * Update an annotation queue item + */ + public CompletableFuture updateQueueItem(String queueId, String itemId, + UpdateAnnotationQueueItemRequest request, RequestOptions requestOptions) { + return this.rawClient.updateQueueItem(queueId, itemId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Remove an item from an annotation queue + */ + public CompletableFuture deleteQueueItem(String queueId, + String itemId) { + return this.rawClient.deleteQueueItem(queueId, itemId).thenApply(response -> response.body()); + } + + /** + * Remove an item from an annotation queue + */ + public CompletableFuture deleteQueueItem(String queueId, + String itemId, RequestOptions requestOptions) { + return this.rawClient.deleteQueueItem(queueId, itemId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create an assignment for a user to an annotation queue + */ + public CompletableFuture createQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request) { + return this.rawClient.createQueueAssignment(queueId, request).thenApply(response -> response.body()); + } + + /** + * Create an assignment for a user to an annotation queue + */ + public CompletableFuture createQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request, RequestOptions requestOptions) { + return this.rawClient.createQueueAssignment(queueId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public CompletableFuture deleteQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request) { + return this.rawClient.deleteQueueAssignment(queueId, request).thenApply(response -> response.body()); + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public CompletableFuture deleteQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request, RequestOptions requestOptions) { + return this.rawClient.deleteQueueAssignment(queueId, request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/AsyncRawAnnotationQueuesClient.java b/src/main/java/com/langfuse/client/resources/annotationqueues/AsyncRawAnnotationQueuesClient.java new file mode 100644 index 0000000..f2637e9 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/AsyncRawAnnotationQueuesClient.java @@ -0,0 +1,920 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.annotationqueues; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueueItemsRequest; +import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueuesRequest; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueue; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueueAssignmentRequest; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueueItem; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueAssignmentResponse; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueItemRequest; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueRequest; +import com.langfuse.client.resources.annotationqueues.types.DeleteAnnotationQueueAssignmentResponse; +import com.langfuse.client.resources.annotationqueues.types.DeleteAnnotationQueueItemResponse; +import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueueItems; +import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueues; +import com.langfuse.client.resources.annotationqueues.types.UpdateAnnotationQueueItemRequest; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; + +public class AsyncRawAnnotationQueuesClient { + protected final ClientOptions clientOptions; + + public AsyncRawAnnotationQueuesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all annotation queues + */ + public CompletableFuture> listQueues() { + return listQueues(GetAnnotationQueuesRequest.builder().build()); + } + + /** + * Get all annotation queues + */ + public CompletableFuture> listQueues( + RequestOptions requestOptions) { + return listQueues(GetAnnotationQueuesRequest.builder().build(),requestOptions); + } + + /** + * Get all annotation queues + */ + public CompletableFuture> listQueues( + GetAnnotationQueuesRequest request) { + return listQueues(request,null); + } + + /** + * Get all annotation queues + */ + public CompletableFuture> listQueues( + GetAnnotationQueuesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedAnnotationQueues.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create an annotation queue + */ + public CompletableFuture> createQueue( + CreateAnnotationQueueRequest request) { + return createQueue(request,null); + } + + /** + * Create an annotation queue + */ + public CompletableFuture> createQueue( + CreateAnnotationQueueRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueue.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get an annotation queue by ID + */ + public CompletableFuture> getQueue( + String queueId) { + return getQueue(queueId,null); + } + + /** + * Get an annotation queue by ID + */ + public CompletableFuture> getQueue(String queueId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueue.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture> listQueueItems( + String queueId) { + return listQueueItems(queueId,GetAnnotationQueueItemsRequest.builder().build()); + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture> listQueueItems( + String queueId, RequestOptions requestOptions) { + return listQueueItems(queueId,GetAnnotationQueueItemsRequest.builder().build(),requestOptions); + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture> listQueueItems( + String queueId, GetAnnotationQueueItemsRequest request) { + return listQueueItems(queueId,request,null); + } + + /** + * Get items for a specific annotation queue + */ + public CompletableFuture> listQueueItems( + String queueId, GetAnnotationQueueItemsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items");if (request.getStatus().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "status", request.getStatus().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedAnnotationQueueItems.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a specific item from an annotation queue + */ + public CompletableFuture> getQueueItem( + String queueId, String itemId) { + return getQueueItem(queueId,itemId,null); + } + + /** + * Get a specific item from an annotation queue + */ + public CompletableFuture> getQueueItem( + String queueId, String itemId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items") + .addPathSegment(itemId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueueItem.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Add an item to an annotation queue + */ + public CompletableFuture> createQueueItem( + String queueId, CreateAnnotationQueueItemRequest request) { + return createQueueItem(queueId,request,null); + } + + /** + * Add an item to an annotation queue + */ + public CompletableFuture> createQueueItem( + String queueId, CreateAnnotationQueueItemRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueueItem.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Update an annotation queue item + */ + public CompletableFuture> updateQueueItem( + String queueId, String itemId) { + return updateQueueItem(queueId,itemId,UpdateAnnotationQueueItemRequest.builder().build()); + } + + /** + * Update an annotation queue item + */ + public CompletableFuture> updateQueueItem( + String queueId, String itemId, RequestOptions requestOptions) { + return updateQueueItem(queueId,itemId,UpdateAnnotationQueueItemRequest.builder().build(),requestOptions); + } + + /** + * Update an annotation queue item + */ + public CompletableFuture> updateQueueItem( + String queueId, String itemId, UpdateAnnotationQueueItemRequest request) { + return updateQueueItem(queueId,itemId,request,null); + } + + /** + * Update an annotation queue item + */ + public CompletableFuture> updateQueueItem( + String queueId, String itemId, UpdateAnnotationQueueItemRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items") + .addPathSegment(itemId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueueItem.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Remove an item from an annotation queue + */ + public CompletableFuture> deleteQueueItem( + String queueId, String itemId) { + return deleteQueueItem(queueId,itemId,null); + } + + /** + * Remove an item from an annotation queue + */ + public CompletableFuture> deleteQueueItem( + String queueId, String itemId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items") + .addPathSegment(itemId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteAnnotationQueueItemResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create an assignment for a user to an annotation queue + */ + public CompletableFuture> createQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request) { + return createQueueAssignment(queueId,request,null); + } + + /** + * Create an assignment for a user to an annotation queue + */ + public CompletableFuture> createQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("assignments");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateAnnotationQueueAssignmentResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public CompletableFuture> deleteQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request) { + return deleteQueueAssignment(queueId,request,null); + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public CompletableFuture> deleteQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("assignments");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteAnnotationQueueAssignmentResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/RawAnnotationQueuesClient.java b/src/main/java/com/langfuse/client/resources/annotationqueues/RawAnnotationQueuesClient.java new file mode 100644 index 0000000..7cf9212 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/RawAnnotationQueuesClient.java @@ -0,0 +1,733 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.annotationqueues; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueueItemsRequest; +import com.langfuse.client.resources.annotationqueues.requests.GetAnnotationQueuesRequest; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueue; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueueAssignmentRequest; +import com.langfuse.client.resources.annotationqueues.types.AnnotationQueueItem; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueAssignmentResponse; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueItemRequest; +import com.langfuse.client.resources.annotationqueues.types.CreateAnnotationQueueRequest; +import com.langfuse.client.resources.annotationqueues.types.DeleteAnnotationQueueAssignmentResponse; +import com.langfuse.client.resources.annotationqueues.types.DeleteAnnotationQueueItemResponse; +import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueueItems; +import com.langfuse.client.resources.annotationqueues.types.PaginatedAnnotationQueues; +import com.langfuse.client.resources.annotationqueues.types.UpdateAnnotationQueueItemRequest; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; + +public class RawAnnotationQueuesClient { + protected final ClientOptions clientOptions; + + public RawAnnotationQueuesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all annotation queues + */ + public LangfuseClientHttpResponse listQueues() { + return listQueues(GetAnnotationQueuesRequest.builder().build()); + } + + /** + * Get all annotation queues + */ + public LangfuseClientHttpResponse listQueues( + RequestOptions requestOptions) { + return listQueues(GetAnnotationQueuesRequest.builder().build(),requestOptions); + } + + /** + * Get all annotation queues + */ + public LangfuseClientHttpResponse listQueues( + GetAnnotationQueuesRequest request) { + return listQueues(request,null); + } + + /** + * Get all annotation queues + */ + public LangfuseClientHttpResponse listQueues( + GetAnnotationQueuesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedAnnotationQueues.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create an annotation queue + */ + public LangfuseClientHttpResponse createQueue( + CreateAnnotationQueueRequest request) { + return createQueue(request,null); + } + + /** + * Create an annotation queue + */ + public LangfuseClientHttpResponse createQueue( + CreateAnnotationQueueRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueue.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get an annotation queue by ID + */ + public LangfuseClientHttpResponse getQueue(String queueId) { + return getQueue(queueId,null); + } + + /** + * Get an annotation queue by ID + */ + public LangfuseClientHttpResponse getQueue(String queueId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueue.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get items for a specific annotation queue + */ + public LangfuseClientHttpResponse listQueueItems( + String queueId) { + return listQueueItems(queueId,GetAnnotationQueueItemsRequest.builder().build()); + } + + /** + * Get items for a specific annotation queue + */ + public LangfuseClientHttpResponse listQueueItems( + String queueId, RequestOptions requestOptions) { + return listQueueItems(queueId,GetAnnotationQueueItemsRequest.builder().build(),requestOptions); + } + + /** + * Get items for a specific annotation queue + */ + public LangfuseClientHttpResponse listQueueItems( + String queueId, GetAnnotationQueueItemsRequest request) { + return listQueueItems(queueId,request,null); + } + + /** + * Get items for a specific annotation queue + */ + public LangfuseClientHttpResponse listQueueItems( + String queueId, GetAnnotationQueueItemsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items");if (request.getStatus().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "status", request.getStatus().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedAnnotationQueueItems.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a specific item from an annotation queue + */ + public LangfuseClientHttpResponse getQueueItem(String queueId, + String itemId) { + return getQueueItem(queueId,itemId,null); + } + + /** + * Get a specific item from an annotation queue + */ + public LangfuseClientHttpResponse getQueueItem(String queueId, + String itemId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items") + .addPathSegment(itemId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueueItem.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Add an item to an annotation queue + */ + public LangfuseClientHttpResponse createQueueItem(String queueId, + CreateAnnotationQueueItemRequest request) { + return createQueueItem(queueId,request,null); + } + + /** + * Add an item to an annotation queue + */ + public LangfuseClientHttpResponse createQueueItem(String queueId, + CreateAnnotationQueueItemRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueueItem.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Update an annotation queue item + */ + public LangfuseClientHttpResponse updateQueueItem(String queueId, + String itemId) { + return updateQueueItem(queueId,itemId,UpdateAnnotationQueueItemRequest.builder().build()); + } + + /** + * Update an annotation queue item + */ + public LangfuseClientHttpResponse updateQueueItem(String queueId, + String itemId, RequestOptions requestOptions) { + return updateQueueItem(queueId,itemId,UpdateAnnotationQueueItemRequest.builder().build(),requestOptions); + } + + /** + * Update an annotation queue item + */ + public LangfuseClientHttpResponse updateQueueItem(String queueId, + String itemId, UpdateAnnotationQueueItemRequest request) { + return updateQueueItem(queueId,itemId,request,null); + } + + /** + * Update an annotation queue item + */ + public LangfuseClientHttpResponse updateQueueItem(String queueId, + String itemId, UpdateAnnotationQueueItemRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items") + .addPathSegment(itemId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, AnnotationQueueItem.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Remove an item from an annotation queue + */ + public LangfuseClientHttpResponse deleteQueueItem( + String queueId, String itemId) { + return deleteQueueItem(queueId,itemId,null); + } + + /** + * Remove an item from an annotation queue + */ + public LangfuseClientHttpResponse deleteQueueItem( + String queueId, String itemId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("items") + .addPathSegment(itemId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteAnnotationQueueItemResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create an assignment for a user to an annotation queue + */ + public LangfuseClientHttpResponse createQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request) { + return createQueueAssignment(queueId,request,null); + } + + /** + * Create an assignment for a user to an annotation queue + */ + public LangfuseClientHttpResponse createQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("assignments");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateAnnotationQueueAssignmentResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public LangfuseClientHttpResponse deleteQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request) { + return deleteQueueAssignment(queueId,request,null); + } + + /** + * Delete an assignment for a user to an annotation queue + */ + public LangfuseClientHttpResponse deleteQueueAssignment( + String queueId, AnnotationQueueAssignmentRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("annotation-queues") + .addPathSegment(queueId) + .addPathSegments("assignments");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteAnnotationQueueAssignmentResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueueItemsRequest.java b/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueueItemsRequest.java index 6ffba05..2fe5562 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueueItemsRequest.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueueItemsRequest.java @@ -119,6 +119,9 @@ public Builder from(GetAnnotationQueueItemsRequest other) { return this; } + /** + *

Filter by status

+ */ @JsonSetter( value = "status", nulls = Nulls.SKIP @@ -133,6 +136,9 @@ public Builder status(AnnotationQueueStatus status) { return this; } + /** + *

page number, starts at 1

+ */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -147,6 +153,9 @@ public Builder page(Integer page) { return this; } + /** + *

limit of items per page

+ */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -164,5 +173,15 @@ public Builder limit(Integer limit) { public GetAnnotationQueueItemsRequest build() { return new GetAnnotationQueueItemsRequest(status, page, limit, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueuesRequest.java b/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueuesRequest.java index 725b191..1d123ad 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueuesRequest.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/requests/GetAnnotationQueuesRequest.java @@ -104,6 +104,9 @@ public Builder from(GetAnnotationQueuesRequest other) { return this; } + /** + *

page number, starts at 1

+ */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder page(Integer page) { return this; } + /** + *

limit of items per page

+ */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder limit(Integer limit) { public GetAnnotationQueuesRequest build() { return new GetAnnotationQueuesRequest(page, limit, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueue.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueue.java index 6fed5b4..87a7fdb 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueue.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueue.java @@ -135,6 +135,10 @@ public interface UpdatedAtStage { public interface _FinalStage { AnnotationQueue build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage description(Optional description); _FinalStage description(String description); @@ -209,7 +213,9 @@ public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { @java.lang.Override public _FinalStage addAllScoreConfigIds(List scoreConfigIds) { - this.scoreConfigIds.addAll(scoreConfigIds); + if (scoreConfigIds != null) { + this.scoreConfigIds.addAll(scoreConfigIds); + } return this; } @@ -226,7 +232,9 @@ public _FinalStage addScoreConfigIds(String scoreConfigIds) { ) public _FinalStage scoreConfigIds(List scoreConfigIds) { this.scoreConfigIds.clear(); - this.scoreConfigIds.addAll(scoreConfigIds); + if (scoreConfigIds != null) { + this.scoreConfigIds.addAll(scoreConfigIds); + } return this; } @@ -250,5 +258,17 @@ public _FinalStage description(Optional description) { public AnnotationQueue build() { return new AnnotationQueue(id, name, description, scoreConfigIds, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueAssignmentRequest.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueAssignmentRequest.java index ac8b87e..bf76c59 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueAssignmentRequest.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueAssignmentRequest.java @@ -76,6 +76,10 @@ public interface UserIdStage { public interface _FinalStage { AnnotationQueueAssignmentRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -107,5 +111,17 @@ public _FinalStage userId(@NotNull String userId) { public AnnotationQueueAssignmentRequest build() { return new AnnotationQueueAssignmentRequest(userId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueItem.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueItem.java index 30c4352..1cf6601 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueItem.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueItem.java @@ -162,6 +162,10 @@ public interface UpdatedAtStage { public interface _FinalStage { AnnotationQueueItem build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage completedAt(Optional completedAt); _FinalStage completedAt(OffsetDateTime completedAt); @@ -275,5 +279,17 @@ public _FinalStage completedAt(Optional completedAt) { public AnnotationQueueItem build() { return new AnnotationQueueItem(id, queueId, objectId, objectType, status, completedAt, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueObjectType.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueObjectType.java index 1550df4..826237c 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueObjectType.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueObjectType.java @@ -4,25 +4,95 @@ package com.langfuse.client.resources.annotationqueues.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum AnnotationQueueObjectType { - TRACE("TRACE"), +public final class AnnotationQueueObjectType { + public static final AnnotationQueueObjectType OBSERVATION = new AnnotationQueueObjectType(Value.OBSERVATION, "OBSERVATION"); - OBSERVATION("OBSERVATION"), + public static final AnnotationQueueObjectType SESSION = new AnnotationQueueObjectType(Value.SESSION, "SESSION"); - SESSION("SESSION"); + public static final AnnotationQueueObjectType TRACE = new AnnotationQueueObjectType(Value.TRACE, "TRACE"); - private final String value; + private final Value value; - AnnotationQueueObjectType(String value) { + private final String string; + + AnnotationQueueObjectType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof AnnotationQueueObjectType && this.string.equals(((AnnotationQueueObjectType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case OBSERVATION: + return visitor.visitObservation(); + case SESSION: + return visitor.visitSession(); + case TRACE: + return visitor.visitTrace(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static AnnotationQueueObjectType valueOf(String value) { + switch (value) { + case "OBSERVATION": + return OBSERVATION; + case "SESSION": + return SESSION; + case "TRACE": + return TRACE; + default: + return new AnnotationQueueObjectType(Value.UNKNOWN, value); + } + } + + public enum Value { + TRACE, + + OBSERVATION, + + SESSION, + + UNKNOWN + } + + public interface Visitor { + T visitTrace(); + + T visitObservation(); + + T visitSession(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueStatus.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueStatus.java index 96e462e..25de609 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueStatus.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/AnnotationQueueStatus.java @@ -4,23 +4,85 @@ package com.langfuse.client.resources.annotationqueues.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum AnnotationQueueStatus { - PENDING("PENDING"), +public final class AnnotationQueueStatus { + public static final AnnotationQueueStatus COMPLETED = new AnnotationQueueStatus(Value.COMPLETED, "COMPLETED"); - COMPLETED("COMPLETED"); + public static final AnnotationQueueStatus PENDING = new AnnotationQueueStatus(Value.PENDING, "PENDING"); - private final String value; + private final Value value; - AnnotationQueueStatus(String value) { + private final String string; + + AnnotationQueueStatus(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof AnnotationQueueStatus && this.string.equals(((AnnotationQueueStatus) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case COMPLETED: + return visitor.visitCompleted(); + case PENDING: + return visitor.visitPending(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static AnnotationQueueStatus valueOf(String value) { + switch (value) { + case "COMPLETED": + return COMPLETED; + case "PENDING": + return PENDING; + default: + return new AnnotationQueueStatus(Value.UNKNOWN, value); + } + } + + public enum Value { + PENDING, + + COMPLETED, + + UNKNOWN + } + + public interface Visitor { + T visitPending(); + + T visitCompleted(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueAssignmentResponse.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueAssignmentResponse.java index 0b78f2d..e72dd8c 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueAssignmentResponse.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueAssignmentResponse.java @@ -100,6 +100,10 @@ public interface ProjectIdStage { public interface _FinalStage { CreateAnnotationQueueAssignmentResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -151,5 +155,17 @@ public _FinalStage projectId(@NotNull String projectId) { public CreateAnnotationQueueAssignmentResponse build() { return new CreateAnnotationQueueAssignmentResponse(userId, queueId, projectId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueItemRequest.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueItemRequest.java index b50b960..c70cfc6 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueItemRequest.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueItemRequest.java @@ -102,6 +102,13 @@ public interface ObjectTypeStage { public interface _FinalStage { CreateAnnotationQueueItemRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Defaults to PENDING for new queue items

+ */ _FinalStage status(Optional status); _FinalStage status(AnnotationQueueStatus status); @@ -155,6 +162,9 @@ public _FinalStage status(AnnotationQueueStatus status) { return this; } + /** + *

Defaults to PENDING for new queue items

+ */ @java.lang.Override @JsonSetter( value = "status", @@ -169,5 +179,17 @@ public _FinalStage status(Optional status) { public CreateAnnotationQueueItemRequest build() { return new CreateAnnotationQueueItemRequest(objectId, objectType, status, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueRequest.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueRequest.java index ef9ff80..9cc7684 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueRequest.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/CreateAnnotationQueueRequest.java @@ -97,6 +97,10 @@ public interface NameStage { public interface _FinalStage { CreateAnnotationQueueRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage description(Optional description); _FinalStage description(String description); @@ -141,7 +145,9 @@ public _FinalStage name(@NotNull String name) { @java.lang.Override public _FinalStage addAllScoreConfigIds(List scoreConfigIds) { - this.scoreConfigIds.addAll(scoreConfigIds); + if (scoreConfigIds != null) { + this.scoreConfigIds.addAll(scoreConfigIds); + } return this; } @@ -158,7 +164,9 @@ public _FinalStage addScoreConfigIds(String scoreConfigIds) { ) public _FinalStage scoreConfigIds(List scoreConfigIds) { this.scoreConfigIds.clear(); - this.scoreConfigIds.addAll(scoreConfigIds); + if (scoreConfigIds != null) { + this.scoreConfigIds.addAll(scoreConfigIds); + } return this; } @@ -182,5 +190,17 @@ public _FinalStage description(Optional description) { public CreateAnnotationQueueRequest build() { return new CreateAnnotationQueueRequest(name, description, scoreConfigIds, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueAssignmentResponse.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueAssignmentResponse.java index 191e7af..3750d5d 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueAssignmentResponse.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueAssignmentResponse.java @@ -75,6 +75,10 @@ public interface SuccessStage { public interface _FinalStage { DeleteAnnotationQueueAssignmentResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -106,5 +110,17 @@ public _FinalStage success(boolean success) { public DeleteAnnotationQueueAssignmentResponse build() { return new DeleteAnnotationQueueAssignmentResponse(success, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueItemResponse.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueItemResponse.java index 842bdb7..e8bd326 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueItemResponse.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/DeleteAnnotationQueueItemResponse.java @@ -88,6 +88,10 @@ public interface MessageStage { public interface _FinalStage { DeleteAnnotationQueueItemResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -129,5 +133,17 @@ public _FinalStage message(@NotNull String message) { public DeleteAnnotationQueueItemResponse build() { return new DeleteAnnotationQueueItemResponse(success, message, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueueItems.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueueItems.java index 083c787..b011524 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueueItems.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueueItems.java @@ -89,6 +89,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedAnnotationQueueItems build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(AnnotationQueueItem data); @@ -126,7 +130,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -143,7 +149,9 @@ public _FinalStage addData(AnnotationQueueItem data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -151,5 +159,17 @@ public _FinalStage data(List data) { public PaginatedAnnotationQueueItems build() { return new PaginatedAnnotationQueueItems(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueues.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueues.java index ebc0bbc..7e3491c 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueues.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/PaginatedAnnotationQueues.java @@ -89,6 +89,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedAnnotationQueues build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(AnnotationQueue data); @@ -126,7 +130,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -143,7 +149,9 @@ public _FinalStage addData(AnnotationQueue data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -151,5 +159,17 @@ public _FinalStage data(List data) { public PaginatedAnnotationQueues build() { return new PaginatedAnnotationQueues(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/annotationqueues/types/UpdateAnnotationQueueItemRequest.java b/src/main/java/com/langfuse/client/resources/annotationqueues/types/UpdateAnnotationQueueItemRequest.java index cd61d0d..6963f6d 100644 --- a/src/main/java/com/langfuse/client/resources/annotationqueues/types/UpdateAnnotationQueueItemRequest.java +++ b/src/main/java/com/langfuse/client/resources/annotationqueues/types/UpdateAnnotationQueueItemRequest.java @@ -103,5 +103,15 @@ public Builder status(AnnotationQueueStatus status) { public UpdateAnnotationQueueItemRequest build() { return new UpdateAnnotationQueueItemRequest(status, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/AsyncBlobStorageIntegrationsClient.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/AsyncBlobStorageIntegrationsClient.java new file mode 100644 index 0000000..bbd5665 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/AsyncBlobStorageIntegrationsClient.java @@ -0,0 +1,79 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.blobstorageintegrations; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationDeletionResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationsResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.CreateBlobStorageIntegrationRequest; + +public class AsyncBlobStorageIntegrationsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawBlobStorageIntegrationsClient rawClient; + + public AsyncBlobStorageIntegrationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawBlobStorageIntegrationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawBlobStorageIntegrationsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get all blob storage integrations for the organization (requires organization-scoped API key) + */ + public CompletableFuture getBlobStorageIntegrations() { + return this.rawClient.getBlobStorageIntegrations().thenApply(response -> response.body()); + } + + /** + * Get all blob storage integrations for the organization (requires organization-scoped API key) + */ + public CompletableFuture getBlobStorageIntegrations( + RequestOptions requestOptions) { + return this.rawClient.getBlobStorageIntegrations(requestOptions).thenApply(response -> response.body()); + } + + /** + * Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket. + */ + public CompletableFuture upsertBlobStorageIntegration( + CreateBlobStorageIntegrationRequest request) { + return this.rawClient.upsertBlobStorageIntegration(request).thenApply(response -> response.body()); + } + + /** + * Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket. + */ + public CompletableFuture upsertBlobStorageIntegration( + CreateBlobStorageIntegrationRequest request, RequestOptions requestOptions) { + return this.rawClient.upsertBlobStorageIntegration(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a blob storage integration by ID (requires organization-scoped API key) + */ + public CompletableFuture deleteBlobStorageIntegration( + String id) { + return this.rawClient.deleteBlobStorageIntegration(id).thenApply(response -> response.body()); + } + + /** + * Delete a blob storage integration by ID (requires organization-scoped API key) + */ + public CompletableFuture deleteBlobStorageIntegration( + String id, RequestOptions requestOptions) { + return this.rawClient.deleteBlobStorageIntegration(id, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/AsyncRawBlobStorageIntegrationsClient.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/AsyncRawBlobStorageIntegrationsClient.java new file mode 100644 index 0000000..4228c39 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/AsyncRawBlobStorageIntegrationsClient.java @@ -0,0 +1,277 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.blobstorageintegrations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationDeletionResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationsResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.CreateBlobStorageIntegrationRequest; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; + +public class AsyncRawBlobStorageIntegrationsClient { + protected final ClientOptions clientOptions; + + public AsyncRawBlobStorageIntegrationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all blob storage integrations for the organization (requires organization-scoped API key) + */ + public CompletableFuture> getBlobStorageIntegrations( + ) { + return getBlobStorageIntegrations(null); + } + + /** + * Get all blob storage integrations for the organization (requires organization-scoped API key) + */ + public CompletableFuture> getBlobStorageIntegrations( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/integrations/blob-storage") + ;if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BlobStorageIntegrationsResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket. + */ + public CompletableFuture> upsertBlobStorageIntegration( + CreateBlobStorageIntegrationRequest request) { + return upsertBlobStorageIntegration(request,null); + } + + /** + * Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket. + */ + public CompletableFuture> upsertBlobStorageIntegration( + CreateBlobStorageIntegrationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/integrations/blob-storage") + ;if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BlobStorageIntegrationResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a blob storage integration by ID (requires organization-scoped API key) + */ + public CompletableFuture> deleteBlobStorageIntegration( + String id) { + return deleteBlobStorageIntegration(id,null); + } + + /** + * Delete a blob storage integration by ID (requires organization-scoped API key) + */ + public CompletableFuture> deleteBlobStorageIntegration( + String id, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/integrations/blob-storage") + + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BlobStorageIntegrationDeletionResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/BlobStorageIntegrationsClient.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/BlobStorageIntegrationsClient.java index 9aaed7c..3252c7c 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/BlobStorageIntegrationsClient.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/BlobStorageIntegrationsClient.java @@ -4,89 +4,43 @@ package com.langfuse.client.resources.blobstorageintegrations; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationDeletionResponse; import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationResponse; import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationsResponse; import com.langfuse.client.resources.blobstorageintegrations.types.CreateBlobStorageIntegrationRequest; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; public class BlobStorageIntegrationsClient { protected final ClientOptions clientOptions; + private final RawBlobStorageIntegrationsClient rawClient; + public BlobStorageIntegrationsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawBlobStorageIntegrationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawBlobStorageIntegrationsClient withRawResponse() { + return this.rawClient; } /** * Get all blob storage integrations for the organization (requires organization-scoped API key) */ public BlobStorageIntegrationsResponse getBlobStorageIntegrations() { - return getBlobStorageIntegrations(null); + return this.rawClient.getBlobStorageIntegrations().body(); } /** * Get all blob storage integrations for the organization (requires organization-scoped API key) */ public BlobStorageIntegrationsResponse getBlobStorageIntegrations(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/integrations/blob-storage") - - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), BlobStorageIntegrationsResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getBlobStorageIntegrations(requestOptions).body(); } /** @@ -94,7 +48,7 @@ public BlobStorageIntegrationsResponse getBlobStorageIntegrations(RequestOptions */ public BlobStorageIntegrationResponse upsertBlobStorageIntegration( CreateBlobStorageIntegrationRequest request) { - return upsertBlobStorageIntegration(request,null); + return this.rawClient.upsertBlobStorageIntegration(request).body(); } /** @@ -102,58 +56,14 @@ public BlobStorageIntegrationResponse upsertBlobStorageIntegration( */ public BlobStorageIntegrationResponse upsertBlobStorageIntegration( CreateBlobStorageIntegrationRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/integrations/blob-storage") - - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), BlobStorageIntegrationResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.upsertBlobStorageIntegration(request, requestOptions).body(); } /** * Delete a blob storage integration by ID (requires organization-scoped API key) */ public BlobStorageIntegrationDeletionResponse deleteBlobStorageIntegration(String id) { - return deleteBlobStorageIntegration(id,null); + return this.rawClient.deleteBlobStorageIntegration(id).body(); } /** @@ -161,44 +71,6 @@ public BlobStorageIntegrationDeletionResponse deleteBlobStorageIntegration(Strin */ public BlobStorageIntegrationDeletionResponse deleteBlobStorageIntegration(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/integrations/blob-storage") - - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), BlobStorageIntegrationDeletionResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.deleteBlobStorageIntegration(id, requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/RawBlobStorageIntegrationsClient.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/RawBlobStorageIntegrationsClient.java new file mode 100644 index 0000000..fd6c7c1 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/RawBlobStorageIntegrationsClient.java @@ -0,0 +1,217 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.blobstorageintegrations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationDeletionResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.BlobStorageIntegrationsResponse; +import com.langfuse.client.resources.blobstorageintegrations.types.CreateBlobStorageIntegrationRequest; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; + +public class RawBlobStorageIntegrationsClient { + protected final ClientOptions clientOptions; + + public RawBlobStorageIntegrationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all blob storage integrations for the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getBlobStorageIntegrations() { + return getBlobStorageIntegrations(null); + } + + /** + * Get all blob storage integrations for the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getBlobStorageIntegrations( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/integrations/blob-storage") + ;if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BlobStorageIntegrationsResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket. + */ + public LangfuseClientHttpResponse upsertBlobStorageIntegration( + CreateBlobStorageIntegrationRequest request) { + return upsertBlobStorageIntegration(request,null); + } + + /** + * Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket. + */ + public LangfuseClientHttpResponse upsertBlobStorageIntegration( + CreateBlobStorageIntegrationRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/integrations/blob-storage") + ;if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BlobStorageIntegrationResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a blob storage integration by ID (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse deleteBlobStorageIntegration( + String id) { + return deleteBlobStorageIntegration(id,null); + } + + /** + * Delete a blob storage integration by ID (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse deleteBlobStorageIntegration( + String id, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/integrations/blob-storage") + + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, BlobStorageIntegrationDeletionResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportFrequency.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportFrequency.java index c5b8219..bb9598a 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportFrequency.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportFrequency.java @@ -4,25 +4,95 @@ package com.langfuse.client.resources.blobstorageintegrations.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum BlobStorageExportFrequency { - HOURLY("hourly"), +public final class BlobStorageExportFrequency { + public static final BlobStorageExportFrequency HOURLY = new BlobStorageExportFrequency(Value.HOURLY, "hourly"); - DAILY("daily"), + public static final BlobStorageExportFrequency DAILY = new BlobStorageExportFrequency(Value.DAILY, "daily"); - WEEKLY("weekly"); + public static final BlobStorageExportFrequency WEEKLY = new BlobStorageExportFrequency(Value.WEEKLY, "weekly"); - private final String value; + private final Value value; - BlobStorageExportFrequency(String value) { + private final String string; + + BlobStorageExportFrequency(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof BlobStorageExportFrequency && this.string.equals(((BlobStorageExportFrequency) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case HOURLY: + return visitor.visitHourly(); + case DAILY: + return visitor.visitDaily(); + case WEEKLY: + return visitor.visitWeekly(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static BlobStorageExportFrequency valueOf(String value) { + switch (value) { + case "hourly": + return HOURLY; + case "daily": + return DAILY; + case "weekly": + return WEEKLY; + default: + return new BlobStorageExportFrequency(Value.UNKNOWN, value); + } + } + + public enum Value { + HOURLY, + + DAILY, + + WEEKLY, + + UNKNOWN + } + + public interface Visitor { + T visitHourly(); + + T visitDaily(); + + T visitWeekly(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportMode.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportMode.java index eddf532..6f7c510 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportMode.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageExportMode.java @@ -4,25 +4,95 @@ package com.langfuse.client.resources.blobstorageintegrations.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum BlobStorageExportMode { - FULL_HISTORY("FULL_HISTORY"), +public final class BlobStorageExportMode { + public static final BlobStorageExportMode FULL_HISTORY = new BlobStorageExportMode(Value.FULL_HISTORY, "FULL_HISTORY"); - FROM_TODAY("FROM_TODAY"), + public static final BlobStorageExportMode FROM_CUSTOM_DATE = new BlobStorageExportMode(Value.FROM_CUSTOM_DATE, "FROM_CUSTOM_DATE"); - FROM_CUSTOM_DATE("FROM_CUSTOM_DATE"); + public static final BlobStorageExportMode FROM_TODAY = new BlobStorageExportMode(Value.FROM_TODAY, "FROM_TODAY"); - private final String value; + private final Value value; - BlobStorageExportMode(String value) { + private final String string; + + BlobStorageExportMode(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof BlobStorageExportMode && this.string.equals(((BlobStorageExportMode) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FULL_HISTORY: + return visitor.visitFullHistory(); + case FROM_CUSTOM_DATE: + return visitor.visitFromCustomDate(); + case FROM_TODAY: + return visitor.visitFromToday(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static BlobStorageExportMode valueOf(String value) { + switch (value) { + case "FULL_HISTORY": + return FULL_HISTORY; + case "FROM_CUSTOM_DATE": + return FROM_CUSTOM_DATE; + case "FROM_TODAY": + return FROM_TODAY; + default: + return new BlobStorageExportMode(Value.UNKNOWN, value); + } + } + + public enum Value { + FULL_HISTORY, + + FROM_TODAY, + + FROM_CUSTOM_DATE, + + UNKNOWN + } + + public interface Visitor { + T visitFullHistory(); + + T visitFromToday(); + + T visitFromCustomDate(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationDeletionResponse.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationDeletionResponse.java index 31a2b8a..e19c30c 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationDeletionResponse.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationDeletionResponse.java @@ -76,6 +76,10 @@ public interface MessageStage { public interface _FinalStage { BlobStorageIntegrationDeletionResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -107,5 +111,17 @@ public _FinalStage message(@NotNull String message) { public BlobStorageIntegrationDeletionResponse build() { return new BlobStorageIntegrationDeletionResponse(message, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationFileType.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationFileType.java index dac1c0b..5fbb5c2 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationFileType.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationFileType.java @@ -4,25 +4,95 @@ package com.langfuse.client.resources.blobstorageintegrations.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum BlobStorageIntegrationFileType { - JSON("JSON"), +public final class BlobStorageIntegrationFileType { + public static final BlobStorageIntegrationFileType JSONL = new BlobStorageIntegrationFileType(Value.JSONL, "JSONL"); - CSV("CSV"), + public static final BlobStorageIntegrationFileType JSON = new BlobStorageIntegrationFileType(Value.JSON, "JSON"); - JSONL("JSONL"); + public static final BlobStorageIntegrationFileType CSV = new BlobStorageIntegrationFileType(Value.CSV, "CSV"); - private final String value; + private final Value value; - BlobStorageIntegrationFileType(String value) { + private final String string; + + BlobStorageIntegrationFileType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof BlobStorageIntegrationFileType && this.string.equals(((BlobStorageIntegrationFileType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case JSONL: + return visitor.visitJsonl(); + case JSON: + return visitor.visitJson(); + case CSV: + return visitor.visitCsv(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static BlobStorageIntegrationFileType valueOf(String value) { + switch (value) { + case "JSONL": + return JSONL; + case "JSON": + return JSON; + case "CSV": + return CSV; + default: + return new BlobStorageIntegrationFileType(Value.UNKNOWN, value); + } + } + + public enum Value { + JSON, + + CSV, + + JSONL, + + UNKNOWN + } + + public interface Visitor { + T visitJson(); + + T visitCsv(); + + T visitJsonl(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationResponse.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationResponse.java index 258c48b..a5c49ba 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationResponse.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationResponse.java @@ -270,6 +270,10 @@ public interface UpdatedAtStage { public interface _FinalStage { BlobStorageIntegrationResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage endpoint(Optional endpoint); _FinalStage endpoint(String endpoint); @@ -535,5 +539,17 @@ public _FinalStage endpoint(Optional endpoint) { public BlobStorageIntegrationResponse build() { return new BlobStorageIntegrationResponse(id, projectId, type, bucketName, endpoint, region, accessKeyId, prefix, exportFrequency, enabled, forcePathStyle, fileType, exportMode, exportStartDate, nextSyncAt, lastSyncAt, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationType.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationType.java index 74d1e1c..53cdf55 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationType.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationType.java @@ -4,25 +4,95 @@ package com.langfuse.client.resources.blobstorageintegrations.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum BlobStorageIntegrationType { - S_3("S3"), +public final class BlobStorageIntegrationType { + public static final BlobStorageIntegrationType S3COMPATIBLE = new BlobStorageIntegrationType(Value.S3COMPATIBLE, "S3_COMPATIBLE"); - S_3_COMPATIBLE("S3_COMPATIBLE"), + public static final BlobStorageIntegrationType S3 = new BlobStorageIntegrationType(Value.S3, "S3"); - AZURE_BLOB_STORAGE("AZURE_BLOB_STORAGE"); + public static final BlobStorageIntegrationType AZURE_BLOB_STORAGE = new BlobStorageIntegrationType(Value.AZURE_BLOB_STORAGE, "AZURE_BLOB_STORAGE"); - private final String value; + private final Value value; - BlobStorageIntegrationType(String value) { + private final String string; + + BlobStorageIntegrationType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof BlobStorageIntegrationType && this.string.equals(((BlobStorageIntegrationType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case S3COMPATIBLE: + return visitor.visitS3Compatible(); + case S3: + return visitor.visitS3(); + case AZURE_BLOB_STORAGE: + return visitor.visitAzureBlobStorage(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static BlobStorageIntegrationType valueOf(String value) { + switch (value) { + case "S3_COMPATIBLE": + return S3COMPATIBLE; + case "S3": + return S3; + case "AZURE_BLOB_STORAGE": + return AZURE_BLOB_STORAGE; + default: + return new BlobStorageIntegrationType(Value.UNKNOWN, value); + } + } + + public enum Value { + S3, + + S3COMPATIBLE, + + AZURE_BLOB_STORAGE, + + UNKNOWN + } + + public interface Visitor { + T visitS3(); + + T visitS3Compatible(); + + T visitAzureBlobStorage(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationsResponse.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationsResponse.java index 84c1d2a..766328c 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationsResponse.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/BlobStorageIntegrationsResponse.java @@ -93,7 +93,9 @@ public Builder from(BlobStorageIntegrationsResponse other) { ) public Builder data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -103,12 +105,24 @@ public Builder addData(BlobStorageIntegrationResponse data) { } public Builder addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } public BlobStorageIntegrationsResponse build() { return new BlobStorageIntegrationsResponse(data, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/CreateBlobStorageIntegrationRequest.java b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/CreateBlobStorageIntegrationRequest.java index ba9958d..7c3a28b 100644 --- a/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/CreateBlobStorageIntegrationRequest.java +++ b/src/main/java/com/langfuse/client/resources/blobstorageintegrations/types/CreateBlobStorageIntegrationRequest.java @@ -210,6 +210,9 @@ public static ProjectIdStage builder() { } public interface ProjectIdStage { + /** + *

ID of the project in which to configure the blob storage integration

+ */ TypeStage projectId(@NotNull String projectId); Builder from(CreateBlobStorageIntegrationRequest other); @@ -220,10 +223,16 @@ public interface TypeStage { } public interface BucketNameStage { + /** + *

Name of the storage bucket

+ */ RegionStage bucketName(@NotNull String bucketName); } public interface RegionStage { + /** + *

Storage region

+ */ ExportFrequencyStage region(@NotNull String region); } @@ -232,10 +241,16 @@ public interface ExportFrequencyStage { } public interface EnabledStage { + /** + *

Whether the integration is active

+ */ ForcePathStyleStage enabled(boolean enabled); } public interface ForcePathStyleStage { + /** + *

Use path-style URLs for S3 requests

+ */ FileTypeStage forcePathStyle(boolean forcePathStyle); } @@ -250,22 +265,41 @@ public interface ExportModeStage { public interface _FinalStage { CreateBlobStorageIntegrationRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Custom endpoint URL (required for S3_COMPATIBLE type)

+ */ _FinalStage endpoint(Optional endpoint); _FinalStage endpoint(String endpoint); + /** + *

Access key ID for authentication

+ */ _FinalStage accessKeyId(Optional accessKeyId); _FinalStage accessKeyId(String accessKeyId); + /** + *

Secret access key for authentication (will be encrypted when stored)

+ */ _FinalStage secretAccessKey(Optional secretAccessKey); _FinalStage secretAccessKey(String secretAccessKey); + /** + *

Path prefix for exported files (must end with forward slash if provided)

+ */ _FinalStage prefix(Optional prefix); _FinalStage prefix(String prefix); + /** + *

Custom start date for exports (required when exportMode is FROM_CUSTOM_DATE)

+ */ _FinalStage exportStartDate(Optional exportStartDate); _FinalStage exportStartDate(OffsetDateTime exportStartDate); @@ -329,6 +363,7 @@ public Builder from(CreateBlobStorageIntegrationRequest other) { } /** + *

ID of the project in which to configure the blob storage integration

*

ID of the project in which to configure the blob storage integration

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -347,6 +382,7 @@ public BucketNameStage type(@NotNull BlobStorageIntegrationType type) { } /** + *

Name of the storage bucket

*

Name of the storage bucket

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -358,6 +394,7 @@ public RegionStage bucketName(@NotNull String bucketName) { } /** + *

Storage region

*

Storage region

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -376,6 +413,7 @@ public EnabledStage exportFrequency(@NotNull BlobStorageExportFrequency exportFr } /** + *

Whether the integration is active

*

Whether the integration is active

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -387,6 +425,7 @@ public ForcePathStyleStage enabled(boolean enabled) { } /** + *

Use path-style URLs for S3 requests

*

Use path-style URLs for S3 requests

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -421,6 +460,9 @@ public _FinalStage exportStartDate(OffsetDateTime exportStartDate) { return this; } + /** + *

Custom start date for exports (required when exportMode is FROM_CUSTOM_DATE)

+ */ @java.lang.Override @JsonSetter( value = "exportStartDate", @@ -441,6 +483,9 @@ public _FinalStage prefix(String prefix) { return this; } + /** + *

Path prefix for exported files (must end with forward slash if provided)

+ */ @java.lang.Override @JsonSetter( value = "prefix", @@ -461,6 +506,9 @@ public _FinalStage secretAccessKey(String secretAccessKey) { return this; } + /** + *

Secret access key for authentication (will be encrypted when stored)

+ */ @java.lang.Override @JsonSetter( value = "secretAccessKey", @@ -481,6 +529,9 @@ public _FinalStage accessKeyId(String accessKeyId) { return this; } + /** + *

Access key ID for authentication

+ */ @java.lang.Override @JsonSetter( value = "accessKeyId", @@ -501,6 +552,9 @@ public _FinalStage endpoint(String endpoint) { return this; } + /** + *

Custom endpoint URL (required for S3_COMPATIBLE type)

+ */ @java.lang.Override @JsonSetter( value = "endpoint", @@ -515,5 +569,17 @@ public _FinalStage endpoint(Optional endpoint) { public CreateBlobStorageIntegrationRequest build() { return new CreateBlobStorageIntegrationRequest(projectId, type, bucketName, endpoint, region, accessKeyId, secretAccessKey, prefix, exportFrequency, enabled, forcePathStyle, fileType, exportMode, exportStartDate, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/comments/AsyncCommentsClient.java b/src/main/java/com/langfuse/client/resources/comments/AsyncCommentsClient.java new file mode 100644 index 0000000..78c27b9 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/comments/AsyncCommentsClient.java @@ -0,0 +1,91 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.comments; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.comments.requests.GetCommentsRequest; +import com.langfuse.client.resources.comments.types.CreateCommentRequest; +import com.langfuse.client.resources.comments.types.CreateCommentResponse; +import com.langfuse.client.resources.comments.types.GetCommentsResponse; +import com.langfuse.client.resources.commons.types.Comment; + +public class AsyncCommentsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawCommentsClient rawClient; + + public AsyncCommentsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawCommentsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawCommentsClient withRawResponse() { + return this.rawClient; + } + + /** + * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). + */ + public CompletableFuture create(CreateCommentRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). + */ + public CompletableFuture create(CreateCommentRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all comments + */ + public CompletableFuture get() { + return this.rawClient.get().thenApply(response -> response.body()); + } + + /** + * Get all comments + */ + public CompletableFuture get(RequestOptions requestOptions) { + return this.rawClient.get(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all comments + */ + public CompletableFuture get(GetCommentsRequest request) { + return this.rawClient.get(request).thenApply(response -> response.body()); + } + + /** + * Get all comments + */ + public CompletableFuture get(GetCommentsRequest request, + RequestOptions requestOptions) { + return this.rawClient.get(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a comment by id + */ + public CompletableFuture getById(String commentId) { + return this.rawClient.getById(commentId).thenApply(response -> response.body()); + } + + /** + * Get a comment by id + */ + public CompletableFuture getById(String commentId, RequestOptions requestOptions) { + return this.rawClient.getById(commentId, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/comments/AsyncRawCommentsClient.java b/src/main/java/com/langfuse/client/resources/comments/AsyncRawCommentsClient.java new file mode 100644 index 0000000..85b9891 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/comments/AsyncRawCommentsClient.java @@ -0,0 +1,308 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.comments; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.comments.requests.GetCommentsRequest; +import com.langfuse.client.resources.comments.types.CreateCommentRequest; +import com.langfuse.client.resources.comments.types.CreateCommentResponse; +import com.langfuse.client.resources.comments.types.GetCommentsResponse; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Comment; + +public class AsyncRawCommentsClient { + protected final ClientOptions clientOptions; + + public AsyncRawCommentsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). + */ + public CompletableFuture> create( + CreateCommentRequest request) { + return create(request,null); + } + + /** + * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). + */ + public CompletableFuture> create( + CreateCommentRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("comments");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateCommentResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get all comments + */ + public CompletableFuture> get() { + return get(GetCommentsRequest.builder().build()); + } + + /** + * Get all comments + */ + public CompletableFuture> get( + RequestOptions requestOptions) { + return get(GetCommentsRequest.builder().build(),requestOptions); + } + + /** + * Get all comments + */ + public CompletableFuture> get( + GetCommentsRequest request) { + return get(request,null); + } + + /** + * Get all comments + */ + public CompletableFuture> get( + GetCommentsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("comments");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getObjectType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "objectType", request.getObjectType().get(), false); + } + if (request.getObjectId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "objectId", request.getObjectId().get(), false); + } + if (request.getAuthorUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "authorUserId", request.getAuthorUserId().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetCommentsResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a comment by id + */ + public CompletableFuture> getById(String commentId) { + return getById(commentId,null); + } + + /** + * Get a comment by id + */ + public CompletableFuture> getById(String commentId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("comments") + .addPathSegment(commentId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Comment.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/comments/CommentsClient.java b/src/main/java/com/langfuse/client/resources/comments/CommentsClient.java index 53d5403..6e44920 100644 --- a/src/main/java/com/langfuse/client/resources/comments/CommentsClient.java +++ b/src/main/java/com/langfuse/client/resources/comments/CommentsClient.java @@ -4,220 +4,85 @@ package com.langfuse.client.resources.comments; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; import com.langfuse.client.resources.comments.requests.GetCommentsRequest; import com.langfuse.client.resources.comments.types.CreateCommentRequest; import com.langfuse.client.resources.comments.types.CreateCommentResponse; import com.langfuse.client.resources.comments.types.GetCommentsResponse; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.Comment; public class CommentsClient { protected final ClientOptions clientOptions; + private final RawCommentsClient rawClient; + public CommentsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawCommentsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawCommentsClient withRawResponse() { + return this.rawClient; } /** * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). */ public CreateCommentResponse create(CreateCommentRequest request) { - return create(request,null); + return this.rawClient.create(request).body(); } /** * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). */ public CreateCommentResponse create(CreateCommentRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("comments") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateCommentResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * Get all comments */ public GetCommentsResponse get() { - return get(GetCommentsRequest.builder().build()); + return this.rawClient.get().body(); + } + + /** + * Get all comments + */ + public GetCommentsResponse get(RequestOptions requestOptions) { + return this.rawClient.get(requestOptions).body(); } /** * Get all comments */ public GetCommentsResponse get(GetCommentsRequest request) { - return get(request,null); + return this.rawClient.get(request).body(); } /** * Get all comments */ public GetCommentsResponse get(GetCommentsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("comments");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - if (request.getObjectType().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "objectType", request.getObjectType().get(), false); - } - if (request.getObjectId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "objectId", request.getObjectId().get(), false); - } - if (request.getAuthorUserId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "authorUserId", request.getAuthorUserId().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetCommentsResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.get(request, requestOptions).body(); + } - /** - * Get a comment by id - */ - public Comment getById(String commentId) { - return getById(commentId,null); - } + /** + * Get a comment by id + */ + public Comment getById(String commentId) { + return this.rawClient.getById(commentId).body(); + } - /** - * Get a comment by id - */ - public Comment getById(String commentId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("comments") - .addPathSegment(commentId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Comment.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a comment by id + */ + public Comment getById(String commentId, RequestOptions requestOptions) { + return this.rawClient.getById(commentId, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/comments/RawCommentsClient.java b/src/main/java/com/langfuse/client/resources/comments/RawCommentsClient.java new file mode 100644 index 0000000..dc1b6f8 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/comments/RawCommentsClient.java @@ -0,0 +1,246 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.comments; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.comments.requests.GetCommentsRequest; +import com.langfuse.client.resources.comments.types.CreateCommentRequest; +import com.langfuse.client.resources.comments.types.CreateCommentResponse; +import com.langfuse.client.resources.comments.types.GetCommentsResponse; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Comment; + +public class RawCommentsClient { + protected final ClientOptions clientOptions; + + public RawCommentsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). + */ + public LangfuseClientHttpResponse create(CreateCommentRequest request) { + return create(request,null); + } + + /** + * Create a comment. Comments may be attached to different object types (trace, observation, session, prompt). + */ + public LangfuseClientHttpResponse create(CreateCommentRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("comments");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateCommentResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get all comments + */ + public LangfuseClientHttpResponse get() { + return get(GetCommentsRequest.builder().build()); + } + + /** + * Get all comments + */ + public LangfuseClientHttpResponse get(RequestOptions requestOptions) { + return get(GetCommentsRequest.builder().build(),requestOptions); + } + + /** + * Get all comments + */ + public LangfuseClientHttpResponse get(GetCommentsRequest request) { + return get(request,null); + } + + /** + * Get all comments + */ + public LangfuseClientHttpResponse get(GetCommentsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("comments");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getObjectType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "objectType", request.getObjectType().get(), false); + } + if (request.getObjectId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "objectId", request.getObjectId().get(), false); + } + if (request.getAuthorUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "authorUserId", request.getAuthorUserId().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetCommentsResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a comment by id + */ + public LangfuseClientHttpResponse getById(String commentId) { + return getById(commentId,null); + } + + /** + * Get a comment by id + */ + public LangfuseClientHttpResponse getById(String commentId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("comments") + .addPathSegment(commentId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Comment.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/comments/requests/GetCommentsRequest.java b/src/main/java/com/langfuse/client/resources/comments/requests/GetCommentsRequest.java index 02cfc9c..9142b86 100644 --- a/src/main/java/com/langfuse/client/resources/comments/requests/GetCommentsRequest.java +++ b/src/main/java/com/langfuse/client/resources/comments/requests/GetCommentsRequest.java @@ -147,6 +147,9 @@ public Builder from(GetCommentsRequest other) { return this; } + /** + *

Page number, starts at 1.

+ */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -161,6 +164,9 @@ public Builder page(Integer page) { return this; } + /** + *

Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit

+ */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -175,6 +181,9 @@ public Builder limit(Integer limit) { return this; } + /** + *

Filter comments by object type (trace, observation, session, prompt).

+ */ @JsonSetter( value = "objectType", nulls = Nulls.SKIP @@ -189,6 +198,9 @@ public Builder objectType(String objectType) { return this; } + /** + *

Filter comments by object id. If objectType is not provided, an error will be thrown.

+ */ @JsonSetter( value = "objectId", nulls = Nulls.SKIP @@ -203,6 +215,9 @@ public Builder objectId(String objectId) { return this; } + /** + *

Filter comments by author user id.

+ */ @JsonSetter( value = "authorUserId", nulls = Nulls.SKIP @@ -220,5 +235,15 @@ public Builder authorUserId(String authorUserId) { public GetCommentsRequest build() { return new GetCommentsRequest(page, limit, objectType, objectId, authorUserId, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentRequest.java b/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentRequest.java index 0763a8f..18b15b1 100644 --- a/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentRequest.java +++ b/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentRequest.java @@ -118,26 +118,45 @@ public static ProjectIdStage builder() { } public interface ProjectIdStage { + /** + *

The id of the project to attach the comment to.

+ */ ObjectTypeStage projectId(@NotNull String projectId); Builder from(CreateCommentRequest other); } public interface ObjectTypeStage { + /** + *

The type of the object to attach the comment to (trace, observation, session, prompt).

+ */ ObjectIdStage objectType(@NotNull String objectType); } public interface ObjectIdStage { + /** + *

The id of the object to attach the comment to. If this does not reference a valid existing object, an error will be thrown.

+ */ ContentStage objectId(@NotNull String objectId); } public interface ContentStage { + /** + *

The content of the comment. May include markdown. Currently limited to 5000 characters.

+ */ _FinalStage content(@NotNull String content); } public interface _FinalStage { CreateCommentRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The id of the user who created the comment.

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); @@ -174,6 +193,7 @@ public Builder from(CreateCommentRequest other) { } /** + *

The id of the project to attach the comment to.

*

The id of the project to attach the comment to.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -185,6 +205,7 @@ public ObjectTypeStage projectId(@NotNull String projectId) { } /** + *

The type of the object to attach the comment to (trace, observation, session, prompt).

*

The type of the object to attach the comment to (trace, observation, session, prompt).

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -196,6 +217,7 @@ public ObjectIdStage objectType(@NotNull String objectType) { } /** + *

The id of the object to attach the comment to. If this does not reference a valid existing object, an error will be thrown.

*

The id of the object to attach the comment to. If this does not reference a valid existing object, an error will be thrown.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -207,6 +229,7 @@ public ContentStage objectId(@NotNull String objectId) { } /** + *

The content of the comment. May include markdown. Currently limited to 5000 characters.

*

The content of the comment. May include markdown. Currently limited to 5000 characters.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -227,6 +250,9 @@ public _FinalStage authorUserId(String authorUserId) { return this; } + /** + *

The id of the user who created the comment.

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -241,5 +267,17 @@ public _FinalStage authorUserId(Optional authorUserId) { public CreateCommentRequest build() { return new CreateCommentRequest(projectId, objectType, objectId, content, authorUserId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentResponse.java b/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentResponse.java index 654bbf7..43cc0e6 100644 --- a/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentResponse.java +++ b/src/main/java/com/langfuse/client/resources/comments/types/CreateCommentResponse.java @@ -71,6 +71,9 @@ public static IdStage builder() { } public interface IdStage { + /** + *

The id of the created object in Langfuse

+ */ _FinalStage id(@NotNull String id); Builder from(CreateCommentResponse other); @@ -78,6 +81,10 @@ public interface IdStage { public interface _FinalStage { CreateCommentResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -99,6 +106,7 @@ public Builder from(CreateCommentResponse other) { } /** + *

The id of the created object in Langfuse

*

The id of the created object in Langfuse

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -113,5 +121,17 @@ public _FinalStage id(@NotNull String id) { public CreateCommentResponse build() { return new CreateCommentResponse(id, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/comments/types/GetCommentsResponse.java b/src/main/java/com/langfuse/client/resources/comments/types/GetCommentsResponse.java index fc2bb17..733c274 100644 --- a/src/main/java/com/langfuse/client/resources/comments/types/GetCommentsResponse.java +++ b/src/main/java/com/langfuse/client/resources/comments/types/GetCommentsResponse.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { GetCommentsResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(Comment data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(Comment data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public GetCommentsResponse build() { return new GetCommentsResponse(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/errors/AccessDeniedError.java b/src/main/java/com/langfuse/client/resources/commons/errors/AccessDeniedError.java index c1dec8f..a2d13e0 100644 --- a/src/main/java/com/langfuse/client/resources/commons/errors/AccessDeniedError.java +++ b/src/main/java/com/langfuse/client/resources/commons/errors/AccessDeniedError.java @@ -6,6 +6,7 @@ import com.langfuse.client.core.LangfuseClientApiException; import java.lang.Object; +import okhttp3.Response; public final class AccessDeniedError extends LangfuseClientApiException { /** @@ -18,6 +19,11 @@ public AccessDeniedError(Object body) { this.body = body; } + public AccessDeniedError(Object body, Response rawResponse) { + super("AccessDeniedError", 403, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/langfuse/client/resources/commons/errors/Error.java b/src/main/java/com/langfuse/client/resources/commons/errors/Error.java index dfd053f..a3d35b5 100644 --- a/src/main/java/com/langfuse/client/resources/commons/errors/Error.java +++ b/src/main/java/com/langfuse/client/resources/commons/errors/Error.java @@ -6,6 +6,7 @@ import com.langfuse.client.core.LangfuseClientApiException; import java.lang.Object; +import okhttp3.Response; public final class Error extends LangfuseClientApiException { /** @@ -18,6 +19,11 @@ public Error(Object body) { this.body = body; } + public Error(Object body, Response rawResponse) { + super("Error", 400, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/langfuse/client/resources/commons/errors/MethodNotAllowedError.java b/src/main/java/com/langfuse/client/resources/commons/errors/MethodNotAllowedError.java index 027be1f..ca337bf 100644 --- a/src/main/java/com/langfuse/client/resources/commons/errors/MethodNotAllowedError.java +++ b/src/main/java/com/langfuse/client/resources/commons/errors/MethodNotAllowedError.java @@ -6,6 +6,7 @@ import com.langfuse.client.core.LangfuseClientApiException; import java.lang.Object; +import okhttp3.Response; public final class MethodNotAllowedError extends LangfuseClientApiException { /** @@ -18,6 +19,11 @@ public MethodNotAllowedError(Object body) { this.body = body; } + public MethodNotAllowedError(Object body, Response rawResponse) { + super("MethodNotAllowedError", 405, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/langfuse/client/resources/commons/errors/NotFoundError.java b/src/main/java/com/langfuse/client/resources/commons/errors/NotFoundError.java index f971587..72cb1d3 100644 --- a/src/main/java/com/langfuse/client/resources/commons/errors/NotFoundError.java +++ b/src/main/java/com/langfuse/client/resources/commons/errors/NotFoundError.java @@ -6,6 +6,7 @@ import com.langfuse.client.core.LangfuseClientApiException; import java.lang.Object; +import okhttp3.Response; public final class NotFoundError extends LangfuseClientApiException { /** @@ -18,6 +19,11 @@ public NotFoundError(Object body) { this.body = body; } + public NotFoundError(Object body, Response rawResponse) { + super("NotFoundError", 404, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/langfuse/client/resources/commons/errors/UnauthorizedError.java b/src/main/java/com/langfuse/client/resources/commons/errors/UnauthorizedError.java index 9429922..09cce67 100644 --- a/src/main/java/com/langfuse/client/resources/commons/errors/UnauthorizedError.java +++ b/src/main/java/com/langfuse/client/resources/commons/errors/UnauthorizedError.java @@ -6,6 +6,7 @@ import com.langfuse.client.core.LangfuseClientApiException; import java.lang.Object; +import okhttp3.Response; public final class UnauthorizedError extends LangfuseClientApiException { /** @@ -18,6 +19,11 @@ public UnauthorizedError(Object body) { this.body = body; } + public UnauthorizedError(Object body, Response rawResponse) { + super("UnauthorizedError", 401, body, rawResponse); + this.body = body; + } + /** * @return the body */ diff --git a/src/main/java/com/langfuse/client/resources/commons/types/BaseScore.java b/src/main/java/com/langfuse/client/resources/commons/types/BaseScore.java index 388559e..6f131c4 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/BaseScore.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/BaseScore.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -51,13 +54,13 @@ public final class BaseScore implements IBaseScore { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Map additionalProperties; @@ -65,8 +68,8 @@ private BaseScore(String id, Optional traceId, Optional sessionI Optional observationId, Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + Map additionalProperties) { this.id = id; this.traceId = traceId; this.sessionId = sessionId; @@ -92,27 +95,51 @@ public String getId() { return id; } - @JsonProperty("traceId") + /** + * @return The trace ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } - @JsonProperty("sessionId") + /** + * @return The session ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } - @JsonProperty("datasetRunId") + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } return datasetRunId; } @@ -146,39 +173,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -187,10 +235,82 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -243,57 +363,107 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { BaseScore build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The trace ID associated with the score

+ */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

The session ID associated with the score

+ */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The dataset run ID associated with the score

+ */ _FinalStage datasetRunId(Optional datasetRunId); _FinalStage datasetRunId(String datasetRunId); + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private String id; private String name; @@ -306,14 +476,14 @@ public static final class Builder implements IdStage, NameStage, SourceStage, Ti private OffsetDateTime updatedAt; - private Optional environment = Optional.empty(); + private Object metadata; + + private String environment; private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -390,28 +560,50 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

*

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -425,6 +617,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -435,6 +630,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -445,6 +658,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -455,28 +671,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -487,12 +712,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -503,12 +753,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage datasetRunId(String datasetRunId) { this.datasetRunId = Optional.ofNullable(datasetRunId); return this; } + /** + *

The dataset run ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "datasetRunId", @@ -519,12 +794,37 @@ public _FinalStage datasetRunId(Optional datasetRunId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -535,12 +835,37 @@ public _FinalStage observationId(Optional observationId) { return this; } + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sessionId(String sessionId) { this.sessionId = Optional.ofNullable(sessionId); return this; } + /** + *

The session ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -551,12 +876,37 @@ public _FinalStage sessionId(Optional sessionId) { return this; } + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage traceId(String traceId) { this.traceId = Optional.ofNullable(traceId); return this; } + /** + *

The trace ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "traceId", @@ -571,5 +921,17 @@ public _FinalStage traceId(Optional traceId) { public BaseScore build() { return new BaseScore(id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/BaseScoreV1.java b/src/main/java/com/langfuse/client/resources/commons/types/BaseScoreV1.java index b16ace2..84d6f0a 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/BaseScoreV1.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/BaseScoreV1.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -47,21 +50,21 @@ public final class BaseScoreV1 implements IBaseScoreV1 { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Map additionalProperties; private BaseScoreV1(String id, String traceId, String name, ScoreSource source, Optional observationId, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + Map additionalProperties) { this.id = id; this.traceId = traceId; this.name = name; @@ -103,9 +106,15 @@ public ScoreSource getSource() { return source; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } @@ -127,39 +136,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -168,10 +198,55 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -228,45 +303,80 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { BaseScoreV1 build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private String id; private String traceId; @@ -281,14 +391,14 @@ public static final class Builder implements IdStage, TraceIdStage, NameStage, S private OffsetDateTime updatedAt; - private Optional environment = Optional.empty(); + private Object metadata; + + private String environment; private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -364,28 +474,50 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } + /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

*

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -399,6 +531,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -409,6 +544,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -419,6 +572,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -429,28 +585,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -461,12 +626,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -477,12 +667,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -497,5 +712,17 @@ public _FinalStage observationId(Optional observationId) { public BaseScoreV1 build() { return new BaseScoreV1(id, traceId, name, source, observationId, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/BooleanScore.java b/src/main/java/com/langfuse/client/resources/commons/types/BooleanScore.java index 3ad7bbe..3d5a9f3 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/BooleanScore.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/BooleanScore.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -55,13 +58,13 @@ public final class BooleanScore implements IBooleanScore, IBaseScore { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Map additionalProperties; @@ -69,8 +72,8 @@ private BooleanScore(double value, String stringValue, String id, Optional sessionId, Optional observationId, Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + Map additionalProperties) { this.value = value; this.stringValue = stringValue; this.id = id; @@ -116,27 +119,51 @@ public String getId() { return id; } - @JsonProperty("traceId") + /** + * @return The trace ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } - @JsonProperty("sessionId") + /** + * @return The session ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } - @JsonProperty("datasetRunId") + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } return datasetRunId; } @@ -170,39 +197,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -211,10 +259,82 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -245,12 +365,18 @@ public static ValueStage builder() { } public interface ValueStage { + /** + *

The numeric value of the score. Equals 1 for "True" and 0 for "False"

+ */ StringValueStage value(double value); Builder from(BooleanScore other); } public interface StringValueStage { + /** + *

The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

+ */ IdStage stringValue(@NotNull String stringValue); } @@ -275,57 +401,107 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { BooleanScore build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The trace ID associated with the score

+ */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

The session ID associated with the score

+ */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The dataset run ID associated with the score

+ */ _FinalStage datasetRunId(Optional datasetRunId); _FinalStage datasetRunId(String datasetRunId); + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private double value; private String stringValue; @@ -342,14 +518,14 @@ public static final class Builder implements ValueStage, StringValueStage, IdSta private OffsetDateTime updatedAt; - private Optional environment = Optional.empty(); + private Object metadata; + + private String environment; private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -392,6 +568,7 @@ public Builder from(BooleanScore other) { } /** + *

The numeric value of the score. Equals 1 for "True" and 0 for "False"

*

The numeric value of the score. Equals 1 for "True" and 0 for "False"

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -403,6 +580,7 @@ public StringValueStage value(double value) { } /** + *

The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

*

The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -450,28 +628,50 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

*

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -485,6 +685,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -495,6 +698,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -505,6 +726,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -515,28 +739,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -547,12 +780,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -563,12 +821,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage datasetRunId(String datasetRunId) { this.datasetRunId = Optional.ofNullable(datasetRunId); return this; } + /** + *

The dataset run ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "datasetRunId", @@ -579,12 +862,37 @@ public _FinalStage datasetRunId(Optional datasetRunId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -595,12 +903,37 @@ public _FinalStage observationId(Optional observationId) { return this; } + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sessionId(String sessionId) { this.sessionId = Optional.ofNullable(sessionId); return this; } + /** + *

The session ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -611,12 +944,37 @@ public _FinalStage sessionId(Optional sessionId) { return this; } + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage traceId(String traceId) { this.traceId = Optional.ofNullable(traceId); return this; } + /** + *

The trace ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "traceId", @@ -631,5 +989,17 @@ public _FinalStage traceId(Optional traceId) { public BooleanScore build() { return new BooleanScore(value, stringValue, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/BooleanScoreV1.java b/src/main/java/com/langfuse/client/resources/commons/types/BooleanScoreV1.java index 148f45f..58a9625 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/BooleanScoreV1.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/BooleanScoreV1.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -47,13 +50,13 @@ public final class BooleanScoreV1 implements IBaseScoreV1 { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final double value; @@ -64,9 +67,8 @@ public final class BooleanScoreV1 implements IBaseScoreV1 { private BooleanScoreV1(String id, String traceId, String name, ScoreSource source, Optional observationId, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, double value, String stringValue, - Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + double value, String stringValue, Map additionalProperties) { this.id = id; this.traceId = traceId; this.name = name; @@ -110,9 +112,15 @@ public ScoreSource getSource() { return source; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } @@ -134,39 +142,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -175,7 +204,7 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -195,6 +224,51 @@ public String getStringValue() { return stringValue; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -251,53 +325,94 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - ValueStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + ValueStage environment(@NotNull String environment); } public interface ValueStage { + /** + *

The numeric value of the score. Equals 1 for "True" and 0 for "False"

+ */ StringValueStage value(double value); } public interface StringValueStage { + /** + *

The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

+ */ _FinalStage stringValue(@NotNull String stringValue); } public interface _FinalStage { BooleanScoreV1 build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, ValueStage, StringValueStage, _FinalStage { + public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, ValueStage, StringValueStage, _FinalStage { private String id; private String traceId; @@ -312,18 +427,18 @@ public static final class Builder implements IdStage, TraceIdStage, NameStage, S private OffsetDateTime updatedAt; + private Object metadata; + + private String environment; + private double value; private String stringValue; - private Optional environment = Optional.empty(); - private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -401,12 +516,37 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public ValueStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public ValueStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + + /** + *

The numeric value of the score. Equals 1 for "True" and 0 for "False"

*

The numeric value of the score. Equals 1 for "True" and 0 for "False"

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -418,6 +558,7 @@ public StringValueStage value(double value) { } /** + *

The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

*

The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -429,22 +570,20 @@ public _FinalStage stringValue(@NotNull String stringValue) { } /** - *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -458,6 +597,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -468,6 +610,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -478,6 +638,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -488,28 +651,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -520,12 +692,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -536,12 +733,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -556,5 +778,17 @@ public _FinalStage observationId(Optional observationId) { public BooleanScoreV1 build() { return new BooleanScoreV1(id, traceId, name, source, observationId, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, value, stringValue, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScore.java b/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScore.java index 35083ac..acb89cc 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScore.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScore.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -55,13 +58,13 @@ public final class CategoricalScore implements ICategoricalScore, IBaseScore { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Map additionalProperties; @@ -69,8 +72,8 @@ private CategoricalScore(double value, String stringValue, String id, Optional sessionId, Optional observationId, Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + Map additionalProperties) { this.value = value; this.stringValue = stringValue; this.id = id; @@ -116,27 +119,51 @@ public String getId() { return id; } - @JsonProperty("traceId") + /** + * @return The trace ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } - @JsonProperty("sessionId") + /** + * @return The session ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } - @JsonProperty("datasetRunId") + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } return datasetRunId; } @@ -170,39 +197,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -211,10 +259,82 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -245,12 +365,18 @@ public static ValueStage builder() { } public interface ValueStage { + /** + *

Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

+ */ StringValueStage value(double value); Builder from(CategoricalScore other); } public interface StringValueStage { + /** + *

The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

+ */ IdStage stringValue(@NotNull String stringValue); } @@ -275,57 +401,107 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { CategoricalScore build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The trace ID associated with the score

+ */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

The session ID associated with the score

+ */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The dataset run ID associated with the score

+ */ _FinalStage datasetRunId(Optional datasetRunId); _FinalStage datasetRunId(String datasetRunId); + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private double value; private String stringValue; @@ -342,14 +518,14 @@ public static final class Builder implements ValueStage, StringValueStage, IdSta private OffsetDateTime updatedAt; - private Optional environment = Optional.empty(); + private Object metadata; + + private String environment; private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -392,6 +568,7 @@ public Builder from(CategoricalScore other) { } /** + *

Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

*

Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -403,6 +580,7 @@ public StringValueStage value(double value) { } /** + *

The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

*

The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -450,28 +628,50 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

*

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -485,6 +685,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -495,6 +698,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -505,6 +726,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -515,28 +739,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -547,12 +780,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -563,12 +821,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage datasetRunId(String datasetRunId) { this.datasetRunId = Optional.ofNullable(datasetRunId); return this; } + /** + *

The dataset run ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "datasetRunId", @@ -579,12 +862,37 @@ public _FinalStage datasetRunId(Optional datasetRunId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -595,12 +903,37 @@ public _FinalStage observationId(Optional observationId) { return this; } + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sessionId(String sessionId) { this.sessionId = Optional.ofNullable(sessionId); return this; } + /** + *

The session ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -611,12 +944,37 @@ public _FinalStage sessionId(Optional sessionId) { return this; } + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage traceId(String traceId) { this.traceId = Optional.ofNullable(traceId); return this; } + /** + *

The trace ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "traceId", @@ -631,5 +989,17 @@ public _FinalStage traceId(Optional traceId) { public CategoricalScore build() { return new CategoricalScore(value, stringValue, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScoreV1.java b/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScoreV1.java index fe3556f..4501905 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScoreV1.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/CategoricalScoreV1.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -47,13 +50,13 @@ public final class CategoricalScoreV1 implements IBaseScoreV1 { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final double value; @@ -64,9 +67,8 @@ public final class CategoricalScoreV1 implements IBaseScoreV1 { private CategoricalScoreV1(String id, String traceId, String name, ScoreSource source, Optional observationId, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, double value, String stringValue, - Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + double value, String stringValue, Map additionalProperties) { this.id = id; this.traceId = traceId; this.name = name; @@ -110,9 +112,15 @@ public ScoreSource getSource() { return source; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } @@ -134,39 +142,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -175,7 +204,7 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -195,6 +224,51 @@ public String getStringValue() { return stringValue; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -251,53 +325,94 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - ValueStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + ValueStage environment(@NotNull String environment); } public interface ValueStage { + /** + *

Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

+ */ StringValueStage value(double value); } public interface StringValueStage { + /** + *

The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

+ */ _FinalStage stringValue(@NotNull String stringValue); } public interface _FinalStage { CategoricalScoreV1 build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, ValueStage, StringValueStage, _FinalStage { + public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, ValueStage, StringValueStage, _FinalStage { private String id; private String traceId; @@ -312,18 +427,18 @@ public static final class Builder implements IdStage, TraceIdStage, NameStage, S private OffsetDateTime updatedAt; + private Object metadata; + + private String environment; + private double value; private String stringValue; - private Optional environment = Optional.empty(); - private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -401,12 +516,37 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public ValueStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public ValueStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + + /** + *

Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

*

Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -418,6 +558,7 @@ public StringValueStage value(double value) { } /** + *

The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

*

The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -429,22 +570,20 @@ public _FinalStage stringValue(@NotNull String stringValue) { } /** - *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -458,6 +597,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -468,6 +610,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -478,6 +638,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -488,28 +651,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -520,12 +692,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -536,12 +733,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -556,5 +778,17 @@ public _FinalStage observationId(Optional observationId) { public CategoricalScoreV1 build() { return new CategoricalScoreV1(id, traceId, name, source, observationId, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, value, stringValue, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Comment.java b/src/main/java/com/langfuse/client/resources/commons/types/Comment.java index a255091..0631577 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Comment.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Comment.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -94,8 +97,23 @@ public String getContent() { return content; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the comment author + */ + @JsonIgnore public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { return authorUserId; } @@ -161,9 +179,18 @@ public interface ContentStage { public interface _FinalStage { Comment build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The user ID of the comment author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + + _FinalStage authorUserId(Nullable authorUserId); } @JsonIgnoreProperties( @@ -254,12 +281,37 @@ public _FinalStage content(@NotNull String content) { return this; } + /** + *

The user ID of the comment author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the comment author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the comment author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -274,5 +326,17 @@ public _FinalStage authorUserId(Optional authorUserId) { public Comment build() { return new Comment(id, projectId, createdAt, updatedAt, objectType, objectId, content, authorUserId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/CommentObjectType.java b/src/main/java/com/langfuse/client/resources/commons/types/CommentObjectType.java index efe8f75..9bedf1f 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/CommentObjectType.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/CommentObjectType.java @@ -4,27 +4,105 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum CommentObjectType { - TRACE("TRACE"), +public final class CommentObjectType { + public static final CommentObjectType OBSERVATION = new CommentObjectType(Value.OBSERVATION, "OBSERVATION"); - OBSERVATION("OBSERVATION"), + public static final CommentObjectType PROMPT = new CommentObjectType(Value.PROMPT, "PROMPT"); - SESSION("SESSION"), + public static final CommentObjectType SESSION = new CommentObjectType(Value.SESSION, "SESSION"); - PROMPT("PROMPT"); + public static final CommentObjectType TRACE = new CommentObjectType(Value.TRACE, "TRACE"); - private final String value; + private final Value value; - CommentObjectType(String value) { + private final String string; + + CommentObjectType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof CommentObjectType && this.string.equals(((CommentObjectType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case OBSERVATION: + return visitor.visitObservation(); + case PROMPT: + return visitor.visitPrompt(); + case SESSION: + return visitor.visitSession(); + case TRACE: + return visitor.visitTrace(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static CommentObjectType valueOf(String value) { + switch (value) { + case "OBSERVATION": + return OBSERVATION; + case "PROMPT": + return PROMPT; + case "SESSION": + return SESSION; + case "TRACE": + return TRACE; + default: + return new CommentObjectType(Value.UNKNOWN, value); + } + } + + public enum Value { + TRACE, + + OBSERVATION, + + SESSION, + + PROMPT, + + UNKNOWN + } + + public interface Visitor { + T visitTrace(); + + T visitObservation(); + + T visitSession(); + + T visitPrompt(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ConfigCategory.java b/src/main/java/com/langfuse/client/resources/commons/types/ConfigCategory.java index f19156f..5968e79 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ConfigCategory.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ConfigCategory.java @@ -87,6 +87,10 @@ public interface LabelStage { public interface _FinalStage { ConfigCategory build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -128,5 +132,17 @@ public _FinalStage label(@NotNull String label) { public ConfigCategory build() { return new ConfigCategory(value, label, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/CorrectionScore.java b/src/main/java/com/langfuse/client/resources/commons/types/CorrectionScore.java new file mode 100644 index 0000000..3c33e2f --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/commons/types/CorrectionScore.java @@ -0,0 +1,1005 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.commons.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; +import com.langfuse.client.core.ObjectMappers; +import java.lang.Object; +import java.lang.String; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize( + builder = CorrectionScore.Builder.class +) +public final class CorrectionScore implements ICorrectionScore, IBaseScore { + private final double value; + + private final String stringValue; + + private final String id; + + private final Optional traceId; + + private final Optional sessionId; + + private final Optional observationId; + + private final Optional datasetRunId; + + private final String name; + + private final ScoreSource source; + + private final OffsetDateTime timestamp; + + private final OffsetDateTime createdAt; + + private final OffsetDateTime updatedAt; + + private final Optional authorUserId; + + private final Optional comment; + + private final Object metadata; + + private final Optional configId; + + private final Optional queueId; + + private final String environment; + + private final Map additionalProperties; + + private CorrectionScore(double value, String stringValue, String id, Optional traceId, + Optional sessionId, Optional observationId, Optional datasetRunId, + String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, + OffsetDateTime updatedAt, Optional authorUserId, Optional comment, + Object metadata, Optional configId, Optional queueId, String environment, + Map additionalProperties) { + this.value = value; + this.stringValue = stringValue; + this.id = id; + this.traceId = traceId; + this.sessionId = sessionId; + this.observationId = observationId; + this.datasetRunId = datasetRunId; + this.name = name; + this.source = source; + this.timestamp = timestamp; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.authorUserId = authorUserId; + this.comment = comment; + this.metadata = metadata; + this.configId = configId; + this.queueId = queueId; + this.environment = environment; + this.additionalProperties = additionalProperties; + } + + /** + * @return The numeric value of the score. Always 0 for correction scores. + */ + @JsonProperty("value") + @java.lang.Override + public double getValue() { + return value; + } + + /** + * @return The string representation of the correction content + */ + @JsonProperty("stringValue") + @java.lang.Override + public String getStringValue() { + return stringValue; + } + + @JsonProperty("id") + @java.lang.Override + public String getId() { + return id; + } + + /** + * @return The trace ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } + return traceId; + } + + /** + * @return The session ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } + return sessionId; + } + + /** + * @return The observation ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } + return observationId; + } + + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } + return datasetRunId; + } + + @JsonProperty("name") + @java.lang.Override + public String getName() { + return name; + } + + @JsonProperty("source") + @java.lang.Override + public ScoreSource getSource() { + return source; + } + + @JsonProperty("timestamp") + @java.lang.Override + public OffsetDateTime getTimestamp() { + return timestamp; + } + + @JsonProperty("createdAt") + @java.lang.Override + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + @JsonProperty("updatedAt") + @java.lang.Override + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + /** + * @return The user ID of the author + */ + @JsonIgnore + @java.lang.Override + public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } + return authorUserId; + } + + /** + * @return Comment on the score + */ + @JsonIgnore + @java.lang.Override + public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } + return comment; + } + + /** + * @return Metadata associated with the score + */ + @JsonProperty("metadata") + @java.lang.Override + public Object getMetadata() { + return metadata; + } + + /** + * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range + */ + @JsonIgnore + @java.lang.Override + public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } + return configId; + } + + /** + * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. + */ + @JsonIgnore + @java.lang.Override + public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } + return queueId; + } + + /** + * @return The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'. + */ + @JsonProperty("environment") + @java.lang.Override + public String getEnvironment() { + return environment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CorrectionScore && equalTo((CorrectionScore) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(CorrectionScore other) { + return value == other.value && stringValue.equals(other.stringValue) && id.equals(other.id) && traceId.equals(other.traceId) && sessionId.equals(other.sessionId) && observationId.equals(other.observationId) && datasetRunId.equals(other.datasetRunId) && name.equals(other.name) && source.equals(other.source) && timestamp.equals(other.timestamp) && createdAt.equals(other.createdAt) && updatedAt.equals(other.updatedAt) && authorUserId.equals(other.authorUserId) && comment.equals(other.comment) && metadata.equals(other.metadata) && configId.equals(other.configId) && queueId.equals(other.queueId) && environment.equals(other.environment); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value, this.stringValue, this.id, this.traceId, this.sessionId, this.observationId, this.datasetRunId, this.name, this.source, this.timestamp, this.createdAt, this.updatedAt, this.authorUserId, this.comment, this.metadata, this.configId, this.queueId, this.environment); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ValueStage builder() { + return new Builder(); + } + + public interface ValueStage { + /** + *

The numeric value of the score. Always 0 for correction scores.

+ */ + StringValueStage value(double value); + + Builder from(CorrectionScore other); + } + + public interface StringValueStage { + /** + *

The string representation of the correction content

+ */ + IdStage stringValue(@NotNull String stringValue); + } + + public interface IdStage { + NameStage id(@NotNull String id); + } + + public interface NameStage { + SourceStage name(@NotNull String name); + } + + public interface SourceStage { + TimestampStage source(@NotNull ScoreSource source); + } + + public interface TimestampStage { + CreatedAtStage timestamp(@NotNull OffsetDateTime timestamp); + } + + public interface CreatedAtStage { + UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt); + } + + public interface UpdatedAtStage { + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); + } + + public interface _FinalStage { + CorrectionScore build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The trace ID associated with the score

+ */ + _FinalStage traceId(Optional traceId); + + _FinalStage traceId(String traceId); + + _FinalStage traceId(Nullable traceId); + + /** + *

The session ID associated with the score

+ */ + _FinalStage sessionId(Optional sessionId); + + _FinalStage sessionId(String sessionId); + + _FinalStage sessionId(Nullable sessionId); + + /** + *

The observation ID associated with the score

+ */ + _FinalStage observationId(Optional observationId); + + _FinalStage observationId(String observationId); + + _FinalStage observationId(Nullable observationId); + + /** + *

The dataset run ID associated with the score

+ */ + _FinalStage datasetRunId(Optional datasetRunId); + + _FinalStage datasetRunId(String datasetRunId); + + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

The user ID of the author

+ */ + _FinalStage authorUserId(Optional authorUserId); + + _FinalStage authorUserId(String authorUserId); + + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ + _FinalStage comment(Optional comment); + + _FinalStage comment(String comment); + + _FinalStage comment(Nullable comment); + + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ + _FinalStage configId(Optional configId); + + _FinalStage configId(String configId); + + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ + _FinalStage queueId(Optional queueId); + + _FinalStage queueId(String queueId); + + _FinalStage queueId(Nullable queueId); + } + + @JsonIgnoreProperties( + ignoreUnknown = true + ) + public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { + private double value; + + private String stringValue; + + private String id; + + private String name; + + private ScoreSource source; + + private OffsetDateTime timestamp; + + private OffsetDateTime createdAt; + + private OffsetDateTime updatedAt; + + private Object metadata; + + private String environment; + + private Optional queueId = Optional.empty(); + + private Optional configId = Optional.empty(); + + private Optional comment = Optional.empty(); + + private Optional authorUserId = Optional.empty(); + + private Optional datasetRunId = Optional.empty(); + + private Optional observationId = Optional.empty(); + + private Optional sessionId = Optional.empty(); + + private Optional traceId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() { + } + + @java.lang.Override + public Builder from(CorrectionScore other) { + value(other.getValue()); + stringValue(other.getStringValue()); + id(other.getId()); + traceId(other.getTraceId()); + sessionId(other.getSessionId()); + observationId(other.getObservationId()); + datasetRunId(other.getDatasetRunId()); + name(other.getName()); + source(other.getSource()); + timestamp(other.getTimestamp()); + createdAt(other.getCreatedAt()); + updatedAt(other.getUpdatedAt()); + authorUserId(other.getAuthorUserId()); + comment(other.getComment()); + metadata(other.getMetadata()); + configId(other.getConfigId()); + queueId(other.getQueueId()); + environment(other.getEnvironment()); + return this; + } + + /** + *

The numeric value of the score. Always 0 for correction scores.

+ *

The numeric value of the score. Always 0 for correction scores.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("value") + public StringValueStage value(double value) { + this.value = value; + return this; + } + + /** + *

The string representation of the correction content

+ *

The string representation of the correction content

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("stringValue") + public IdStage stringValue(@NotNull String stringValue) { + this.stringValue = Objects.requireNonNull(stringValue, "stringValue must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("id") + public NameStage id(@NotNull String id) { + this.id = Objects.requireNonNull(id, "id must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("name") + public SourceStage name(@NotNull String name) { + this.name = Objects.requireNonNull(name, "name must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("source") + public TimestampStage source(@NotNull ScoreSource source) { + this.source = Objects.requireNonNull(source, "source must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("timestamp") + public CreatedAtStage timestamp(@NotNull OffsetDateTime timestamp) { + this.timestamp = Objects.requireNonNull(timestamp, "timestamp must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("createdAt") + public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { + this.createdAt = Objects.requireNonNull(createdAt, "createdAt must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("updatedAt") + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { + this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); + return this; + } + + /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } + return this; + } + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage queueId(String queueId) { + this.queueId = Optional.ofNullable(queueId); + return this; + } + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ + @java.lang.Override + @JsonSetter( + value = "queueId", + nulls = Nulls.SKIP + ) + public _FinalStage queueId(Optional queueId) { + this.queueId = queueId; + return this; + } + + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(String configId) { + this.configId = Optional.ofNullable(configId); + return this; + } + + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ + @java.lang.Override + @JsonSetter( + value = "configId", + nulls = Nulls.SKIP + ) + public _FinalStage configId(Optional configId) { + this.configId = configId; + return this; + } + + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } + return this; + } + + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage comment(String comment) { + this.comment = Optional.ofNullable(comment); + return this; + } + + /** + *

Comment on the score

+ */ + @java.lang.Override + @JsonSetter( + value = "comment", + nulls = Nulls.SKIP + ) + public _FinalStage comment(Optional comment) { + this.comment = comment; + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(String authorUserId) { + this.authorUserId = Optional.ofNullable(authorUserId); + return this; + } + + /** + *

The user ID of the author

+ */ + @java.lang.Override + @JsonSetter( + value = "authorUserId", + nulls = Nulls.SKIP + ) + public _FinalStage authorUserId(Optional authorUserId) { + this.authorUserId = authorUserId; + return this; + } + + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(String datasetRunId) { + this.datasetRunId = Optional.ofNullable(datasetRunId); + return this; + } + + /** + *

The dataset run ID associated with the score

+ */ + @java.lang.Override + @JsonSetter( + value = "datasetRunId", + nulls = Nulls.SKIP + ) + public _FinalStage datasetRunId(Optional datasetRunId) { + this.datasetRunId = datasetRunId; + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(String observationId) { + this.observationId = Optional.ofNullable(observationId); + return this; + } + + /** + *

The observation ID associated with the score

+ */ + @java.lang.Override + @JsonSetter( + value = "observationId", + nulls = Nulls.SKIP + ) + public _FinalStage observationId(Optional observationId) { + this.observationId = observationId; + return this; + } + + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(String sessionId) { + this.sessionId = Optional.ofNullable(sessionId); + return this; + } + + /** + *

The session ID associated with the score

+ */ + @java.lang.Override + @JsonSetter( + value = "sessionId", + nulls = Nulls.SKIP + ) + public _FinalStage sessionId(Optional sessionId) { + this.sessionId = sessionId; + return this; + } + + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(String traceId) { + this.traceId = Optional.ofNullable(traceId); + return this; + } + + /** + *

The trace ID associated with the score

+ */ + @java.lang.Override + @JsonSetter( + value = "traceId", + nulls = Nulls.SKIP + ) + public _FinalStage traceId(Optional traceId) { + this.traceId = traceId; + return this; + } + + @java.lang.Override + public CorrectionScore build() { + return new CorrectionScore(value, stringValue, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/src/main/java/com/langfuse/client/resources/commons/types/CreateScoreValue.java b/src/main/java/com/langfuse/client/resources/commons/types/CreateScoreValue.java index 9cc2973..a811c79 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/CreateScoreValue.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/CreateScoreValue.java @@ -13,10 +13,11 @@ import com.langfuse.client.core.ObjectMappers; import java.io.IOException; import java.lang.Double; -import java.lang.IllegalArgumentException; import java.lang.IllegalStateException; import java.lang.Object; +import java.lang.RuntimeException; import java.lang.String; +import java.lang.SuppressWarnings; import java.util.Objects; @JsonDeserialize( @@ -37,6 +38,7 @@ public Object get() { return this.value; } + @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if(this.type == 0) { return visitor.visit((double) this.value); @@ -94,7 +96,7 @@ public CreateScoreValue deserialize(JsonParser p, DeserializationContext context } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Dataset.java b/src/main/java/com/langfuse/client/resources/commons/types/Dataset.java index 2c7f8d4..fdd9600 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Dataset.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Dataset.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -33,7 +36,7 @@ public final class Dataset { private final Optional description; - private final Optional metadata; + private final Object metadata; private final Optional inputSchema; @@ -47,7 +50,7 @@ public final class Dataset { private final Map additionalProperties; - private Dataset(String id, String name, Optional description, Optional metadata, + private Dataset(String id, String name, Optional description, Object metadata, Optional inputSchema, Optional expectedOutputSchema, String projectId, OffsetDateTime createdAt, OffsetDateTime updatedAt, Map additionalProperties) { @@ -73,29 +76,44 @@ public String getName() { return name; } - @JsonProperty("description") + /** + * @return Description of the dataset + */ + @JsonIgnore public Optional getDescription() { + if (description == null) { + return Optional.empty(); + } return description; } + /** + * @return Metadata associated with the dataset + */ @JsonProperty("metadata") - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return JSON Schema for validating dataset item inputs */ - @JsonProperty("inputSchema") + @JsonIgnore public Optional getInputSchema() { + if (inputSchema == null) { + return Optional.empty(); + } return inputSchema; } /** * @return JSON Schema for validating dataset item expected outputs */ - @JsonProperty("expectedOutputSchema") + @JsonIgnore public Optional getExpectedOutputSchema() { + if (expectedOutputSchema == null) { + return Optional.empty(); + } return expectedOutputSchema; } @@ -114,6 +132,33 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("description") + private Optional _getDescription() { + return description; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("inputSchema") + private Optional _getInputSchema() { + return inputSchema; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("expectedOutputSchema") + private Optional _getExpectedOutputSchema() { + return expectedOutputSchema; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -150,7 +195,14 @@ public interface IdStage { } public interface NameStage { - ProjectIdStage name(@NotNull String name); + MetadataStage name(@NotNull String name); + } + + public interface MetadataStage { + /** + *

Metadata associated with the dataset

+ */ + ProjectIdStage metadata(Object metadata); } public interface ProjectIdStage { @@ -168,31 +220,48 @@ public interface UpdatedAtStage { public interface _FinalStage { Dataset build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Description of the dataset

+ */ _FinalStage description(Optional description); _FinalStage description(String description); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage description(Nullable description); + /** + *

JSON Schema for validating dataset item inputs

+ */ _FinalStage inputSchema(Optional inputSchema); _FinalStage inputSchema(Object inputSchema); + _FinalStage inputSchema(Nullable inputSchema); + + /** + *

JSON Schema for validating dataset item expected outputs

+ */ _FinalStage expectedOutputSchema(Optional expectedOutputSchema); _FinalStage expectedOutputSchema(Object expectedOutputSchema); + + _FinalStage expectedOutputSchema(Nullable expectedOutputSchema); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, NameStage, ProjectIdStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements IdStage, NameStage, MetadataStage, ProjectIdStage, CreatedAtStage, UpdatedAtStage, _FinalStage { private String id; private String name; + private Object metadata; + private String projectId; private OffsetDateTime createdAt; @@ -203,8 +272,6 @@ public static final class Builder implements IdStage, NameStage, ProjectIdStage, private Optional inputSchema = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional description = Optional.empty(); @JsonAnySetter @@ -236,11 +303,23 @@ public NameStage id(@NotNull String id) { @java.lang.Override @JsonSetter("name") - public ProjectIdStage name(@NotNull String name) { + public MetadataStage name(@NotNull String name) { this.name = Objects.requireNonNull(name, "name must not be null"); return this; } + /** + *

Metadata associated with the dataset

+ *

Metadata associated with the dataset

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public ProjectIdStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + @java.lang.Override @JsonSetter("projectId") public CreatedAtStage projectId(@NotNull String projectId) { @@ -262,6 +341,24 @@ public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { return this; } + /** + *

JSON Schema for validating dataset item expected outputs

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage expectedOutputSchema(Nullable expectedOutputSchema) { + if (expectedOutputSchema.isNull()) { + this.expectedOutputSchema = null; + } + else if (expectedOutputSchema.isEmpty()) { + this.expectedOutputSchema = Optional.empty(); + } + else { + this.expectedOutputSchema = Optional.of(expectedOutputSchema.get()); + } + return this; + } + /** *

JSON Schema for validating dataset item expected outputs

* @return Reference to {@code this} so that method calls can be chained together. @@ -272,6 +369,9 @@ public _FinalStage expectedOutputSchema(Object expectedOutputSchema) { return this; } + /** + *

JSON Schema for validating dataset item expected outputs

+ */ @java.lang.Override @JsonSetter( value = "expectedOutputSchema", @@ -282,6 +382,24 @@ public _FinalStage expectedOutputSchema(Optional expectedOutputSchema) { return this; } + /** + *

JSON Schema for validating dataset item inputs

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage inputSchema(Nullable inputSchema) { + if (inputSchema.isNull()) { + this.inputSchema = null; + } + else if (inputSchema.isEmpty()) { + this.inputSchema = Optional.empty(); + } + else { + this.inputSchema = Optional.of(inputSchema.get()); + } + return this; + } + /** *

JSON Schema for validating dataset item inputs

* @return Reference to {@code this} so that method calls can be chained together. @@ -292,6 +410,9 @@ public _FinalStage inputSchema(Object inputSchema) { return this; } + /** + *

JSON Schema for validating dataset item inputs

+ */ @java.lang.Override @JsonSetter( value = "inputSchema", @@ -302,28 +423,37 @@ public _FinalStage inputSchema(Optional inputSchema) { return this; } + /** + *

Description of the dataset

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage description(Nullable description) { + if (description.isNull()) { + this.description = null; + } + else if (description.isEmpty()) { + this.description = Optional.empty(); + } + else { + this.description = Optional.of(description.get()); + } return this; } + /** + *

Description of the dataset

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage description(String description) { this.description = Optional.ofNullable(description); return this; } + /** + *

Description of the dataset

+ */ @java.lang.Override @JsonSetter( value = "description", @@ -338,5 +468,17 @@ public _FinalStage description(Optional description) { public Dataset build() { return new Dataset(id, name, description, metadata, inputSchema, expectedOutputSchema, projectId, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/DatasetItem.java b/src/main/java/com/langfuse/client/resources/commons/types/DatasetItem.java index 0837bc3..8e34dfb 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/DatasetItem.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/DatasetItem.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -31,11 +34,11 @@ public final class DatasetItem { private final DatasetStatus status; - private final Optional input; + private final Object input; - private final Optional expectedOutput; + private final Object expectedOutput; - private final Optional metadata; + private final Object metadata; private final Optional sourceTraceId; @@ -51,10 +54,9 @@ public final class DatasetItem { private final Map additionalProperties; - private DatasetItem(String id, DatasetStatus status, Optional input, - Optional expectedOutput, Optional metadata, Optional sourceTraceId, - Optional sourceObservationId, String datasetId, String datasetName, - OffsetDateTime createdAt, OffsetDateTime updatedAt, + private DatasetItem(String id, DatasetStatus status, Object input, Object expectedOutput, + Object metadata, Optional sourceTraceId, Optional sourceObservationId, + String datasetId, String datasetName, OffsetDateTime createdAt, OffsetDateTime updatedAt, Map additionalProperties) { this.id = id; this.status = status; @@ -80,28 +82,49 @@ public DatasetStatus getStatus() { return status; } + /** + * @return Input data for the dataset item + */ @JsonProperty("input") - public Optional getInput() { + public Object getInput() { return input; } + /** + * @return Expected output for the dataset item + */ @JsonProperty("expectedOutput") - public Optional getExpectedOutput() { + public Object getExpectedOutput() { return expectedOutput; } + /** + * @return Metadata associated with the dataset item + */ @JsonProperty("metadata") - public Optional getMetadata() { + public Object getMetadata() { return metadata; } - @JsonProperty("sourceTraceId") + /** + * @return The trace ID that sourced this dataset item + */ + @JsonIgnore public Optional getSourceTraceId() { + if (sourceTraceId == null) { + return Optional.empty(); + } return sourceTraceId; } - @JsonProperty("sourceObservationId") + /** + * @return The observation ID that sourced this dataset item + */ + @JsonIgnore public Optional getSourceObservationId() { + if (sourceObservationId == null) { + return Optional.empty(); + } return sourceObservationId; } @@ -125,6 +148,24 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sourceTraceId") + private Optional _getSourceTraceId() { + return sourceTraceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sourceObservationId") + private Optional _getSourceObservationId() { + return sourceObservationId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -161,7 +202,28 @@ public interface IdStage { } public interface StatusStage { - DatasetIdStage status(@NotNull DatasetStatus status); + InputStage status(@NotNull DatasetStatus status); + } + + public interface InputStage { + /** + *

Input data for the dataset item

+ */ + ExpectedOutputStage input(Object input); + } + + public interface ExpectedOutputStage { + /** + *

Expected output for the dataset item

+ */ + MetadataStage expectedOutput(Object expectedOutput); + } + + public interface MetadataStage { + /** + *

Metadata associated with the dataset item

+ */ + DatasetIdStage metadata(Object metadata); } public interface DatasetIdStage { @@ -183,35 +245,43 @@ public interface UpdatedAtStage { public interface _FinalStage { DatasetItem build(); - _FinalStage input(Optional input); - - _FinalStage input(Object input); - - _FinalStage expectedOutput(Optional expectedOutput); + _FinalStage additionalProperty(String key, Object value); - _FinalStage expectedOutput(Object expectedOutput); - - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage additionalProperties(Map additionalProperties); + /** + *

The trace ID that sourced this dataset item

+ */ _FinalStage sourceTraceId(Optional sourceTraceId); _FinalStage sourceTraceId(String sourceTraceId); + _FinalStage sourceTraceId(Nullable sourceTraceId); + + /** + *

The observation ID that sourced this dataset item

+ */ _FinalStage sourceObservationId(Optional sourceObservationId); _FinalStage sourceObservationId(String sourceObservationId); + + _FinalStage sourceObservationId(Nullable sourceObservationId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, StatusStage, DatasetIdStage, DatasetNameStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements IdStage, StatusStage, InputStage, ExpectedOutputStage, MetadataStage, DatasetIdStage, DatasetNameStage, CreatedAtStage, UpdatedAtStage, _FinalStage { private String id; private DatasetStatus status; + private Object input; + + private Object expectedOutput; + + private Object metadata; + private String datasetId; private String datasetName; @@ -224,12 +294,6 @@ public static final class Builder implements IdStage, StatusStage, DatasetIdStag private Optional sourceTraceId = Optional.empty(); - private Optional metadata = Optional.empty(); - - private Optional expectedOutput = Optional.empty(); - - private Optional input = Optional.empty(); - @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -261,11 +325,47 @@ public StatusStage id(@NotNull String id) { @java.lang.Override @JsonSetter("status") - public DatasetIdStage status(@NotNull DatasetStatus status) { + public InputStage status(@NotNull DatasetStatus status) { this.status = Objects.requireNonNull(status, "status must not be null"); return this; } + /** + *

Input data for the dataset item

+ *

Input data for the dataset item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("input") + public ExpectedOutputStage input(Object input) { + this.input = input; + return this; + } + + /** + *

Expected output for the dataset item

+ *

Expected output for the dataset item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("expectedOutput") + public MetadataStage expectedOutput(Object expectedOutput) { + this.expectedOutput = expectedOutput; + return this; + } + + /** + *

Metadata associated with the dataset item

+ *

Metadata associated with the dataset item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public DatasetIdStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + @java.lang.Override @JsonSetter("datasetId") public DatasetNameStage datasetId(@NotNull String datasetId) { @@ -294,12 +394,37 @@ public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { return this; } + /** + *

The observation ID that sourced this dataset item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sourceObservationId(Nullable sourceObservationId) { + if (sourceObservationId.isNull()) { + this.sourceObservationId = null; + } + else if (sourceObservationId.isEmpty()) { + this.sourceObservationId = Optional.empty(); + } + else { + this.sourceObservationId = Optional.of(sourceObservationId.get()); + } + return this; + } + + /** + *

The observation ID that sourced this dataset item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sourceObservationId(String sourceObservationId) { this.sourceObservationId = Optional.ofNullable(sourceObservationId); return this; } + /** + *

The observation ID that sourced this dataset item

+ */ @java.lang.Override @JsonSetter( value = "sourceObservationId", @@ -310,12 +435,37 @@ public _FinalStage sourceObservationId(Optional sourceObservationId) { return this; } + /** + *

The trace ID that sourced this dataset item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sourceTraceId(Nullable sourceTraceId) { + if (sourceTraceId.isNull()) { + this.sourceTraceId = null; + } + else if (sourceTraceId.isEmpty()) { + this.sourceTraceId = Optional.empty(); + } + else { + this.sourceTraceId = Optional.of(sourceTraceId.get()); + } + return this; + } + + /** + *

The trace ID that sourced this dataset item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sourceTraceId(String sourceTraceId) { this.sourceTraceId = Optional.ofNullable(sourceTraceId); return this; } + /** + *

The trace ID that sourced this dataset item

+ */ @java.lang.Override @JsonSetter( value = "sourceTraceId", @@ -327,56 +477,20 @@ public _FinalStage sourceTraceId(Optional sourceTraceId) { } @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; - return this; - } - - @java.lang.Override - public _FinalStage expectedOutput(Object expectedOutput) { - this.expectedOutput = Optional.ofNullable(expectedOutput); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "expectedOutput", - nulls = Nulls.SKIP - ) - public _FinalStage expectedOutput(Optional expectedOutput) { - this.expectedOutput = expectedOutput; - return this; + public DatasetItem build() { + return new DatasetItem(id, status, input, expectedOutput, metadata, sourceTraceId, sourceObservationId, datasetId, datasetName, createdAt, updatedAt, additionalProperties); } @java.lang.Override - public _FinalStage input(Object input) { - this.input = Optional.ofNullable(input); + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); return this; } @java.lang.Override - @JsonSetter( - value = "input", - nulls = Nulls.SKIP - ) - public _FinalStage input(Optional input) { - this.input = input; + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); return this; } - - @java.lang.Override - public DatasetItem build() { - return new DatasetItem(id, status, input, expectedOutput, metadata, sourceTraceId, sourceObservationId, datasetId, datasetName, createdAt, updatedAt, additionalProperties); - } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/DatasetRun.java b/src/main/java/com/langfuse/client/resources/commons/types/DatasetRun.java index 3754d35..d63cee7 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/DatasetRun.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/DatasetRun.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -33,7 +36,7 @@ public final class DatasetRun implements IDatasetRun { private final Optional description; - private final Optional metadata; + private final Object metadata; private final String datasetId; @@ -45,9 +48,9 @@ public final class DatasetRun implements IDatasetRun { private final Map additionalProperties; - private DatasetRun(String id, String name, Optional description, - Optional metadata, String datasetId, String datasetName, OffsetDateTime createdAt, - OffsetDateTime updatedAt, Map additionalProperties) { + private DatasetRun(String id, String name, Optional description, Object metadata, + String datasetId, String datasetName, OffsetDateTime createdAt, OffsetDateTime updatedAt, + Map additionalProperties) { this.id = id; this.name = name; this.description = description; @@ -80,9 +83,12 @@ public String getName() { /** * @return Description of the run */ - @JsonProperty("description") + @JsonIgnore @java.lang.Override public Optional getDescription() { + if (description == null) { + return Optional.empty(); + } return description; } @@ -91,7 +97,7 @@ public Optional getDescription() { */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } @@ -131,6 +137,15 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("description") + private Optional _getDescription() { + return description; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -161,51 +176,83 @@ public static IdStage builder() { } public interface IdStage { + /** + *

Unique identifier of the dataset run

+ */ NameStage id(@NotNull String id); Builder from(DatasetRun other); } public interface NameStage { - DatasetIdStage name(@NotNull String name); + /** + *

Name of the dataset run

+ */ + MetadataStage name(@NotNull String name); + } + + public interface MetadataStage { + /** + *

Metadata of the dataset run

+ */ + DatasetIdStage metadata(Object metadata); } public interface DatasetIdStage { + /** + *

Id of the associated dataset

+ */ DatasetNameStage datasetId(@NotNull String datasetId); } public interface DatasetNameStage { + /** + *

Name of the associated dataset

+ */ CreatedAtStage datasetName(@NotNull String datasetName); } public interface CreatedAtStage { + /** + *

The date and time when the dataset run was created

+ */ UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt); } public interface UpdatedAtStage { + /** + *

The date and time when the dataset run was last updated

+ */ _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); } public interface _FinalStage { DatasetRun build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Description of the run

+ */ _FinalStage description(Optional description); _FinalStage description(String description); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage description(Nullable description); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, NameStage, DatasetIdStage, DatasetNameStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements IdStage, NameStage, MetadataStage, DatasetIdStage, DatasetNameStage, CreatedAtStage, UpdatedAtStage, _FinalStage { private String id; private String name; + private Object metadata; + private String datasetId; private String datasetName; @@ -214,8 +261,6 @@ public static final class Builder implements IdStage, NameStage, DatasetIdStage, private OffsetDateTime updatedAt; - private Optional metadata = Optional.empty(); - private Optional description = Optional.empty(); @JsonAnySetter @@ -238,6 +283,7 @@ public Builder from(DatasetRun other) { } /** + *

Unique identifier of the dataset run

*

Unique identifier of the dataset run

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -249,17 +295,31 @@ public NameStage id(@NotNull String id) { } /** + *

Name of the dataset run

*

Name of the dataset run

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("name") - public DatasetIdStage name(@NotNull String name) { + public MetadataStage name(@NotNull String name) { this.name = Objects.requireNonNull(name, "name must not be null"); return this; } /** + *

Metadata of the dataset run

+ *

Metadata of the dataset run

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public DatasetIdStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

Id of the associated dataset

*

Id of the associated dataset

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -271,6 +331,7 @@ public DatasetNameStage datasetId(@NotNull String datasetId) { } /** + *

Name of the associated dataset

*

Name of the associated dataset

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -282,6 +343,7 @@ public CreatedAtStage datasetName(@NotNull String datasetName) { } /** + *

The date and time when the dataset run was created

*

The date and time when the dataset run was created

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -293,6 +355,7 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { } /** + *

The date and time when the dataset run was last updated

*

The date and time when the dataset run was last updated

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -304,22 +367,20 @@ public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { } /** - *

Metadata of the dataset run

+ *

Description of the run

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage description(Nullable description) { + if (description.isNull()) { + this.description = null; + } + else if (description.isEmpty()) { + this.description = Optional.empty(); + } + else { + this.description = Optional.of(description.get()); + } return this; } @@ -333,6 +394,9 @@ public _FinalStage description(String description) { return this; } + /** + *

Description of the run

+ */ @java.lang.Override @JsonSetter( value = "description", @@ -347,5 +411,17 @@ public _FinalStage description(Optional description) { public DatasetRun build() { return new DatasetRun(id, name, description, metadata, datasetId, datasetName, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunItem.java b/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunItem.java index 5f9f06b..cfe9ed7 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunItem.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunItem.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -85,8 +88,14 @@ public String getTraceId() { return traceId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with this run item + */ + @JsonIgnore public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } @@ -100,6 +109,15 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -162,9 +180,18 @@ public interface UpdatedAtStage { public interface _FinalStage { DatasetRunItem build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The observation ID associated with this run item

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + + _FinalStage observationId(Nullable observationId); } @JsonIgnoreProperties( @@ -255,12 +282,37 @@ public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { return this; } + /** + *

The observation ID associated with this run item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with this run item

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with this run item

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -275,5 +327,17 @@ public _FinalStage observationId(Optional observationId) { public DatasetRunItem build() { return new DatasetRunItem(id, datasetRunId, datasetRunName, datasetItemId, traceId, observationId, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunWithItems.java b/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunWithItems.java index 4d51a87..fea2d83 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunWithItems.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/DatasetRunWithItems.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -35,7 +38,7 @@ public final class DatasetRunWithItems implements IDatasetRun { private final Optional description; - private final Optional metadata; + private final Object metadata; private final String datasetId; @@ -49,10 +52,9 @@ public final class DatasetRunWithItems implements IDatasetRun { private final Map additionalProperties; - private DatasetRunWithItems(String id, String name, Optional description, - Optional metadata, String datasetId, String datasetName, OffsetDateTime createdAt, - OffsetDateTime updatedAt, List datasetRunItems, - Map additionalProperties) { + private DatasetRunWithItems(String id, String name, Optional description, Object metadata, + String datasetId, String datasetName, OffsetDateTime createdAt, OffsetDateTime updatedAt, + List datasetRunItems, Map additionalProperties) { this.id = id; this.name = name; this.description = description; @@ -86,9 +88,12 @@ public String getName() { /** * @return Description of the run */ - @JsonProperty("description") + @JsonIgnore @java.lang.Override public Optional getDescription() { + if (description == null) { + return Optional.empty(); + } return description; } @@ -97,7 +102,7 @@ public Optional getDescription() { */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } @@ -142,6 +147,15 @@ public List getDatasetRunItems() { return datasetRunItems; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("description") + private Optional _getDescription() { + return description; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -172,41 +186,71 @@ public static IdStage builder() { } public interface IdStage { + /** + *

Unique identifier of the dataset run

+ */ NameStage id(@NotNull String id); Builder from(DatasetRunWithItems other); } public interface NameStage { - DatasetIdStage name(@NotNull String name); + /** + *

Name of the dataset run

+ */ + MetadataStage name(@NotNull String name); + } + + public interface MetadataStage { + /** + *

Metadata of the dataset run

+ */ + DatasetIdStage metadata(Object metadata); } public interface DatasetIdStage { + /** + *

Id of the associated dataset

+ */ DatasetNameStage datasetId(@NotNull String datasetId); } public interface DatasetNameStage { + /** + *

Name of the associated dataset

+ */ CreatedAtStage datasetName(@NotNull String datasetName); } public interface CreatedAtStage { + /** + *

The date and time when the dataset run was created

+ */ UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt); } public interface UpdatedAtStage { + /** + *

The date and time when the dataset run was last updated

+ */ _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); } public interface _FinalStage { DatasetRunWithItems build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Description of the run

+ */ _FinalStage description(Optional description); _FinalStage description(String description); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage description(Nullable description); _FinalStage datasetRunItems(List datasetRunItems); @@ -218,11 +262,13 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, NameStage, DatasetIdStage, DatasetNameStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements IdStage, NameStage, MetadataStage, DatasetIdStage, DatasetNameStage, CreatedAtStage, UpdatedAtStage, _FinalStage { private String id; private String name; + private Object metadata; + private String datasetId; private String datasetName; @@ -233,8 +279,6 @@ public static final class Builder implements IdStage, NameStage, DatasetIdStage, private List datasetRunItems = new ArrayList<>(); - private Optional metadata = Optional.empty(); - private Optional description = Optional.empty(); @JsonAnySetter @@ -258,6 +302,7 @@ public Builder from(DatasetRunWithItems other) { } /** + *

Unique identifier of the dataset run

*

Unique identifier of the dataset run

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -269,17 +314,31 @@ public NameStage id(@NotNull String id) { } /** + *

Name of the dataset run

*

Name of the dataset run

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("name") - public DatasetIdStage name(@NotNull String name) { + public MetadataStage name(@NotNull String name) { this.name = Objects.requireNonNull(name, "name must not be null"); return this; } /** + *

Metadata of the dataset run

+ *

Metadata of the dataset run

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public DatasetIdStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

Id of the associated dataset

*

Id of the associated dataset

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -291,6 +350,7 @@ public DatasetNameStage datasetId(@NotNull String datasetId) { } /** + *

Name of the associated dataset

*

Name of the associated dataset

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -302,6 +362,7 @@ public CreatedAtStage datasetName(@NotNull String datasetName) { } /** + *

The date and time when the dataset run was created

*

The date and time when the dataset run was created

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -313,6 +374,7 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { } /** + *

The date and time when the dataset run was last updated

*

The date and time when the dataset run was last updated

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -325,7 +387,9 @@ public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { @java.lang.Override public _FinalStage addAllDatasetRunItems(List datasetRunItems) { - this.datasetRunItems.addAll(datasetRunItems); + if (datasetRunItems != null) { + this.datasetRunItems.addAll(datasetRunItems); + } return this; } @@ -342,27 +406,27 @@ public _FinalStage addDatasetRunItems(DatasetRunItem datasetRunItems) { ) public _FinalStage datasetRunItems(List datasetRunItems) { this.datasetRunItems.clear(); - this.datasetRunItems.addAll(datasetRunItems); + if (datasetRunItems != null) { + this.datasetRunItems.addAll(datasetRunItems); + } return this; } /** - *

Metadata of the dataset run

+ *

Description of the run

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage description(Nullable description) { + if (description.isNull()) { + this.description = null; + } + else if (description.isEmpty()) { + this.description = Optional.empty(); + } + else { + this.description = Optional.of(description.get()); + } return this; } @@ -376,6 +440,9 @@ public _FinalStage description(String description) { return this; } + /** + *

Description of the run

+ */ @java.lang.Override @JsonSetter( value = "description", @@ -390,5 +457,17 @@ public _FinalStage description(Optional description) { public DatasetRunWithItems build() { return new DatasetRunWithItems(id, name, description, metadata, datasetId, datasetName, createdAt, updatedAt, datasetRunItems, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/DatasetStatus.java b/src/main/java/com/langfuse/client/resources/commons/types/DatasetStatus.java index 13f3cd6..cf7df19 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/DatasetStatus.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/DatasetStatus.java @@ -4,23 +4,85 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum DatasetStatus { - ACTIVE("ACTIVE"), +public final class DatasetStatus { + public static final DatasetStatus ARCHIVED = new DatasetStatus(Value.ARCHIVED, "ARCHIVED"); - ARCHIVED("ARCHIVED"); + public static final DatasetStatus ACTIVE = new DatasetStatus(Value.ACTIVE, "ACTIVE"); - private final String value; + private final Value value; - DatasetStatus(String value) { + private final String string; + + DatasetStatus(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DatasetStatus && this.string.equals(((DatasetStatus) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ARCHIVED: + return visitor.visitArchived(); + case ACTIVE: + return visitor.visitActive(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static DatasetStatus valueOf(String value) { + switch (value) { + case "ARCHIVED": + return ARCHIVED; + case "ACTIVE": + return ACTIVE; + default: + return new DatasetStatus(Value.UNKNOWN, value); + } + } + + public enum Value { + ACTIVE, + + ARCHIVED, + + UNKNOWN + } + + public interface Visitor { + T visitActive(); + + T visitArchived(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/IBaseScore.java b/src/main/java/com/langfuse/client/resources/commons/types/IBaseScore.java index 4970bef..f8e6742 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/IBaseScore.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/IBaseScore.java @@ -34,11 +34,11 @@ public interface IBaseScore { Optional getComment(); - Optional getMetadata(); + Object getMetadata(); Optional getConfigId(); Optional getQueueId(); - Optional getEnvironment(); + String getEnvironment(); } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/IBaseScoreV1.java b/src/main/java/com/langfuse/client/resources/commons/types/IBaseScoreV1.java index 365dfdd..e539adc 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/IBaseScoreV1.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/IBaseScoreV1.java @@ -30,11 +30,11 @@ public interface IBaseScoreV1 { Optional getComment(); - Optional getMetadata(); + Object getMetadata(); Optional getConfigId(); Optional getQueueId(); - Optional getEnvironment(); + String getEnvironment(); } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ICorrectionScore.java b/src/main/java/com/langfuse/client/resources/commons/types/ICorrectionScore.java new file mode 100644 index 0000000..bfa3b94 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/commons/types/ICorrectionScore.java @@ -0,0 +1,13 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.commons.types; + +import java.lang.String; + +public interface ICorrectionScore extends IBaseScore { + double getValue(); + + String getStringValue(); +} diff --git a/src/main/java/com/langfuse/client/resources/commons/types/IDatasetRun.java b/src/main/java/com/langfuse/client/resources/commons/types/IDatasetRun.java index 0ca902d..035351d 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/IDatasetRun.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/IDatasetRun.java @@ -16,7 +16,7 @@ public interface IDatasetRun { Optional getDescription(); - Optional getMetadata(); + Object getMetadata(); String getDatasetId(); diff --git a/src/main/java/com/langfuse/client/resources/commons/types/IObservation.java b/src/main/java/com/langfuse/client/resources/commons/types/IObservation.java index 12645f1..e7d9c4c 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/IObservation.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/IObservation.java @@ -29,17 +29,17 @@ public interface IObservation { Optional getModel(); - Optional> getModelParameters(); + Object getModelParameters(); - Optional getInput(); + Object getInput(); Optional getVersion(); - Optional getMetadata(); + Object getMetadata(); - Optional getOutput(); + Object getOutput(); - Optional getUsage(); + Usage getUsage(); ObservationLevel getLevel(); @@ -49,9 +49,9 @@ public interface IObservation { Optional getPromptId(); - Optional> getUsageDetails(); + Map getUsageDetails(); - Optional> getCostDetails(); + Map getCostDetails(); - Optional getEnvironment(); + String getEnvironment(); } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ISession.java b/src/main/java/com/langfuse/client/resources/commons/types/ISession.java index 59530af..6f1a7ff 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ISession.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ISession.java @@ -6,7 +6,6 @@ import java.lang.String; import java.time.OffsetDateTime; -import java.util.Optional; public interface ISession { String getId(); @@ -15,5 +14,5 @@ public interface ISession { String getProjectId(); - Optional getEnvironment(); + String getEnvironment(); } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ITrace.java b/src/main/java/com/langfuse/client/resources/commons/types/ITrace.java index 82133e8..9419390 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ITrace.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ITrace.java @@ -4,7 +4,6 @@ package com.langfuse.client.resources.commons.types; -import java.lang.Boolean; import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; @@ -32,9 +31,9 @@ public interface ITrace { Optional getMetadata(); - Optional> getTags(); + List getTags(); - Optional getPublic(); + boolean getPublic(); - Optional getEnvironment(); + String getEnvironment(); } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/MapValue.java b/src/main/java/com/langfuse/client/resources/commons/types/MapValue.java index e38ba5f..fcf4072 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/MapValue.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/MapValue.java @@ -14,11 +14,13 @@ import com.langfuse.client.core.ObjectMappers; import java.io.IOException; import java.lang.Boolean; -import java.lang.IllegalArgumentException; +import java.lang.Float; import java.lang.IllegalStateException; import java.lang.Integer; import java.lang.Object; +import java.lang.RuntimeException; import java.lang.String; +import java.lang.SuppressWarnings; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -41,14 +43,17 @@ public Object get() { return this.value; } + @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if(this.type == 0) { return visitor.visitOptionalString((Optional) this.value); } else if(this.type == 1) { return visitor.visitOptionalInteger((Optional) this.value); } else if(this.type == 2) { - return visitor.visitOptionalBoolean((Optional) this.value); + return visitor.visitOptionalFloat((Optional) this.value); } else if(this.type == 3) { + return visitor.visitOptionalBoolean((Optional) this.value); + } else if(this.type == 4) { return visitor.visitOptionalListOfString((Optional>) this.value); } throw new IllegalStateException("Failed to visit value. This should never happen."); @@ -82,19 +87,25 @@ public static MapValue ofOptionalInteger(Optional value) { return new MapValue(value, 1); } - public static MapValue ofOptionalBoolean(Optional value) { + public static MapValue ofOptionalFloat(Optional value) { return new MapValue(value, 2); } - public static MapValue ofOptionalListOfString(Optional> value) { + public static MapValue ofOptionalBoolean(Optional value) { return new MapValue(value, 3); } + public static MapValue ofOptionalListOfString(Optional> value) { + return new MapValue(value, 4); + } + public interface Visitor { T visitOptionalString(Optional value); T visitOptionalInteger(Optional value); + T visitOptionalFloat(Optional value); + T visitOptionalBoolean(Optional value); T visitOptionalListOfString(Optional> value); @@ -110,19 +121,23 @@ public MapValue deserialize(JsonParser p, DeserializationContext context) throws Object value = p.readValueAs(Object.class); try { return ofOptionalString(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } try { return ofOptionalInteger(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { + } + try { + return ofOptionalFloat(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); + } catch(RuntimeException e) { } try { return ofOptionalBoolean(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } try { return ofOptionalListOfString(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>>() {})); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Model.java b/src/main/java/com/langfuse/client/resources/commons/types/Model.java index 4062d73..613e896 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Model.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Model.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Double; import java.lang.Object; @@ -49,7 +52,7 @@ public final class Model { private final Optional tokenizerId; - private final Optional tokenizerConfig; + private final Object tokenizerConfig; private final boolean isLangfuseManaged; @@ -64,7 +67,7 @@ public final class Model { private Model(String id, String modelName, String matchPattern, Optional startDate, Optional unit, Optional inputPrice, Optional outputPrice, Optional totalPrice, - Optional tokenizerId, Optional tokenizerConfig, boolean isLangfuseManaged, + Optional tokenizerId, Object tokenizerConfig, boolean isLangfuseManaged, OffsetDateTime createdAt, Map prices, List pricingTiers, Map additionalProperties) { this.id = id; @@ -108,48 +111,66 @@ public String getMatchPattern() { /** * @return Apply only to generations which are newer than this ISO date. */ - @JsonProperty("startDate") + @JsonIgnore public Optional getStartDate() { + if (startDate == null) { + return Optional.empty(); + } return startDate; } /** * @return Unit used by this model. */ - @JsonProperty("unit") + @JsonIgnore public Optional getUnit() { + if (unit == null) { + return Optional.empty(); + } return unit; } /** * @return Deprecated. See 'prices' instead. Price (USD) per input unit */ - @JsonProperty("inputPrice") + @JsonIgnore public Optional getInputPrice() { + if (inputPrice == null) { + return Optional.empty(); + } return inputPrice; } /** * @return Deprecated. See 'prices' instead. Price (USD) per output unit */ - @JsonProperty("outputPrice") + @JsonIgnore public Optional getOutputPrice() { + if (outputPrice == null) { + return Optional.empty(); + } return outputPrice; } /** * @return Deprecated. See 'prices' instead. Price (USD) per total unit. Cannot be set if input or output price is set. */ - @JsonProperty("totalPrice") + @JsonIgnore public Optional getTotalPrice() { + if (totalPrice == null) { + return Optional.empty(); + } return totalPrice; } /** * @return Optional. Tokenizer to be applied to observations which match to this model. See docs for more details. */ - @JsonProperty("tokenizerId") + @JsonIgnore public Optional getTokenizerId() { + if (tokenizerId == null) { + return Optional.empty(); + } return tokenizerId; } @@ -157,7 +178,7 @@ public Optional getTokenizerId() { * @return Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details. */ @JsonProperty("tokenizerConfig") - public Optional getTokenizerConfig() { + public Object getTokenizerConfig() { return tokenizerConfig; } @@ -197,6 +218,60 @@ public List getPricingTiers() { return pricingTiers; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("startDate") + private Optional _getStartDate() { + return startDate; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("unit") + private Optional _getUnit() { + return unit; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("inputPrice") + private Optional _getInputPrice() { + return inputPrice; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("outputPrice") + private Optional _getOutputPrice() { + return outputPrice; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("totalPrice") + private Optional _getTotalPrice() { + return totalPrice; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("tokenizerId") + private Optional _getTokenizerId() { + return tokenizerId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -233,11 +308,24 @@ public interface IdStage { } public interface ModelNameStage { + /** + *

Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime

+ */ MatchPatternStage modelName(@NotNull String modelName); } public interface MatchPatternStage { - IsLangfuseManagedStage matchPattern(@NotNull String matchPattern); + /** + *

Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use (?i)^modelname$

+ */ + TokenizerConfigStage matchPattern(@NotNull String matchPattern); + } + + public interface TokenizerConfigStage { + /** + *

Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.

+ */ + IsLangfuseManagedStage tokenizerConfig(Object tokenizerConfig); } public interface IsLangfuseManagedStage { @@ -245,46 +333,92 @@ public interface IsLangfuseManagedStage { } public interface CreatedAtStage { + /** + *

Timestamp when the model was created

+ */ _FinalStage createdAt(@NotNull OffsetDateTime createdAt); } public interface _FinalStage { Model build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Apply only to generations which are newer than this ISO date.

+ */ _FinalStage startDate(Optional startDate); _FinalStage startDate(OffsetDateTime startDate); + _FinalStage startDate(Nullable startDate); + + /** + *

Unit used by this model.

+ */ _FinalStage unit(Optional unit); _FinalStage unit(ModelUsageUnit unit); + _FinalStage unit(Nullable unit); + + /** + *

Deprecated. See 'prices' instead. Price (USD) per input unit

+ */ _FinalStage inputPrice(Optional inputPrice); _FinalStage inputPrice(Double inputPrice); + _FinalStage inputPrice(Nullable inputPrice); + + /** + *

Deprecated. See 'prices' instead. Price (USD) per output unit

+ */ _FinalStage outputPrice(Optional outputPrice); _FinalStage outputPrice(Double outputPrice); + _FinalStage outputPrice(Nullable outputPrice); + + /** + *

Deprecated. See 'prices' instead. Price (USD) per total unit. Cannot be set if input or output price is set.

+ */ _FinalStage totalPrice(Optional totalPrice); _FinalStage totalPrice(Double totalPrice); + _FinalStage totalPrice(Nullable totalPrice); + + /** + *

Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.

+ */ _FinalStage tokenizerId(Optional tokenizerId); _FinalStage tokenizerId(String tokenizerId); - _FinalStage tokenizerConfig(Optional tokenizerConfig); - - _FinalStage tokenizerConfig(Object tokenizerConfig); + _FinalStage tokenizerId(Nullable tokenizerId); + /** + *

Deprecated. Use 'pricingTiers' instead for models with usage-based pricing variations.

+ *

This field shows prices by usage type from the default pricing tier. Maintained for backward compatibility. + * If the model uses tiered pricing, this field will be populated from the default tier's prices.

+ */ _FinalStage prices(Map prices); _FinalStage putAllPrices(Map prices); _FinalStage prices(String key, ModelPrice value); + /** + *

Array of pricing tiers with conditional pricing based on usage thresholds.

+ *

Pricing tiers enable accurate cost tracking for models that charge different rates based on usage patterns + * (e.g., different rates for high-volume usage, large context windows, or cached tokens).

+ *

Each model must have exactly one default tier (isDefault=true, priority=0) that serves as a fallback. + * Additional conditional tiers can be defined with specific matching criteria.

+ *

If this array is empty, the model uses legacy flat pricing from the inputPrice/outputPrice/totalPrice fields.

+ */ _FinalStage pricingTiers(List pricingTiers); _FinalStage addPricingTiers(PricingTier pricingTiers); @@ -295,13 +429,15 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, ModelNameStage, MatchPatternStage, IsLangfuseManagedStage, CreatedAtStage, _FinalStage { + public static final class Builder implements IdStage, ModelNameStage, MatchPatternStage, TokenizerConfigStage, IsLangfuseManagedStage, CreatedAtStage, _FinalStage { private String id; private String modelName; private String matchPattern; + private Object tokenizerConfig; + private boolean isLangfuseManaged; private OffsetDateTime createdAt; @@ -310,8 +446,6 @@ public static final class Builder implements IdStage, ModelNameStage, MatchPatte private Map prices = new LinkedHashMap<>(); - private Optional tokenizerConfig = Optional.empty(); - private Optional tokenizerId = Optional.empty(); private Optional totalPrice = Optional.empty(); @@ -357,6 +491,7 @@ public ModelNameStage id(@NotNull String id) { } /** + *

Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime

*

Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -368,16 +503,29 @@ public MatchPatternStage modelName(@NotNull String modelName) { } /** + *

Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use (?i)^modelname$

*

Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use (?i)^modelname$

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("matchPattern") - public IsLangfuseManagedStage matchPattern(@NotNull String matchPattern) { + public TokenizerConfigStage matchPattern(@NotNull String matchPattern) { this.matchPattern = Objects.requireNonNull(matchPattern, "matchPattern must not be null"); return this; } + /** + *

Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.

+ *

Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("tokenizerConfig") + public IsLangfuseManagedStage tokenizerConfig(Object tokenizerConfig) { + this.tokenizerConfig = tokenizerConfig; + return this; + } + @java.lang.Override @JsonSetter("isLangfuseManaged") public CreatedAtStage isLangfuseManaged(boolean isLangfuseManaged) { @@ -386,6 +534,7 @@ public CreatedAtStage isLangfuseManaged(boolean isLangfuseManaged) { } /** + *

Timestamp when the model was created

*

Timestamp when the model was created

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -407,7 +556,9 @@ public _FinalStage createdAt(@NotNull OffsetDateTime createdAt) { */ @java.lang.Override public _FinalStage addAllPricingTiers(List pricingTiers) { - this.pricingTiers.addAll(pricingTiers); + if (pricingTiers != null) { + this.pricingTiers.addAll(pricingTiers); + } return this; } @@ -426,6 +577,14 @@ public _FinalStage addPricingTiers(PricingTier pricingTiers) { return this; } + /** + *

Array of pricing tiers with conditional pricing based on usage thresholds.

+ *

Pricing tiers enable accurate cost tracking for models that charge different rates based on usage patterns + * (e.g., different rates for high-volume usage, large context windows, or cached tokens).

+ *

Each model must have exactly one default tier (isDefault=true, priority=0) that serves as a fallback. + * Additional conditional tiers can be defined with specific matching criteria.

+ *

If this array is empty, the model uses legacy flat pricing from the inputPrice/outputPrice/totalPrice fields.

+ */ @java.lang.Override @JsonSetter( value = "pricingTiers", @@ -433,7 +592,9 @@ public _FinalStage addPricingTiers(PricingTier pricingTiers) { ) public _FinalStage pricingTiers(List pricingTiers) { this.pricingTiers.clear(); - this.pricingTiers.addAll(pricingTiers); + if (pricingTiers != null) { + this.pricingTiers.addAll(pricingTiers); + } return this; } @@ -457,10 +618,17 @@ public _FinalStage prices(String key, ModelPrice value) { */ @java.lang.Override public _FinalStage putAllPrices(Map prices) { - this.prices.putAll(prices); + if (prices != null) { + this.prices.putAll(prices); + } return this; } + /** + *

Deprecated. Use 'pricingTiers' instead for models with usage-based pricing variations.

+ *

This field shows prices by usage type from the default pricing tier. Maintained for backward compatibility. + * If the model uses tiered pricing, this field will be populated from the default tier's prices.

+ */ @java.lang.Override @JsonSetter( value = "prices", @@ -468,27 +636,27 @@ public _FinalStage putAllPrices(Map prices) { ) public _FinalStage prices(Map prices) { this.prices.clear(); - this.prices.putAll(prices); + if (prices != null) { + this.prices.putAll(prices); + } return this; } /** - *

Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.

+ *

Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage tokenizerConfig(Object tokenizerConfig) { - this.tokenizerConfig = Optional.ofNullable(tokenizerConfig); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "tokenizerConfig", - nulls = Nulls.SKIP - ) - public _FinalStage tokenizerConfig(Optional tokenizerConfig) { - this.tokenizerConfig = tokenizerConfig; + public _FinalStage tokenizerId(Nullable tokenizerId) { + if (tokenizerId.isNull()) { + this.tokenizerId = null; + } + else if (tokenizerId.isEmpty()) { + this.tokenizerId = Optional.empty(); + } + else { + this.tokenizerId = Optional.of(tokenizerId.get()); + } return this; } @@ -502,6 +670,9 @@ public _FinalStage tokenizerId(String tokenizerId) { return this; } + /** + *

Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.

+ */ @java.lang.Override @JsonSetter( value = "tokenizerId", @@ -512,6 +683,24 @@ public _FinalStage tokenizerId(Optional tokenizerId) { return this; } + /** + *

Deprecated. See 'prices' instead. Price (USD) per total unit. Cannot be set if input or output price is set.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage totalPrice(Nullable totalPrice) { + if (totalPrice.isNull()) { + this.totalPrice = null; + } + else if (totalPrice.isEmpty()) { + this.totalPrice = Optional.empty(); + } + else { + this.totalPrice = Optional.of(totalPrice.get()); + } + return this; + } + /** *

Deprecated. See 'prices' instead. Price (USD) per total unit. Cannot be set if input or output price is set.

* @return Reference to {@code this} so that method calls can be chained together. @@ -522,6 +711,9 @@ public _FinalStage totalPrice(Double totalPrice) { return this; } + /** + *

Deprecated. See 'prices' instead. Price (USD) per total unit. Cannot be set if input or output price is set.

+ */ @java.lang.Override @JsonSetter( value = "totalPrice", @@ -532,6 +724,24 @@ public _FinalStage totalPrice(Optional totalPrice) { return this; } + /** + *

Deprecated. See 'prices' instead. Price (USD) per output unit

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputPrice(Nullable outputPrice) { + if (outputPrice.isNull()) { + this.outputPrice = null; + } + else if (outputPrice.isEmpty()) { + this.outputPrice = Optional.empty(); + } + else { + this.outputPrice = Optional.of(outputPrice.get()); + } + return this; + } + /** *

Deprecated. See 'prices' instead. Price (USD) per output unit

* @return Reference to {@code this} so that method calls can be chained together. @@ -542,6 +752,9 @@ public _FinalStage outputPrice(Double outputPrice) { return this; } + /** + *

Deprecated. See 'prices' instead. Price (USD) per output unit

+ */ @java.lang.Override @JsonSetter( value = "outputPrice", @@ -552,6 +765,24 @@ public _FinalStage outputPrice(Optional outputPrice) { return this; } + /** + *

Deprecated. See 'prices' instead. Price (USD) per input unit

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage inputPrice(Nullable inputPrice) { + if (inputPrice.isNull()) { + this.inputPrice = null; + } + else if (inputPrice.isEmpty()) { + this.inputPrice = Optional.empty(); + } + else { + this.inputPrice = Optional.of(inputPrice.get()); + } + return this; + } + /** *

Deprecated. See 'prices' instead. Price (USD) per input unit

* @return Reference to {@code this} so that method calls can be chained together. @@ -562,6 +793,9 @@ public _FinalStage inputPrice(Double inputPrice) { return this; } + /** + *

Deprecated. See 'prices' instead. Price (USD) per input unit

+ */ @java.lang.Override @JsonSetter( value = "inputPrice", @@ -572,6 +806,24 @@ public _FinalStage inputPrice(Optional inputPrice) { return this; } + /** + *

Unit used by this model.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage unit(Nullable unit) { + if (unit.isNull()) { + this.unit = null; + } + else if (unit.isEmpty()) { + this.unit = Optional.empty(); + } + else { + this.unit = Optional.of(unit.get()); + } + return this; + } + /** *

Unit used by this model.

* @return Reference to {@code this} so that method calls can be chained together. @@ -582,6 +834,9 @@ public _FinalStage unit(ModelUsageUnit unit) { return this; } + /** + *

Unit used by this model.

+ */ @java.lang.Override @JsonSetter( value = "unit", @@ -592,6 +847,24 @@ public _FinalStage unit(Optional unit) { return this; } + /** + *

Apply only to generations which are newer than this ISO date.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage startDate(Nullable startDate) { + if (startDate.isNull()) { + this.startDate = null; + } + else if (startDate.isEmpty()) { + this.startDate = Optional.empty(); + } + else { + this.startDate = Optional.of(startDate.get()); + } + return this; + } + /** *

Apply only to generations which are newer than this ISO date.

* @return Reference to {@code this} so that method calls can be chained together. @@ -602,6 +875,9 @@ public _FinalStage startDate(OffsetDateTime startDate) { return this; } + /** + *

Apply only to generations which are newer than this ISO date.

+ */ @java.lang.Override @JsonSetter( value = "startDate", @@ -616,5 +892,17 @@ public _FinalStage startDate(Optional startDate) { public Model build() { return new Model(id, modelName, matchPattern, startDate, unit, inputPrice, outputPrice, totalPrice, tokenizerId, tokenizerConfig, isLangfuseManaged, createdAt, prices, pricingTiers, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ModelPrice.java b/src/main/java/com/langfuse/client/resources/commons/types/ModelPrice.java index 6a737f4..bc4ad52 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ModelPrice.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ModelPrice.java @@ -74,6 +74,10 @@ public interface PriceStage { public interface _FinalStage { ModelPrice build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -105,5 +109,17 @@ public _FinalStage price(double price) { public ModelPrice build() { return new ModelPrice(price, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ModelUsageUnit.java b/src/main/java/com/langfuse/client/resources/commons/types/ModelUsageUnit.java index 37f9d1d..250fca7 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ModelUsageUnit.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ModelUsageUnit.java @@ -4,31 +4,125 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum ModelUsageUnit { - CHARACTERS("CHARACTERS"), +public final class ModelUsageUnit { + public static final ModelUsageUnit IMAGES = new ModelUsageUnit(Value.IMAGES, "IMAGES"); - TOKENS("TOKENS"), + public static final ModelUsageUnit SECONDS = new ModelUsageUnit(Value.SECONDS, "SECONDS"); - MILLISECONDS("MILLISECONDS"), + public static final ModelUsageUnit TOKENS = new ModelUsageUnit(Value.TOKENS, "TOKENS"); - SECONDS("SECONDS"), + public static final ModelUsageUnit CHARACTERS = new ModelUsageUnit(Value.CHARACTERS, "CHARACTERS"); - IMAGES("IMAGES"), + public static final ModelUsageUnit MILLISECONDS = new ModelUsageUnit(Value.MILLISECONDS, "MILLISECONDS"); - REQUESTS("REQUESTS"); + public static final ModelUsageUnit REQUESTS = new ModelUsageUnit(Value.REQUESTS, "REQUESTS"); - private final String value; + private final Value value; - ModelUsageUnit(String value) { + private final String string; + + ModelUsageUnit(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ModelUsageUnit && this.string.equals(((ModelUsageUnit) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case IMAGES: + return visitor.visitImages(); + case SECONDS: + return visitor.visitSeconds(); + case TOKENS: + return visitor.visitTokens(); + case CHARACTERS: + return visitor.visitCharacters(); + case MILLISECONDS: + return visitor.visitMilliseconds(); + case REQUESTS: + return visitor.visitRequests(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static ModelUsageUnit valueOf(String value) { + switch (value) { + case "IMAGES": + return IMAGES; + case "SECONDS": + return SECONDS; + case "TOKENS": + return TOKENS; + case "CHARACTERS": + return CHARACTERS; + case "MILLISECONDS": + return MILLISECONDS; + case "REQUESTS": + return REQUESTS; + default: + return new ModelUsageUnit(Value.UNKNOWN, value); + } + } + + public enum Value { + CHARACTERS, + + TOKENS, + + MILLISECONDS, + + SECONDS, + + IMAGES, + + REQUESTS, + + UNKNOWN + } + + public interface Visitor { + T visitCharacters(); + + T visitTokens(); + + T visitMilliseconds(); + + T visitSeconds(); + + T visitImages(); + + T visitRequests(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/NumericScore.java b/src/main/java/com/langfuse/client/resources/commons/types/NumericScore.java index c78912f..cdcc442 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/NumericScore.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/NumericScore.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -53,13 +56,13 @@ public final class NumericScore implements INumericScore, IBaseScore { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Map additionalProperties; @@ -67,8 +70,8 @@ private NumericScore(double value, String id, Optional traceId, Optional sessionId, Optional observationId, Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + Map additionalProperties) { this.value = value; this.id = id; this.traceId = traceId; @@ -104,27 +107,51 @@ public String getId() { return id; } - @JsonProperty("traceId") + /** + * @return The trace ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } - @JsonProperty("sessionId") + /** + * @return The session ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } - @JsonProperty("datasetRunId") + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } return datasetRunId; } @@ -158,39 +185,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -199,10 +247,82 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -233,6 +353,9 @@ public static ValueStage builder() { } public interface ValueStage { + /** + *

The numeric value of the score

+ */ IdStage value(double value); Builder from(NumericScore other); @@ -259,57 +382,107 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { NumericScore build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The trace ID associated with the score

+ */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

The session ID associated with the score

+ */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The dataset run ID associated with the score

+ */ _FinalStage datasetRunId(Optional datasetRunId); _FinalStage datasetRunId(String datasetRunId); + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements ValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements ValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private double value; private String id; @@ -324,14 +497,14 @@ public static final class Builder implements ValueStage, IdStage, NameStage, Sou private OffsetDateTime updatedAt; - private Optional environment = Optional.empty(); + private Object metadata; + + private String environment; private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -373,6 +546,7 @@ public Builder from(NumericScore other) { } /** + *

The numeric value of the score

*

The numeric value of the score

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -420,28 +594,50 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } /** + *

Metadata associated with the score

+ *

Metadata associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

*

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -455,6 +651,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -465,6 +664,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -475,6 +692,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -485,28 +705,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -517,12 +746,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -533,12 +787,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

The dataset run ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage datasetRunId(String datasetRunId) { this.datasetRunId = Optional.ofNullable(datasetRunId); return this; } + /** + *

The dataset run ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "datasetRunId", @@ -549,12 +828,37 @@ public _FinalStage datasetRunId(Optional datasetRunId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -565,12 +869,37 @@ public _FinalStage observationId(Optional observationId) { return this; } + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

The session ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sessionId(String sessionId) { this.sessionId = Optional.ofNullable(sessionId); return this; } + /** + *

The session ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -581,12 +910,37 @@ public _FinalStage sessionId(Optional sessionId) { return this; } + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

The trace ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage traceId(String traceId) { this.traceId = Optional.ofNullable(traceId); return this; } + /** + *

The trace ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "traceId", @@ -601,5 +955,17 @@ public _FinalStage traceId(Optional traceId) { public NumericScore build() { return new NumericScore(value, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/NumericScoreV1.java b/src/main/java/com/langfuse/client/resources/commons/types/NumericScoreV1.java index 16418b8..1ad7e83 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/NumericScoreV1.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/NumericScoreV1.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -47,13 +50,13 @@ public final class NumericScoreV1 implements IBaseScoreV1 { private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final double value; @@ -62,8 +65,8 @@ public final class NumericScoreV1 implements IBaseScoreV1 { private NumericScoreV1(String id, String traceId, String name, ScoreSource source, Optional observationId, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, double value, Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + double value, Map additionalProperties) { this.id = id; this.traceId = traceId; this.name = name; @@ -106,9 +109,15 @@ public ScoreSource getSource() { return source; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } @@ -130,39 +139,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -171,7 +201,7 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -183,6 +213,51 @@ public double getValue() { return value; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -239,49 +314,87 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - ValueStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

Metadata associated with the score

+ */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + ValueStage environment(@NotNull String environment); } public interface ValueStage { + /** + *

The numeric value of the score

+ */ _FinalStage value(double value); } public interface _FinalStage { NumericScoreV1 build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The observation ID associated with the score

+ */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

The user ID of the author

+ */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

Comment on the score

+ */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, ValueStage, _FinalStage { + public static final class Builder implements IdStage, TraceIdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, ValueStage, _FinalStage { private String id; private String traceId; @@ -296,16 +409,16 @@ public static final class Builder implements IdStage, TraceIdStage, NameStage, S private OffsetDateTime updatedAt; - private double value; + private Object metadata; - private Optional environment = Optional.empty(); + private String environment; + + private double value; private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -382,39 +495,62 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public ValueStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } /** - *

The numeric value of the score

+ *

Metadata associated with the score

+ *

Metadata associated with the score

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("value") - public _FinalStage value(double value) { - this.value = value; + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; return this; } /** + *

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

*

The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public ValueStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

The numeric value of the score

+ *

The numeric value of the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + @JsonSetter("value") + public _FinalStage value(double value) { + this.value = value; + return this; + } + + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -428,6 +564,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

+ */ @java.lang.Override @JsonSetter( value = "queueId", @@ -438,6 +577,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

* @return Reference to {@code this} so that method calls can be chained together. @@ -448,6 +605,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

+ */ @java.lang.Override @JsonSetter( value = "configId", @@ -458,28 +618,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

Comment on the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

Comment on the score

+ */ @java.lang.Override @JsonSetter( value = "comment", @@ -490,12 +659,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

The user ID of the author

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

The user ID of the author

+ */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -506,12 +700,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

The observation ID associated with the score

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

The observation ID associated with the score

+ */ @java.lang.Override @JsonSetter( value = "observationId", @@ -526,5 +745,17 @@ public _FinalStage observationId(Optional observationId) { public NumericScoreV1 build() { return new NumericScoreV1(id, traceId, name, source, observationId, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, value, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Observation.java b/src/main/java/com/langfuse/client/resources/commons/types/Observation.java index 6de0546..e64bb40 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Observation.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Observation.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Double; import java.lang.Integer; @@ -19,6 +22,7 @@ import java.lang.String; import java.time.OffsetDateTime; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -45,17 +49,17 @@ public final class Observation implements IObservation { private final Optional model; - private final Optional> modelParameters; + private final Object modelParameters; - private final Optional input; + private final Object input; private final Optional version; - private final Optional metadata; + private final Object metadata; - private final Optional output; + private final Object output; - private final Optional usage; + private final Usage usage; private final ObservationLevel level; @@ -65,23 +69,21 @@ public final class Observation implements IObservation { private final Optional promptId; - private final Optional> usageDetails; + private final Map usageDetails; - private final Optional> costDetails; + private final Map costDetails; - private final Optional environment; + private final String environment; private final Map additionalProperties; private Observation(String id, Optional traceId, String type, Optional name, OffsetDateTime startTime, Optional endTime, - Optional completionStartTime, Optional model, - Optional> modelParameters, Optional input, - Optional version, Optional metadata, Optional output, - Optional usage, ObservationLevel level, Optional statusMessage, - Optional parentObservationId, Optional promptId, - Optional> usageDetails, Optional> costDetails, - Optional environment, Map additionalProperties) { + Optional completionStartTime, Optional model, Object modelParameters, + Object input, Optional version, Object metadata, Object output, Usage usage, + ObservationLevel level, Optional statusMessage, Optional parentObservationId, + Optional promptId, Map usageDetails, Map costDetails, + String environment, Map additionalProperties) { this.id = id; this.traceId = traceId; this.type = type; @@ -118,9 +120,12 @@ public String getId() { /** * @return The trace ID associated with the observation */ - @JsonProperty("traceId") + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } @@ -136,9 +141,12 @@ public String getType() { /** * @return The name of the observation */ - @JsonProperty("name") + @JsonIgnore @java.lang.Override public Optional getName() { + if (name == null) { + return Optional.empty(); + } return name; } @@ -154,27 +162,36 @@ public OffsetDateTime getStartTime() { /** * @return The end time of the observation. */ - @JsonProperty("endTime") + @JsonIgnore @java.lang.Override public Optional getEndTime() { + if (endTime == null) { + return Optional.empty(); + } return endTime; } /** * @return The completion start time of the observation */ - @JsonProperty("completionStartTime") + @JsonIgnore @java.lang.Override public Optional getCompletionStartTime() { + if (completionStartTime == null) { + return Optional.empty(); + } return completionStartTime; } /** * @return The model used for the observation */ - @JsonProperty("model") + @JsonIgnore @java.lang.Override public Optional getModel() { + if (model == null) { + return Optional.empty(); + } return model; } @@ -183,7 +200,7 @@ public Optional getModel() { */ @JsonProperty("modelParameters") @java.lang.Override - public Optional> getModelParameters() { + public Object getModelParameters() { return modelParameters; } @@ -192,16 +209,19 @@ public Optional> getModelParameters() { */ @JsonProperty("input") @java.lang.Override - public Optional getInput() { + public Object getInput() { return input; } /** * @return The version of the observation */ - @JsonProperty("version") + @JsonIgnore @java.lang.Override public Optional getVersion() { + if (version == null) { + return Optional.empty(); + } return version; } @@ -210,7 +230,7 @@ public Optional getVersion() { */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } @@ -219,7 +239,7 @@ public Optional getMetadata() { */ @JsonProperty("output") @java.lang.Override - public Optional getOutput() { + public Object getOutput() { return output; } @@ -228,7 +248,7 @@ public Optional getOutput() { */ @JsonProperty("usage") @java.lang.Override - public Optional getUsage() { + public Usage getUsage() { return usage; } @@ -244,27 +264,36 @@ public ObservationLevel getLevel() { /** * @return The status message of the observation */ - @JsonProperty("statusMessage") + @JsonIgnore @java.lang.Override public Optional getStatusMessage() { + if (statusMessage == null) { + return Optional.empty(); + } return statusMessage; } /** * @return The parent observation ID */ - @JsonProperty("parentObservationId") + @JsonIgnore @java.lang.Override public Optional getParentObservationId() { + if (parentObservationId == null) { + return Optional.empty(); + } return parentObservationId; } /** * @return The prompt ID associated with the observation */ - @JsonProperty("promptId") + @JsonIgnore @java.lang.Override public Optional getPromptId() { + if (promptId == null) { + return Optional.empty(); + } return promptId; } @@ -273,7 +302,7 @@ public Optional getPromptId() { */ @JsonProperty("usageDetails") @java.lang.Override - public Optional> getUsageDetails() { + public Map getUsageDetails() { return usageDetails; } @@ -282,7 +311,7 @@ public Optional> getUsageDetails() { */ @JsonProperty("costDetails") @java.lang.Override - public Optional> getCostDetails() { + public Map getCostDetails() { return costDetails; } @@ -291,10 +320,91 @@ public Optional> getCostDetails() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("name") + private Optional _getName() { + return name; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("endTime") + private Optional _getEndTime() { + return endTime; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("completionStartTime") + private Optional _getCompletionStartTime() { + return completionStartTime; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("model") + private Optional _getModel() { + return model; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("version") + private Optional _getVersion() { + return version; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("statusMessage") + private Optional _getStatusMessage() { + return statusMessage; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("parentObservationId") + private Optional _getParentObservationId() { + return parentObservationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("promptId") + private Optional _getPromptId() { + return promptId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -325,130 +435,219 @@ public static IdStage builder() { } public interface IdStage { + /** + *

The unique identifier of the observation

+ */ TypeStage id(@NotNull String id); Builder from(Observation other); } public interface TypeStage { + /** + *

The type of the observation

+ */ StartTimeStage type(@NotNull String type); } public interface StartTimeStage { - LevelStage startTime(@NotNull OffsetDateTime startTime); + /** + *

The start time of the observation

+ */ + ModelParametersStage startTime(@NotNull OffsetDateTime startTime); + } + + public interface ModelParametersStage { + /** + *

The parameters of the model used for the observation

+ */ + InputStage modelParameters(Object modelParameters); + } + + public interface InputStage { + /** + *

The input data of the observation

+ */ + MetadataStage input(Object input); + } + + public interface MetadataStage { + /** + *

Additional metadata of the observation

+ */ + OutputStage metadata(Object metadata); + } + + public interface OutputStage { + /** + *

The output data of the observation

+ */ + UsageStage output(Object output); + } + + public interface UsageStage { + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ */ + LevelStage usage(@NotNull Usage usage); } public interface LevelStage { - _FinalStage level(@NotNull ObservationLevel level); + /** + *

The level of the observation

+ */ + EnvironmentStage level(@NotNull ObservationLevel level); + } + + public interface EnvironmentStage { + /** + *

The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { Observation build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The trace ID associated with the observation

+ */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

The name of the observation

+ */ _FinalStage name(Optional name); _FinalStage name(String name); + _FinalStage name(Nullable name); + + /** + *

The end time of the observation.

+ */ _FinalStage endTime(Optional endTime); _FinalStage endTime(OffsetDateTime endTime); + _FinalStage endTime(Nullable endTime); + + /** + *

The completion start time of the observation

+ */ _FinalStage completionStartTime(Optional completionStartTime); _FinalStage completionStartTime(OffsetDateTime completionStartTime); + _FinalStage completionStartTime(Nullable completionStartTime); + + /** + *

The model used for the observation

+ */ _FinalStage model(Optional model); _FinalStage model(String model); - _FinalStage modelParameters(Optional> modelParameters); - - _FinalStage modelParameters(Map modelParameters); - - _FinalStage input(Optional input); - - _FinalStage input(Object input); + _FinalStage model(Nullable model); + /** + *

The version of the observation

+ */ _FinalStage version(Optional version); _FinalStage version(String version); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); - - _FinalStage output(Optional output); - - _FinalStage output(Object output); - - _FinalStage usage(Optional usage); - - _FinalStage usage(Usage usage); + _FinalStage version(Nullable version); + /** + *

The status message of the observation

+ */ _FinalStage statusMessage(Optional statusMessage); _FinalStage statusMessage(String statusMessage); + _FinalStage statusMessage(Nullable statusMessage); + + /** + *

The parent observation ID

+ */ _FinalStage parentObservationId(Optional parentObservationId); _FinalStage parentObservationId(String parentObservationId); + _FinalStage parentObservationId(Nullable parentObservationId); + + /** + *

The prompt ID associated with the observation

+ */ _FinalStage promptId(Optional promptId); _FinalStage promptId(String promptId); - _FinalStage usageDetails(Optional> usageDetails); + _FinalStage promptId(Nullable promptId); + /** + *

The usage details of the observation. Key is the name of the usage metric, value is the number of units consumed. The total key is the sum of all (non-total) usage metrics or the total value ingested.

+ */ _FinalStage usageDetails(Map usageDetails); - _FinalStage costDetails(Optional> costDetails); + _FinalStage putAllUsageDetails(Map usageDetails); + _FinalStage usageDetails(String key, Integer value); + + /** + *

The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.

+ */ _FinalStage costDetails(Map costDetails); - _FinalStage environment(Optional environment); + _FinalStage putAllCostDetails(Map costDetails); - _FinalStage environment(String environment); + _FinalStage costDetails(String key, Double value); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TypeStage, StartTimeStage, LevelStage, _FinalStage { + public static final class Builder implements IdStage, TypeStage, StartTimeStage, ModelParametersStage, InputStage, MetadataStage, OutputStage, UsageStage, LevelStage, EnvironmentStage, _FinalStage { private String id; private String type; private OffsetDateTime startTime; - private ObservationLevel level; + private Object modelParameters; - private Optional environment = Optional.empty(); + private Object input; - private Optional> costDetails = Optional.empty(); + private Object metadata; - private Optional> usageDetails = Optional.empty(); + private Object output; - private Optional promptId = Optional.empty(); + private Usage usage; - private Optional parentObservationId = Optional.empty(); + private ObservationLevel level; - private Optional statusMessage = Optional.empty(); + private String environment; - private Optional usage = Optional.empty(); + private Map costDetails = new LinkedHashMap<>(); - private Optional output = Optional.empty(); + private Map usageDetails = new LinkedHashMap<>(); - private Optional metadata = Optional.empty(); + private Optional promptId = Optional.empty(); - private Optional version = Optional.empty(); + private Optional parentObservationId = Optional.empty(); - private Optional input = Optional.empty(); + private Optional statusMessage = Optional.empty(); - private Optional> modelParameters = Optional.empty(); + private Optional version = Optional.empty(); private Optional model = Optional.empty(); @@ -493,6 +692,7 @@ public Builder from(Observation other) { } /** + *

The unique identifier of the observation

*

The unique identifier of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -504,6 +704,7 @@ public TypeStage id(@NotNull String id) { } /** + *

The type of the observation

*

The type of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -515,44 +716,108 @@ public StartTimeStage type(@NotNull String type) { } /** + *

The start time of the observation

*

The start time of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("startTime") - public LevelStage startTime(@NotNull OffsetDateTime startTime) { + public ModelParametersStage startTime(@NotNull OffsetDateTime startTime) { this.startTime = Objects.requireNonNull(startTime, "startTime must not be null"); return this; } /** + *

The parameters of the model used for the observation

+ *

The parameters of the model used for the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("modelParameters") + public InputStage modelParameters(Object modelParameters) { + this.modelParameters = modelParameters; + return this; + } + + /** + *

The input data of the observation

+ *

The input data of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("input") + public MetadataStage input(Object input) { + this.input = input; + return this; + } + + /** + *

Additional metadata of the observation

+ *

Additional metadata of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public OutputStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The output data of the observation

+ *

The output data of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("output") + public UsageStage output(Object output) { + this.output = output; + return this; + } + + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("usage") + public LevelStage usage(@NotNull Usage usage) { + this.usage = Objects.requireNonNull(usage, "usage must not be null"); + return this; + } + + /** + *

The level of the observation

*

The level of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("level") - public _FinalStage level(@NotNull ObservationLevel level) { + public EnvironmentStage level(@NotNull ObservationLevel level) { this.level = Objects.requireNonNull(level, "level must not be null"); return this; } /** + *

The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

*

The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage costDetails(String key, Double value) { + this.costDetails.put(key, value); return this; } @@ -561,18 +826,26 @@ public _FinalStage environment(Optional environment) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage costDetails(Map costDetails) { - this.costDetails = Optional.ofNullable(costDetails); + public _FinalStage putAllCostDetails(Map costDetails) { + if (costDetails != null) { + this.costDetails.putAll(costDetails); + } return this; } + /** + *

The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.

+ */ @java.lang.Override @JsonSetter( value = "costDetails", nulls = Nulls.SKIP ) - public _FinalStage costDetails(Optional> costDetails) { - this.costDetails = costDetails; + public _FinalStage costDetails(Map costDetails) { + this.costDetails.clear(); + if (costDetails != null) { + this.costDetails.putAll(costDetails); + } return this; } @@ -581,18 +854,54 @@ public _FinalStage costDetails(Optional> costDetails) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage usageDetails(Map usageDetails) { - this.usageDetails = Optional.ofNullable(usageDetails); + public _FinalStage usageDetails(String key, Integer value) { + this.usageDetails.put(key, value); + return this; + } + + /** + *

The usage details of the observation. Key is the name of the usage metric, value is the number of units consumed. The total key is the sum of all (non-total) usage metrics or the total value ingested.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage putAllUsageDetails(Map usageDetails) { + if (usageDetails != null) { + this.usageDetails.putAll(usageDetails); + } return this; } + /** + *

The usage details of the observation. Key is the name of the usage metric, value is the number of units consumed. The total key is the sum of all (non-total) usage metrics or the total value ingested.

+ */ @java.lang.Override @JsonSetter( value = "usageDetails", nulls = Nulls.SKIP ) - public _FinalStage usageDetails(Optional> usageDetails) { - this.usageDetails = usageDetails; + public _FinalStage usageDetails(Map usageDetails) { + this.usageDetails.clear(); + if (usageDetails != null) { + this.usageDetails.putAll(usageDetails); + } + return this; + } + + /** + *

The prompt ID associated with the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage promptId(Nullable promptId) { + if (promptId.isNull()) { + this.promptId = null; + } + else if (promptId.isEmpty()) { + this.promptId = Optional.empty(); + } + else { + this.promptId = Optional.of(promptId.get()); + } return this; } @@ -606,6 +915,9 @@ public _FinalStage promptId(String promptId) { return this; } + /** + *

The prompt ID associated with the observation

+ */ @java.lang.Override @JsonSetter( value = "promptId", @@ -616,6 +928,24 @@ public _FinalStage promptId(Optional promptId) { return this; } + /** + *

The parent observation ID

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage parentObservationId(Nullable parentObservationId) { + if (parentObservationId.isNull()) { + this.parentObservationId = null; + } + else if (parentObservationId.isEmpty()) { + this.parentObservationId = Optional.empty(); + } + else { + this.parentObservationId = Optional.of(parentObservationId.get()); + } + return this; + } + /** *

The parent observation ID

* @return Reference to {@code this} so that method calls can be chained together. @@ -626,6 +956,9 @@ public _FinalStage parentObservationId(String parentObservationId) { return this; } + /** + *

The parent observation ID

+ */ @java.lang.Override @JsonSetter( value = "parentObservationId", @@ -641,78 +974,57 @@ public _FinalStage parentObservationId(Optional parentObservationId) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage statusMessage(String statusMessage) { - this.statusMessage = Optional.ofNullable(statusMessage); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "statusMessage", - nulls = Nulls.SKIP - ) - public _FinalStage statusMessage(Optional statusMessage) { - this.statusMessage = statusMessage; + public _FinalStage statusMessage(Nullable statusMessage) { + if (statusMessage.isNull()) { + this.statusMessage = null; + } + else if (statusMessage.isEmpty()) { + this.statusMessage = Optional.empty(); + } + else { + this.statusMessage = Optional.of(statusMessage.get()); + } return this; } /** - *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ *

The status message of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage usage(Usage usage) { - this.usage = Optional.ofNullable(usage); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "usage", - nulls = Nulls.SKIP - ) - public _FinalStage usage(Optional usage) { - this.usage = usage; + public _FinalStage statusMessage(String statusMessage) { + this.statusMessage = Optional.ofNullable(statusMessage); return this; } /** - *

The output data of the observation

- * @return Reference to {@code this} so that method calls can be chained together. + *

The status message of the observation

*/ - @java.lang.Override - public _FinalStage output(Object output) { - this.output = Optional.ofNullable(output); - return this; - } - @java.lang.Override @JsonSetter( - value = "output", + value = "statusMessage", nulls = Nulls.SKIP ) - public _FinalStage output(Optional output) { - this.output = output; + public _FinalStage statusMessage(Optional statusMessage) { + this.statusMessage = statusMessage; return this; } /** - *

Additional metadata of the observation

+ *

The version of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage version(Nullable version) { + if (version.isNull()) { + this.version = null; + } + else if (version.isEmpty()) { + this.version = Optional.empty(); + } + else { + this.version = Optional.of(version.get()); + } return this; } @@ -726,6 +1038,9 @@ public _FinalStage version(String version) { return this; } + /** + *

The version of the observation

+ */ @java.lang.Override @JsonSetter( value = "version", @@ -737,62 +1052,61 @@ public _FinalStage version(Optional version) { } /** - *

The input data of the observation

+ *

The model used for the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage input(Object input) { - this.input = Optional.ofNullable(input); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "input", - nulls = Nulls.SKIP - ) - public _FinalStage input(Optional input) { - this.input = input; + public _FinalStage model(Nullable model) { + if (model.isNull()) { + this.model = null; + } + else if (model.isEmpty()) { + this.model = Optional.empty(); + } + else { + this.model = Optional.of(model.get()); + } return this; } /** - *

The parameters of the model used for the observation

+ *

The model used for the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage modelParameters(Map modelParameters) { - this.modelParameters = Optional.ofNullable(modelParameters); + public _FinalStage model(String model) { + this.model = Optional.ofNullable(model); return this; } + /** + *

The model used for the observation

+ */ @java.lang.Override @JsonSetter( - value = "modelParameters", + value = "model", nulls = Nulls.SKIP ) - public _FinalStage modelParameters(Optional> modelParameters) { - this.modelParameters = modelParameters; + public _FinalStage model(Optional model) { + this.model = model; return this; } /** - *

The model used for the observation

+ *

The completion start time of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage model(String model) { - this.model = Optional.ofNullable(model); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "model", - nulls = Nulls.SKIP - ) - public _FinalStage model(Optional model) { - this.model = model; + public _FinalStage completionStartTime(Nullable completionStartTime) { + if (completionStartTime.isNull()) { + this.completionStartTime = null; + } + else if (completionStartTime.isEmpty()) { + this.completionStartTime = Optional.empty(); + } + else { + this.completionStartTime = Optional.of(completionStartTime.get()); + } return this; } @@ -806,6 +1120,9 @@ public _FinalStage completionStartTime(OffsetDateTime completionStartTime) { return this; } + /** + *

The completion start time of the observation

+ */ @java.lang.Override @JsonSetter( value = "completionStartTime", @@ -816,6 +1133,24 @@ public _FinalStage completionStartTime(Optional completionStartT return this; } + /** + *

The end time of the observation.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage endTime(Nullable endTime) { + if (endTime.isNull()) { + this.endTime = null; + } + else if (endTime.isEmpty()) { + this.endTime = Optional.empty(); + } + else { + this.endTime = Optional.of(endTime.get()); + } + return this; + } + /** *

The end time of the observation.

* @return Reference to {@code this} so that method calls can be chained together. @@ -826,6 +1161,9 @@ public _FinalStage endTime(OffsetDateTime endTime) { return this; } + /** + *

The end time of the observation.

+ */ @java.lang.Override @JsonSetter( value = "endTime", @@ -836,6 +1174,24 @@ public _FinalStage endTime(Optional endTime) { return this; } + /** + *

The name of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage name(Nullable name) { + if (name.isNull()) { + this.name = null; + } + else if (name.isEmpty()) { + this.name = Optional.empty(); + } + else { + this.name = Optional.of(name.get()); + } + return this; + } + /** *

The name of the observation

* @return Reference to {@code this} so that method calls can be chained together. @@ -846,6 +1202,9 @@ public _FinalStage name(String name) { return this; } + /** + *

The name of the observation

+ */ @java.lang.Override @JsonSetter( value = "name", @@ -856,6 +1215,24 @@ public _FinalStage name(Optional name) { return this; } + /** + *

The trace ID associated with the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + /** *

The trace ID associated with the observation

* @return Reference to {@code this} so that method calls can be chained together. @@ -866,6 +1243,9 @@ public _FinalStage traceId(String traceId) { return this; } + /** + *

The trace ID associated with the observation

+ */ @java.lang.Override @JsonSetter( value = "traceId", @@ -880,5 +1260,17 @@ public _FinalStage traceId(Optional traceId) { public Observation build() { return new Observation(id, traceId, type, name, startTime, endTime, completionStartTime, model, modelParameters, input, version, metadata, output, usage, level, statusMessage, parentObservationId, promptId, usageDetails, costDetails, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ObservationLevel.java b/src/main/java/com/langfuse/client/resources/commons/types/ObservationLevel.java index baf5ebd..b7ea0e1 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ObservationLevel.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ObservationLevel.java @@ -4,27 +4,105 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum ObservationLevel { - DEBUG("DEBUG"), +public final class ObservationLevel { + public static final ObservationLevel DEBUG = new ObservationLevel(Value.DEBUG, "DEBUG"); - DEFAULT("DEFAULT"), + public static final ObservationLevel DEFAULT = new ObservationLevel(Value.DEFAULT, "DEFAULT"); - WARNING("WARNING"), + public static final ObservationLevel WARNING = new ObservationLevel(Value.WARNING, "WARNING"); - ERROR("ERROR"); + public static final ObservationLevel ERROR = new ObservationLevel(Value.ERROR, "ERROR"); - private final String value; + private final Value value; - ObservationLevel(String value) { + private final String string; + + ObservationLevel(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ObservationLevel && this.string.equals(((ObservationLevel) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case DEBUG: + return visitor.visitDebug(); + case DEFAULT: + return visitor.visitDefault(); + case WARNING: + return visitor.visitWarning(); + case ERROR: + return visitor.visitError(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static ObservationLevel valueOf(String value) { + switch (value) { + case "DEBUG": + return DEBUG; + case "DEFAULT": + return DEFAULT; + case "WARNING": + return WARNING; + case "ERROR": + return ERROR; + default: + return new ObservationLevel(Value.UNKNOWN, value); + } + } + + public enum Value { + DEBUG, + + DEFAULT, + + WARNING, + + ERROR, + + UNKNOWN + } + + public interface Visitor { + T visitDebug(); + + T visitDefault(); + + T visitWarning(); + + T visitError(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ObservationsView.java b/src/main/java/com/langfuse/client/resources/commons/types/ObservationsView.java index f4b7480..7b5a061 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ObservationsView.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ObservationsView.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Double; import java.lang.Integer; @@ -19,6 +22,7 @@ import java.lang.String; import java.time.OffsetDateTime; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -45,17 +49,17 @@ public final class ObservationsView implements IObservation { private final Optional model; - private final Optional> modelParameters; + private final Object modelParameters; - private final Optional input; + private final Object input; private final Optional version; - private final Optional metadata; + private final Object metadata; - private final Optional output; + private final Object output; - private final Optional usage; + private final Usage usage; private final ObservationLevel level; @@ -65,11 +69,11 @@ public final class ObservationsView implements IObservation { private final Optional promptId; - private final Optional> usageDetails; + private final Map usageDetails; - private final Optional> costDetails; + private final Map costDetails; - private final Optional environment; + private final String environment; private final Optional promptName; @@ -97,13 +101,11 @@ public final class ObservationsView implements IObservation { private ObservationsView(String id, Optional traceId, String type, Optional name, OffsetDateTime startTime, Optional endTime, - Optional completionStartTime, Optional model, - Optional> modelParameters, Optional input, - Optional version, Optional metadata, Optional output, - Optional usage, ObservationLevel level, Optional statusMessage, - Optional parentObservationId, Optional promptId, - Optional> usageDetails, Optional> costDetails, - Optional environment, Optional promptName, Optional promptVersion, + Optional completionStartTime, Optional model, Object modelParameters, + Object input, Optional version, Object metadata, Object output, Usage usage, + ObservationLevel level, Optional statusMessage, Optional parentObservationId, + Optional promptId, Map usageDetails, Map costDetails, + String environment, Optional promptName, Optional promptVersion, Optional modelId, Optional inputPrice, Optional outputPrice, Optional totalPrice, Optional calculatedInputCost, Optional calculatedOutputCost, Optional calculatedTotalCost, @@ -156,9 +158,12 @@ public String getId() { /** * @return The trace ID associated with the observation */ - @JsonProperty("traceId") + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } @@ -174,9 +179,12 @@ public String getType() { /** * @return The name of the observation */ - @JsonProperty("name") + @JsonIgnore @java.lang.Override public Optional getName() { + if (name == null) { + return Optional.empty(); + } return name; } @@ -192,27 +200,36 @@ public OffsetDateTime getStartTime() { /** * @return The end time of the observation. */ - @JsonProperty("endTime") + @JsonIgnore @java.lang.Override public Optional getEndTime() { + if (endTime == null) { + return Optional.empty(); + } return endTime; } /** * @return The completion start time of the observation */ - @JsonProperty("completionStartTime") + @JsonIgnore @java.lang.Override public Optional getCompletionStartTime() { + if (completionStartTime == null) { + return Optional.empty(); + } return completionStartTime; } /** * @return The model used for the observation */ - @JsonProperty("model") + @JsonIgnore @java.lang.Override public Optional getModel() { + if (model == null) { + return Optional.empty(); + } return model; } @@ -221,7 +238,7 @@ public Optional getModel() { */ @JsonProperty("modelParameters") @java.lang.Override - public Optional> getModelParameters() { + public Object getModelParameters() { return modelParameters; } @@ -230,16 +247,19 @@ public Optional> getModelParameters() { */ @JsonProperty("input") @java.lang.Override - public Optional getInput() { + public Object getInput() { return input; } /** * @return The version of the observation */ - @JsonProperty("version") + @JsonIgnore @java.lang.Override public Optional getVersion() { + if (version == null) { + return Optional.empty(); + } return version; } @@ -248,7 +268,7 @@ public Optional getVersion() { */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } @@ -257,7 +277,7 @@ public Optional getMetadata() { */ @JsonProperty("output") @java.lang.Override - public Optional getOutput() { + public Object getOutput() { return output; } @@ -266,7 +286,7 @@ public Optional getOutput() { */ @JsonProperty("usage") @java.lang.Override - public Optional getUsage() { + public Usage getUsage() { return usage; } @@ -282,27 +302,36 @@ public ObservationLevel getLevel() { /** * @return The status message of the observation */ - @JsonProperty("statusMessage") + @JsonIgnore @java.lang.Override public Optional getStatusMessage() { + if (statusMessage == null) { + return Optional.empty(); + } return statusMessage; } /** * @return The parent observation ID */ - @JsonProperty("parentObservationId") + @JsonIgnore @java.lang.Override public Optional getParentObservationId() { + if (parentObservationId == null) { + return Optional.empty(); + } return parentObservationId; } /** * @return The prompt ID associated with the observation */ - @JsonProperty("promptId") + @JsonIgnore @java.lang.Override public Optional getPromptId() { + if (promptId == null) { + return Optional.empty(); + } return promptId; } @@ -311,7 +340,7 @@ public Optional getPromptId() { */ @JsonProperty("usageDetails") @java.lang.Override - public Optional> getUsageDetails() { + public Map getUsageDetails() { return usageDetails; } @@ -320,7 +349,7 @@ public Optional> getUsageDetails() { */ @JsonProperty("costDetails") @java.lang.Override - public Optional> getCostDetails() { + public Map getCostDetails() { return costDetails; } @@ -329,95 +358,308 @@ public Optional> getCostDetails() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } /** * @return The name of the prompt associated with the observation */ - @JsonProperty("promptName") + @JsonIgnore public Optional getPromptName() { + if (promptName == null) { + return Optional.empty(); + } return promptName; } /** * @return The version of the prompt associated with the observation */ - @JsonProperty("promptVersion") + @JsonIgnore public Optional getPromptVersion() { + if (promptVersion == null) { + return Optional.empty(); + } return promptVersion; } /** * @return The unique identifier of the model */ - @JsonProperty("modelId") + @JsonIgnore public Optional getModelId() { + if (modelId == null) { + return Optional.empty(); + } return modelId; } /** * @return The price of the input in USD */ - @JsonProperty("inputPrice") + @JsonIgnore public Optional getInputPrice() { + if (inputPrice == null) { + return Optional.empty(); + } return inputPrice; } /** * @return The price of the output in USD. */ - @JsonProperty("outputPrice") + @JsonIgnore public Optional getOutputPrice() { + if (outputPrice == null) { + return Optional.empty(); + } return outputPrice; } /** * @return The total price in USD. */ - @JsonProperty("totalPrice") + @JsonIgnore public Optional getTotalPrice() { + if (totalPrice == null) { + return Optional.empty(); + } return totalPrice; } /** * @return (Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the input in USD */ - @JsonProperty("calculatedInputCost") + @JsonIgnore public Optional getCalculatedInputCost() { + if (calculatedInputCost == null) { + return Optional.empty(); + } return calculatedInputCost; } /** * @return (Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the output in USD */ - @JsonProperty("calculatedOutputCost") + @JsonIgnore public Optional getCalculatedOutputCost() { + if (calculatedOutputCost == null) { + return Optional.empty(); + } return calculatedOutputCost; } /** * @return (Deprecated. Use usageDetails and costDetails instead.) The calculated total cost in USD */ - @JsonProperty("calculatedTotalCost") + @JsonIgnore public Optional getCalculatedTotalCost() { + if (calculatedTotalCost == null) { + return Optional.empty(); + } return calculatedTotalCost; } /** * @return The latency in seconds. */ - @JsonProperty("latency") + @JsonIgnore public Optional getLatency() { + if (latency == null) { + return Optional.empty(); + } return latency; } /** * @return The time to the first token in seconds */ - @JsonProperty("timeToFirstToken") + @JsonIgnore public Optional getTimeToFirstToken() { + if (timeToFirstToken == null) { + return Optional.empty(); + } + return timeToFirstToken; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("name") + private Optional _getName() { + return name; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("endTime") + private Optional _getEndTime() { + return endTime; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("completionStartTime") + private Optional _getCompletionStartTime() { + return completionStartTime; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("model") + private Optional _getModel() { + return model; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("version") + private Optional _getVersion() { + return version; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("statusMessage") + private Optional _getStatusMessage() { + return statusMessage; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("parentObservationId") + private Optional _getParentObservationId() { + return parentObservationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("promptId") + private Optional _getPromptId() { + return promptId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("promptName") + private Optional _getPromptName() { + return promptName; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("promptVersion") + private Optional _getPromptVersion() { + return promptVersion; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("modelId") + private Optional _getModelId() { + return modelId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("inputPrice") + private Optional _getInputPrice() { + return inputPrice; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("outputPrice") + private Optional _getOutputPrice() { + return outputPrice; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("totalPrice") + private Optional _getTotalPrice() { + return totalPrice; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("calculatedInputCost") + private Optional _getCalculatedInputCost() { + return calculatedInputCost; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("calculatedOutputCost") + private Optional _getCalculatedOutputCost() { + return calculatedOutputCost; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("calculatedTotalCost") + private Optional _getCalculatedTotalCost() { + return calculatedTotalCost; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("latency") + private Optional _getLatency() { + return latency; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("timeToFirstToken") + private Optional _getTimeToFirstToken() { return timeToFirstToken; } @@ -451,151 +693,307 @@ public static IdStage builder() { } public interface IdStage { + /** + *

The unique identifier of the observation

+ */ TypeStage id(@NotNull String id); Builder from(ObservationsView other); } public interface TypeStage { + /** + *

The type of the observation

+ */ StartTimeStage type(@NotNull String type); } public interface StartTimeStage { - LevelStage startTime(@NotNull OffsetDateTime startTime); + /** + *

The start time of the observation

+ */ + ModelParametersStage startTime(@NotNull OffsetDateTime startTime); + } + + public interface ModelParametersStage { + /** + *

The parameters of the model used for the observation

+ */ + InputStage modelParameters(Object modelParameters); + } + + public interface InputStage { + /** + *

The input data of the observation

+ */ + MetadataStage input(Object input); + } + + public interface MetadataStage { + /** + *

Additional metadata of the observation

+ */ + OutputStage metadata(Object metadata); + } + + public interface OutputStage { + /** + *

The output data of the observation

+ */ + UsageStage output(Object output); + } + + public interface UsageStage { + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ */ + LevelStage usage(@NotNull Usage usage); } public interface LevelStage { - _FinalStage level(@NotNull ObservationLevel level); + /** + *

The level of the observation

+ */ + EnvironmentStage level(@NotNull ObservationLevel level); + } + + public interface EnvironmentStage { + /** + *

The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { ObservationsView build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

The trace ID associated with the observation

+ */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

The name of the observation

+ */ _FinalStage name(Optional name); _FinalStage name(String name); + _FinalStage name(Nullable name); + + /** + *

The end time of the observation.

+ */ _FinalStage endTime(Optional endTime); _FinalStage endTime(OffsetDateTime endTime); + _FinalStage endTime(Nullable endTime); + + /** + *

The completion start time of the observation

+ */ _FinalStage completionStartTime(Optional completionStartTime); _FinalStage completionStartTime(OffsetDateTime completionStartTime); + _FinalStage completionStartTime(Nullable completionStartTime); + + /** + *

The model used for the observation

+ */ _FinalStage model(Optional model); _FinalStage model(String model); - _FinalStage modelParameters(Optional> modelParameters); - - _FinalStage modelParameters(Map modelParameters); - - _FinalStage input(Optional input); - - _FinalStage input(Object input); + _FinalStage model(Nullable model); + /** + *

The version of the observation

+ */ _FinalStage version(Optional version); _FinalStage version(String version); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); - - _FinalStage output(Optional output); - - _FinalStage output(Object output); - - _FinalStage usage(Optional usage); - - _FinalStage usage(Usage usage); + _FinalStage version(Nullable version); + /** + *

The status message of the observation

+ */ _FinalStage statusMessage(Optional statusMessage); _FinalStage statusMessage(String statusMessage); + _FinalStage statusMessage(Nullable statusMessage); + + /** + *

The parent observation ID

+ */ _FinalStage parentObservationId(Optional parentObservationId); _FinalStage parentObservationId(String parentObservationId); + _FinalStage parentObservationId(Nullable parentObservationId); + + /** + *

The prompt ID associated with the observation

+ */ _FinalStage promptId(Optional promptId); _FinalStage promptId(String promptId); - _FinalStage usageDetails(Optional> usageDetails); + _FinalStage promptId(Nullable promptId); + /** + *

The usage details of the observation. Key is the name of the usage metric, value is the number of units consumed. The total key is the sum of all (non-total) usage metrics or the total value ingested.

+ */ _FinalStage usageDetails(Map usageDetails); - _FinalStage costDetails(Optional> costDetails); + _FinalStage putAllUsageDetails(Map usageDetails); + + _FinalStage usageDetails(String key, Integer value); + /** + *

The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.

+ */ _FinalStage costDetails(Map costDetails); - _FinalStage environment(Optional environment); + _FinalStage putAllCostDetails(Map costDetails); - _FinalStage environment(String environment); + _FinalStage costDetails(String key, Double value); + /** + *

The name of the prompt associated with the observation

+ */ _FinalStage promptName(Optional promptName); _FinalStage promptName(String promptName); + _FinalStage promptName(Nullable promptName); + + /** + *

The version of the prompt associated with the observation

+ */ _FinalStage promptVersion(Optional promptVersion); _FinalStage promptVersion(Integer promptVersion); + _FinalStage promptVersion(Nullable promptVersion); + + /** + *

The unique identifier of the model

+ */ _FinalStage modelId(Optional modelId); _FinalStage modelId(String modelId); + _FinalStage modelId(Nullable modelId); + + /** + *

The price of the input in USD

+ */ _FinalStage inputPrice(Optional inputPrice); _FinalStage inputPrice(Double inputPrice); + _FinalStage inputPrice(Nullable inputPrice); + + /** + *

The price of the output in USD.

+ */ _FinalStage outputPrice(Optional outputPrice); _FinalStage outputPrice(Double outputPrice); + _FinalStage outputPrice(Nullable outputPrice); + + /** + *

The total price in USD.

+ */ _FinalStage totalPrice(Optional totalPrice); _FinalStage totalPrice(Double totalPrice); + _FinalStage totalPrice(Nullable totalPrice); + + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the input in USD

+ */ _FinalStage calculatedInputCost(Optional calculatedInputCost); _FinalStage calculatedInputCost(Double calculatedInputCost); + _FinalStage calculatedInputCost(Nullable calculatedInputCost); + + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the output in USD

+ */ _FinalStage calculatedOutputCost(Optional calculatedOutputCost); _FinalStage calculatedOutputCost(Double calculatedOutputCost); + _FinalStage calculatedOutputCost(Nullable calculatedOutputCost); + + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated total cost in USD

+ */ _FinalStage calculatedTotalCost(Optional calculatedTotalCost); _FinalStage calculatedTotalCost(Double calculatedTotalCost); + _FinalStage calculatedTotalCost(Nullable calculatedTotalCost); + + /** + *

The latency in seconds.

+ */ _FinalStage latency(Optional latency); _FinalStage latency(Double latency); + _FinalStage latency(Nullable latency); + + /** + *

The time to the first token in seconds

+ */ _FinalStage timeToFirstToken(Optional timeToFirstToken); _FinalStage timeToFirstToken(Double timeToFirstToken); + + _FinalStage timeToFirstToken(Nullable timeToFirstToken); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TypeStage, StartTimeStage, LevelStage, _FinalStage { + public static final class Builder implements IdStage, TypeStage, StartTimeStage, ModelParametersStage, InputStage, MetadataStage, OutputStage, UsageStage, LevelStage, EnvironmentStage, _FinalStage { private String id; private String type; private OffsetDateTime startTime; + private Object modelParameters; + + private Object input; + + private Object metadata; + + private Object output; + + private Usage usage; + private ObservationLevel level; + private String environment; + private Optional timeToFirstToken = Optional.empty(); private Optional latency = Optional.empty(); @@ -618,11 +1016,9 @@ public static final class Builder implements IdStage, TypeStage, StartTimeStage, private Optional promptName = Optional.empty(); - private Optional environment = Optional.empty(); - - private Optional> costDetails = Optional.empty(); + private Map costDetails = new LinkedHashMap<>(); - private Optional> usageDetails = Optional.empty(); + private Map usageDetails = new LinkedHashMap<>(); private Optional promptId = Optional.empty(); @@ -630,18 +1026,8 @@ public static final class Builder implements IdStage, TypeStage, StartTimeStage, private Optional statusMessage = Optional.empty(); - private Optional usage = Optional.empty(); - - private Optional output = Optional.empty(); - - private Optional metadata = Optional.empty(); - private Optional version = Optional.empty(); - private Optional input = Optional.empty(); - - private Optional> modelParameters = Optional.empty(); - private Optional model = Optional.empty(); private Optional completionStartTime = Optional.empty(); @@ -696,6 +1082,7 @@ public Builder from(ObservationsView other) { } /** + *

The unique identifier of the observation

*

The unique identifier of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -707,6 +1094,7 @@ public TypeStage id(@NotNull String id) { } /** + *

The type of the observation

*

The type of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -718,27 +1106,119 @@ public StartTimeStage type(@NotNull String type) { } /** + *

The start time of the observation

*

The start time of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("startTime") - public LevelStage startTime(@NotNull OffsetDateTime startTime) { + public ModelParametersStage startTime(@NotNull OffsetDateTime startTime) { this.startTime = Objects.requireNonNull(startTime, "startTime must not be null"); return this; } /** + *

The parameters of the model used for the observation

+ *

The parameters of the model used for the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("modelParameters") + public InputStage modelParameters(Object modelParameters) { + this.modelParameters = modelParameters; + return this; + } + + /** + *

The input data of the observation

+ *

The input data of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("input") + public MetadataStage input(Object input) { + this.input = input; + return this; + } + + /** + *

Additional metadata of the observation

+ *

Additional metadata of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public OutputStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

The output data of the observation

+ *

The output data of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("output") + public UsageStage output(Object output) { + this.output = output; + return this; + } + + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("usage") + public LevelStage usage(@NotNull Usage usage) { + this.usage = Objects.requireNonNull(usage, "usage must not be null"); + return this; + } + + /** + *

The level of the observation

*

The level of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("level") - public _FinalStage level(@NotNull ObservationLevel level) { + public EnvironmentStage level(@NotNull ObservationLevel level) { this.level = Objects.requireNonNull(level, "level must not be null"); return this; } + /** + *

The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ *

The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + + /** + *

The time to the first token in seconds

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage timeToFirstToken(Nullable timeToFirstToken) { + if (timeToFirstToken.isNull()) { + this.timeToFirstToken = null; + } + else if (timeToFirstToken.isEmpty()) { + this.timeToFirstToken = Optional.empty(); + } + else { + this.timeToFirstToken = Optional.of(timeToFirstToken.get()); + } + return this; + } + /** *

The time to the first token in seconds

* @return Reference to {@code this} so that method calls can be chained together. @@ -749,6 +1229,9 @@ public _FinalStage timeToFirstToken(Double timeToFirstToken) { return this; } + /** + *

The time to the first token in seconds

+ */ @java.lang.Override @JsonSetter( value = "timeToFirstToken", @@ -759,6 +1242,24 @@ public _FinalStage timeToFirstToken(Optional timeToFirstToken) { return this; } + /** + *

The latency in seconds.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage latency(Nullable latency) { + if (latency.isNull()) { + this.latency = null; + } + else if (latency.isEmpty()) { + this.latency = Optional.empty(); + } + else { + this.latency = Optional.of(latency.get()); + } + return this; + } + /** *

The latency in seconds.

* @return Reference to {@code this} so that method calls can be chained together. @@ -769,6 +1270,9 @@ public _FinalStage latency(Double latency) { return this; } + /** + *

The latency in seconds.

+ */ @java.lang.Override @JsonSetter( value = "latency", @@ -779,6 +1283,24 @@ public _FinalStage latency(Optional latency) { return this; } + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated total cost in USD

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage calculatedTotalCost(Nullable calculatedTotalCost) { + if (calculatedTotalCost.isNull()) { + this.calculatedTotalCost = null; + } + else if (calculatedTotalCost.isEmpty()) { + this.calculatedTotalCost = Optional.empty(); + } + else { + this.calculatedTotalCost = Optional.of(calculatedTotalCost.get()); + } + return this; + } + /** *

(Deprecated. Use usageDetails and costDetails instead.) The calculated total cost in USD

* @return Reference to {@code this} so that method calls can be chained together. @@ -789,6 +1311,9 @@ public _FinalStage calculatedTotalCost(Double calculatedTotalCost) { return this; } + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated total cost in USD

+ */ @java.lang.Override @JsonSetter( value = "calculatedTotalCost", @@ -799,6 +1324,24 @@ public _FinalStage calculatedTotalCost(Optional calculatedTotalCost) { return this; } + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the output in USD

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage calculatedOutputCost(Nullable calculatedOutputCost) { + if (calculatedOutputCost.isNull()) { + this.calculatedOutputCost = null; + } + else if (calculatedOutputCost.isEmpty()) { + this.calculatedOutputCost = Optional.empty(); + } + else { + this.calculatedOutputCost = Optional.of(calculatedOutputCost.get()); + } + return this; + } + /** *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the output in USD

* @return Reference to {@code this} so that method calls can be chained together. @@ -809,6 +1352,9 @@ public _FinalStage calculatedOutputCost(Double calculatedOutputCost) { return this; } + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the output in USD

+ */ @java.lang.Override @JsonSetter( value = "calculatedOutputCost", @@ -819,6 +1365,24 @@ public _FinalStage calculatedOutputCost(Optional calculatedOutputCost) { return this; } + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the input in USD

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage calculatedInputCost(Nullable calculatedInputCost) { + if (calculatedInputCost.isNull()) { + this.calculatedInputCost = null; + } + else if (calculatedInputCost.isEmpty()) { + this.calculatedInputCost = Optional.empty(); + } + else { + this.calculatedInputCost = Optional.of(calculatedInputCost.get()); + } + return this; + } + /** *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the input in USD

* @return Reference to {@code this} so that method calls can be chained together. @@ -829,6 +1393,9 @@ public _FinalStage calculatedInputCost(Double calculatedInputCost) { return this; } + /** + *

(Deprecated. Use usageDetails and costDetails instead.) The calculated cost of the input in USD

+ */ @java.lang.Override @JsonSetter( value = "calculatedInputCost", @@ -839,6 +1406,24 @@ public _FinalStage calculatedInputCost(Optional calculatedInputCost) { return this; } + /** + *

The total price in USD.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage totalPrice(Nullable totalPrice) { + if (totalPrice.isNull()) { + this.totalPrice = null; + } + else if (totalPrice.isEmpty()) { + this.totalPrice = Optional.empty(); + } + else { + this.totalPrice = Optional.of(totalPrice.get()); + } + return this; + } + /** *

The total price in USD.

* @return Reference to {@code this} so that method calls can be chained together. @@ -849,6 +1434,9 @@ public _FinalStage totalPrice(Double totalPrice) { return this; } + /** + *

The total price in USD.

+ */ @java.lang.Override @JsonSetter( value = "totalPrice", @@ -859,6 +1447,24 @@ public _FinalStage totalPrice(Optional totalPrice) { return this; } + /** + *

The price of the output in USD.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputPrice(Nullable outputPrice) { + if (outputPrice.isNull()) { + this.outputPrice = null; + } + else if (outputPrice.isEmpty()) { + this.outputPrice = Optional.empty(); + } + else { + this.outputPrice = Optional.of(outputPrice.get()); + } + return this; + } + /** *

The price of the output in USD.

* @return Reference to {@code this} so that method calls can be chained together. @@ -869,6 +1475,9 @@ public _FinalStage outputPrice(Double outputPrice) { return this; } + /** + *

The price of the output in USD.

+ */ @java.lang.Override @JsonSetter( value = "outputPrice", @@ -879,6 +1488,24 @@ public _FinalStage outputPrice(Optional outputPrice) { return this; } + /** + *

The price of the input in USD

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage inputPrice(Nullable inputPrice) { + if (inputPrice.isNull()) { + this.inputPrice = null; + } + else if (inputPrice.isEmpty()) { + this.inputPrice = Optional.empty(); + } + else { + this.inputPrice = Optional.of(inputPrice.get()); + } + return this; + } + /** *

The price of the input in USD

* @return Reference to {@code this} so that method calls can be chained together. @@ -889,6 +1516,9 @@ public _FinalStage inputPrice(Double inputPrice) { return this; } + /** + *

The price of the input in USD

+ */ @java.lang.Override @JsonSetter( value = "inputPrice", @@ -899,6 +1529,24 @@ public _FinalStage inputPrice(Optional inputPrice) { return this; } + /** + *

The unique identifier of the model

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage modelId(Nullable modelId) { + if (modelId.isNull()) { + this.modelId = null; + } + else if (modelId.isEmpty()) { + this.modelId = Optional.empty(); + } + else { + this.modelId = Optional.of(modelId.get()); + } + return this; + } + /** *

The unique identifier of the model

* @return Reference to {@code this} so that method calls can be chained together. @@ -909,6 +1557,9 @@ public _FinalStage modelId(String modelId) { return this; } + /** + *

The unique identifier of the model

+ */ @java.lang.Override @JsonSetter( value = "modelId", @@ -919,6 +1570,24 @@ public _FinalStage modelId(Optional modelId) { return this; } + /** + *

The version of the prompt associated with the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage promptVersion(Nullable promptVersion) { + if (promptVersion.isNull()) { + this.promptVersion = null; + } + else if (promptVersion.isEmpty()) { + this.promptVersion = Optional.empty(); + } + else { + this.promptVersion = Optional.of(promptVersion.get()); + } + return this; + } + /** *

The version of the prompt associated with the observation

* @return Reference to {@code this} so that method calls can be chained together. @@ -929,6 +1598,9 @@ public _FinalStage promptVersion(Integer promptVersion) { return this; } + /** + *

The version of the prompt associated with the observation

+ */ @java.lang.Override @JsonSetter( value = "promptVersion", @@ -939,6 +1611,24 @@ public _FinalStage promptVersion(Optional promptVersion) { return this; } + /** + *

The name of the prompt associated with the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage promptName(Nullable promptName) { + if (promptName.isNull()) { + this.promptName = null; + } + else if (promptName.isEmpty()) { + this.promptName = Optional.empty(); + } + else { + this.promptName = Optional.of(promptName.get()); + } + return this; + } + /** *

The name of the prompt associated with the observation

* @return Reference to {@code this} so that method calls can be chained together. @@ -949,6 +1639,9 @@ public _FinalStage promptName(String promptName) { return this; } + /** + *

The name of the prompt associated with the observation

+ */ @java.lang.Override @JsonSetter( value = "promptName", @@ -960,22 +1653,12 @@ public _FinalStage promptName(Optional promptName) { } /** - *

The environment from which this observation originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

+ *

The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage costDetails(String key, Double value) { + this.costDetails.put(key, value); return this; } @@ -984,18 +1667,26 @@ public _FinalStage environment(Optional environment) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage costDetails(Map costDetails) { - this.costDetails = Optional.ofNullable(costDetails); + public _FinalStage putAllCostDetails(Map costDetails) { + if (costDetails != null) { + this.costDetails.putAll(costDetails); + } return this; } + /** + *

The cost details of the observation. Key is the name of the cost metric, value is the cost in USD. The total key is the sum of all (non-total) cost metrics or the total value ingested.

+ */ @java.lang.Override @JsonSetter( value = "costDetails", nulls = Nulls.SKIP ) - public _FinalStage costDetails(Optional> costDetails) { - this.costDetails = costDetails; + public _FinalStage costDetails(Map costDetails) { + this.costDetails.clear(); + if (costDetails != null) { + this.costDetails.putAll(costDetails); + } return this; } @@ -1004,18 +1695,54 @@ public _FinalStage costDetails(Optional> costDetails) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage usageDetails(Map usageDetails) { - this.usageDetails = Optional.ofNullable(usageDetails); + public _FinalStage usageDetails(String key, Integer value) { + this.usageDetails.put(key, value); return this; } + /** + *

The usage details of the observation. Key is the name of the usage metric, value is the number of units consumed. The total key is the sum of all (non-total) usage metrics or the total value ingested.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage putAllUsageDetails(Map usageDetails) { + if (usageDetails != null) { + this.usageDetails.putAll(usageDetails); + } + return this; + } + + /** + *

The usage details of the observation. Key is the name of the usage metric, value is the number of units consumed. The total key is the sum of all (non-total) usage metrics or the total value ingested.

+ */ @java.lang.Override @JsonSetter( value = "usageDetails", nulls = Nulls.SKIP ) - public _FinalStage usageDetails(Optional> usageDetails) { - this.usageDetails = usageDetails; + public _FinalStage usageDetails(Map usageDetails) { + this.usageDetails.clear(); + if (usageDetails != null) { + this.usageDetails.putAll(usageDetails); + } + return this; + } + + /** + *

The prompt ID associated with the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage promptId(Nullable promptId) { + if (promptId.isNull()) { + this.promptId = null; + } + else if (promptId.isEmpty()) { + this.promptId = Optional.empty(); + } + else { + this.promptId = Optional.of(promptId.get()); + } return this; } @@ -1029,6 +1756,9 @@ public _FinalStage promptId(String promptId) { return this; } + /** + *

The prompt ID associated with the observation

+ */ @java.lang.Override @JsonSetter( value = "promptId", @@ -1039,6 +1769,24 @@ public _FinalStage promptId(Optional promptId) { return this; } + /** + *

The parent observation ID

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage parentObservationId(Nullable parentObservationId) { + if (parentObservationId.isNull()) { + this.parentObservationId = null; + } + else if (parentObservationId.isEmpty()) { + this.parentObservationId = Optional.empty(); + } + else { + this.parentObservationId = Optional.of(parentObservationId.get()); + } + return this; + } + /** *

The parent observation ID

* @return Reference to {@code this} so that method calls can be chained together. @@ -1049,6 +1797,9 @@ public _FinalStage parentObservationId(String parentObservationId) { return this; } + /** + *

The parent observation ID

+ */ @java.lang.Override @JsonSetter( value = "parentObservationId", @@ -1064,78 +1815,57 @@ public _FinalStage parentObservationId(Optional parentObservationId) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage statusMessage(String statusMessage) { - this.statusMessage = Optional.ofNullable(statusMessage); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "statusMessage", - nulls = Nulls.SKIP - ) - public _FinalStage statusMessage(Optional statusMessage) { - this.statusMessage = statusMessage; + public _FinalStage statusMessage(Nullable statusMessage) { + if (statusMessage.isNull()) { + this.statusMessage = null; + } + else if (statusMessage.isEmpty()) { + this.statusMessage = Optional.empty(); + } + else { + this.statusMessage = Optional.of(statusMessage.get()); + } return this; } /** - *

(Deprecated. Use usageDetails and costDetails instead.) The usage data of the observation

+ *

The status message of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage usage(Usage usage) { - this.usage = Optional.ofNullable(usage); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "usage", - nulls = Nulls.SKIP - ) - public _FinalStage usage(Optional usage) { - this.usage = usage; + public _FinalStage statusMessage(String statusMessage) { + this.statusMessage = Optional.ofNullable(statusMessage); return this; } /** - *

The output data of the observation

- * @return Reference to {@code this} so that method calls can be chained together. + *

The status message of the observation

*/ - @java.lang.Override - public _FinalStage output(Object output) { - this.output = Optional.ofNullable(output); - return this; - } - @java.lang.Override @JsonSetter( - value = "output", + value = "statusMessage", nulls = Nulls.SKIP ) - public _FinalStage output(Optional output) { - this.output = output; + public _FinalStage statusMessage(Optional statusMessage) { + this.statusMessage = statusMessage; return this; } /** - *

Additional metadata of the observation

+ *

The version of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage version(Nullable version) { + if (version.isNull()) { + this.version = null; + } + else if (version.isEmpty()) { + this.version = Optional.empty(); + } + else { + this.version = Optional.of(version.get()); + } return this; } @@ -1149,6 +1879,9 @@ public _FinalStage version(String version) { return this; } + /** + *

The version of the observation

+ */ @java.lang.Override @JsonSetter( value = "version", @@ -1160,62 +1893,61 @@ public _FinalStage version(Optional version) { } /** - *

The input data of the observation

+ *

The model used for the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage input(Object input) { - this.input = Optional.ofNullable(input); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "input", - nulls = Nulls.SKIP - ) - public _FinalStage input(Optional input) { - this.input = input; + public _FinalStage model(Nullable model) { + if (model.isNull()) { + this.model = null; + } + else if (model.isEmpty()) { + this.model = Optional.empty(); + } + else { + this.model = Optional.of(model.get()); + } return this; } /** - *

The parameters of the model used for the observation

+ *

The model used for the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage modelParameters(Map modelParameters) { - this.modelParameters = Optional.ofNullable(modelParameters); + public _FinalStage model(String model) { + this.model = Optional.ofNullable(model); return this; } + /** + *

The model used for the observation

+ */ @java.lang.Override @JsonSetter( - value = "modelParameters", + value = "model", nulls = Nulls.SKIP ) - public _FinalStage modelParameters(Optional> modelParameters) { - this.modelParameters = modelParameters; + public _FinalStage model(Optional model) { + this.model = model; return this; } /** - *

The model used for the observation

+ *

The completion start time of the observation

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage model(String model) { - this.model = Optional.ofNullable(model); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "model", - nulls = Nulls.SKIP - ) - public _FinalStage model(Optional model) { - this.model = model; + public _FinalStage completionStartTime(Nullable completionStartTime) { + if (completionStartTime.isNull()) { + this.completionStartTime = null; + } + else if (completionStartTime.isEmpty()) { + this.completionStartTime = Optional.empty(); + } + else { + this.completionStartTime = Optional.of(completionStartTime.get()); + } return this; } @@ -1229,6 +1961,9 @@ public _FinalStage completionStartTime(OffsetDateTime completionStartTime) { return this; } + /** + *

The completion start time of the observation

+ */ @java.lang.Override @JsonSetter( value = "completionStartTime", @@ -1239,6 +1974,24 @@ public _FinalStage completionStartTime(Optional completionStartT return this; } + /** + *

The end time of the observation.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage endTime(Nullable endTime) { + if (endTime.isNull()) { + this.endTime = null; + } + else if (endTime.isEmpty()) { + this.endTime = Optional.empty(); + } + else { + this.endTime = Optional.of(endTime.get()); + } + return this; + } + /** *

The end time of the observation.

* @return Reference to {@code this} so that method calls can be chained together. @@ -1249,6 +2002,9 @@ public _FinalStage endTime(OffsetDateTime endTime) { return this; } + /** + *

The end time of the observation.

+ */ @java.lang.Override @JsonSetter( value = "endTime", @@ -1259,6 +2015,24 @@ public _FinalStage endTime(Optional endTime) { return this; } + /** + *

The name of the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage name(Nullable name) { + if (name.isNull()) { + this.name = null; + } + else if (name.isEmpty()) { + this.name = Optional.empty(); + } + else { + this.name = Optional.of(name.get()); + } + return this; + } + /** *

The name of the observation

* @return Reference to {@code this} so that method calls can be chained together. @@ -1269,6 +2043,9 @@ public _FinalStage name(String name) { return this; } + /** + *

The name of the observation

+ */ @java.lang.Override @JsonSetter( value = "name", @@ -1279,6 +2056,24 @@ public _FinalStage name(Optional name) { return this; } + /** + *

The trace ID associated with the observation

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + /** *

The trace ID associated with the observation

* @return Reference to {@code this} so that method calls can be chained together. @@ -1289,6 +2084,9 @@ public _FinalStage traceId(String traceId) { return this; } + /** + *

The trace ID associated with the observation

+ */ @java.lang.Override @JsonSetter( value = "traceId", @@ -1303,5 +2101,17 @@ public _FinalStage traceId(Optional traceId) { public ObservationsView build() { return new ObservationsView(id, traceId, type, name, startTime, endTime, completionStartTime, model, modelParameters, input, version, metadata, output, usage, level, statusMessage, parentObservationId, promptId, usageDetails, costDetails, environment, promptName, promptVersion, modelId, inputPrice, outputPrice, totalPrice, calculatedInputCost, calculatedOutputCost, calculatedTotalCost, latency, timeToFirstToken, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/PricingTier.java b/src/main/java/com/langfuse/client/resources/commons/types/PricingTier.java index 18d1a42..234af6c 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/PricingTier.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/PricingTier.java @@ -150,32 +150,71 @@ public static IdStage builder() { } public interface IdStage { + /** + *

Unique identifier for the pricing tier

+ */ NameStage id(@NotNull String id); Builder from(PricingTier other); } public interface NameStage { + /** + *

Name of the pricing tier for display and identification purposes.

+ *

Examples: "Standard", "High Volume Tier", "Large Context", "Extended Context Tier"

+ */ IsDefaultStage name(@NotNull String name); } public interface IsDefaultStage { + /** + *

Whether this is the default tier. Every model must have exactly one default tier with priority 0 and no conditions.

+ *

The default tier serves as a fallback when no conditional tiers match, ensuring cost calculation always succeeds. + * It typically represents the base pricing for standard usage patterns.

+ */ PriorityStage isDefault(boolean isDefault); } public interface PriorityStage { + /** + *

Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).

+ *

The default tier must always have priority 0. Conditional tiers should have priority 1, 2, 3, etc.

+ *

Example ordering:

+ *
    + *
  • Priority 0: Default tier (no conditions, always matches as fallback)
  • + *
  • Priority 1: High usage tier (e.g., >200K tokens)
  • + *
  • Priority 2: Medium usage tier (e.g., >100K tokens)
  • + *
+ *

This ensures more specific conditions are checked before general ones.

+ */ _FinalStage priority(int priority); } public interface _FinalStage { PricingTier build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

Array of conditions that must ALL be met for this tier to match (AND logic).

+ *

The default tier must have an empty conditions array. Conditional tiers should have one or more conditions + * that define when this tier's pricing applies.

+ *

Multiple conditions enable complex matching scenarios (e.g., "high input tokens AND low output tokens").

+ */ _FinalStage conditions(List conditions); _FinalStage addConditions(PricingTierCondition conditions); _FinalStage addAllConditions(List conditions); + /** + *

Prices (USD) by usage type for this tier.

+ *

Common usage types: "input", "output", "total", "request", "image" + * Prices are specified in USD per unit (e.g., per token, per request, per second).

+ *

Example: {"input": 0.000003, "output": 0.000015} means $3 per million input tokens and $15 per million output tokens.

+ */ _FinalStage prices(Map prices); _FinalStage putAllPrices(Map prices); @@ -217,6 +256,7 @@ public Builder from(PricingTier other) { } /** + *

Unique identifier for the pricing tier

*

Unique identifier for the pricing tier

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -228,6 +268,8 @@ public NameStage id(@NotNull String id) { } /** + *

Name of the pricing tier for display and identification purposes.

+ *

Examples: "Standard", "High Volume Tier", "Large Context", "Extended Context Tier"

*

Name of the pricing tier for display and identification purposes.

*

Examples: "Standard", "High Volume Tier", "Large Context", "Extended Context Tier"

* @return Reference to {@code this} so that method calls can be chained together. @@ -240,6 +282,9 @@ public IsDefaultStage name(@NotNull String name) { } /** + *

Whether this is the default tier. Every model must have exactly one default tier with priority 0 and no conditions.

+ *

The default tier serves as a fallback when no conditional tiers match, ensuring cost calculation always succeeds. + * It typically represents the base pricing for standard usage patterns.

*

Whether this is the default tier. Every model must have exactly one default tier with priority 0 and no conditions.

*

The default tier serves as a fallback when no conditional tiers match, ensuring cost calculation always succeeds. * It typically represents the base pricing for standard usage patterns.

@@ -253,6 +298,15 @@ public PriorityStage isDefault(boolean isDefault) { } /** + *

Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).

+ *

The default tier must always have priority 0. Conditional tiers should have priority 1, 2, 3, etc.

+ *

Example ordering:

+ *
    + *
  • Priority 0: Default tier (no conditions, always matches as fallback)
  • + *
  • Priority 1: High usage tier (e.g., >200K tokens)
  • + *
  • Priority 2: Medium usage tier (e.g., >100K tokens)
  • + *
+ *

This ensures more specific conditions are checked before general ones.

*

Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).

*

The default tier must always have priority 0. Conditional tiers should have priority 1, 2, 3, etc.

*

Example ordering:

@@ -293,10 +347,18 @@ public _FinalStage prices(String key, Double value) { */ @java.lang.Override public _FinalStage putAllPrices(Map prices) { - this.prices.putAll(prices); + if (prices != null) { + this.prices.putAll(prices); + } return this; } + /** + *

Prices (USD) by usage type for this tier.

+ *

Common usage types: "input", "output", "total", "request", "image" + * Prices are specified in USD per unit (e.g., per token, per request, per second).

+ *

Example: {"input": 0.000003, "output": 0.000015} means $3 per million input tokens and $15 per million output tokens.

+ */ @java.lang.Override @JsonSetter( value = "prices", @@ -304,7 +366,9 @@ public _FinalStage putAllPrices(Map prices) { ) public _FinalStage prices(Map prices) { this.prices.clear(); - this.prices.putAll(prices); + if (prices != null) { + this.prices.putAll(prices); + } return this; } @@ -317,7 +381,9 @@ public _FinalStage prices(Map prices) { */ @java.lang.Override public _FinalStage addAllConditions(List conditions) { - this.conditions.addAll(conditions); + if (conditions != null) { + this.conditions.addAll(conditions); + } return this; } @@ -334,6 +400,12 @@ public _FinalStage addConditions(PricingTierCondition conditions) { return this; } + /** + *

Array of conditions that must ALL be met for this tier to match (AND logic).

+ *

The default tier must have an empty conditions array. Conditional tiers should have one or more conditions + * that define when this tier's pricing applies.

+ *

Multiple conditions enable complex matching scenarios (e.g., "high input tokens AND low output tokens").

+ */ @java.lang.Override @JsonSetter( value = "conditions", @@ -341,7 +413,9 @@ public _FinalStage addConditions(PricingTierCondition conditions) { ) public _FinalStage conditions(List conditions) { this.conditions.clear(); - this.conditions.addAll(conditions); + if (conditions != null) { + this.conditions.addAll(conditions); + } return this; } @@ -349,5 +423,17 @@ public _FinalStage conditions(List conditions) { public PricingTier build() { return new PricingTier(id, name, isDefault, priority, conditions, prices, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/PricingTierCondition.java b/src/main/java/com/langfuse/client/resources/commons/types/PricingTierCondition.java index 1032e7e..0f5faab 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/PricingTierCondition.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/PricingTierCondition.java @@ -120,25 +120,56 @@ public static UsageDetailPatternStage builder() { } public interface UsageDetailPatternStage { + /** + *

Regex pattern to match against usage detail keys. All matching keys' values are summed for threshold comparison.

+ *

Examples:

+ *
    + *
  • "^input" matches "input", "input_tokens", "input_cached", etc.
  • + *
  • "^(input|prompt)" matches both "input_tokens" and "prompt_tokens"
  • + *
  • "_cache$" matches "input_cache", "output_cache", etc.
  • + *
+ *

The pattern is case-insensitive by default. If no keys match, the sum is treated as zero.

+ */ OperatorStage usageDetailPattern(@NotNull String usageDetailPattern); Builder from(PricingTierCondition other); } public interface OperatorStage { + /** + *

Comparison operator to apply between the summed value and the threshold.

+ *
    + *
  • gt: greater than (sum > threshold)
  • + *
  • gte: greater than or equal (sum >= threshold)
  • + *
  • lt: less than (sum < threshold)
  • + *
  • lte: less than or equal (sum <= threshold)
  • + *
  • eq: equal (sum == threshold)
  • + *
  • neq: not equal (sum != threshold)
  • + *
+ */ ValueStage operator(@NotNull PricingTierOperator operator); } public interface ValueStage { + /** + *

Threshold value for comparison. For token-based pricing, this is typically the token count threshold (e.g., 200000 for a 200K token threshold).

+ */ CaseSensitiveStage value(double value); } public interface CaseSensitiveStage { + /** + *

Whether the regex pattern matching is case-sensitive. Default is false (case-insensitive matching).

+ */ _FinalStage caseSensitive(boolean caseSensitive); } public interface _FinalStage { PricingTierCondition build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -169,6 +200,14 @@ public Builder from(PricingTierCondition other) { } /** + *

Regex pattern to match against usage detail keys. All matching keys' values are summed for threshold comparison.

+ *

Examples:

+ *
    + *
  • "^input" matches "input", "input_tokens", "input_cached", etc.
  • + *
  • "^(input|prompt)" matches both "input_tokens" and "prompt_tokens"
  • + *
  • "_cache$" matches "input_cache", "output_cache", etc.
  • + *
+ *

The pattern is case-insensitive by default. If no keys match, the sum is treated as zero.

*

Regex pattern to match against usage detail keys. All matching keys' values are summed for threshold comparison.

*

Examples:

*
    @@ -187,6 +226,15 @@ public OperatorStage usageDetailPattern(@NotNull String usageDetailPattern) { } /** + *

    Comparison operator to apply between the summed value and the threshold.

    + *
      + *
    • gt: greater than (sum > threshold)
    • + *
    • gte: greater than or equal (sum >= threshold)
    • + *
    • lt: less than (sum < threshold)
    • + *
    • lte: less than or equal (sum <= threshold)
    • + *
    • eq: equal (sum == threshold)
    • + *
    • neq: not equal (sum != threshold)
    • + *
    *

    Comparison operator to apply between the summed value and the threshold.

    *
      *
    • gt: greater than (sum > threshold)
    • @@ -206,6 +254,7 @@ public ValueStage operator(@NotNull PricingTierOperator operator) { } /** + *

      Threshold value for comparison. For token-based pricing, this is typically the token count threshold (e.g., 200000 for a 200K token threshold).

      *

      Threshold value for comparison. For token-based pricing, this is typically the token count threshold (e.g., 200000 for a 200K token threshold).

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -217,6 +266,7 @@ public CaseSensitiveStage value(double value) { } /** + *

      Whether the regex pattern matching is case-sensitive. Default is false (case-insensitive matching).

      *

      Whether the regex pattern matching is case-sensitive. Default is false (case-insensitive matching).

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -231,5 +281,17 @@ public _FinalStage caseSensitive(boolean caseSensitive) { public PricingTierCondition build() { return new PricingTierCondition(usageDetailPattern, operator, value, caseSensitive, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/PricingTierInput.java b/src/main/java/com/langfuse/client/resources/commons/types/PricingTierInput.java index 2f629bf..359ff70 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/PricingTierInput.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/PricingTierInput.java @@ -138,28 +138,63 @@ public static NameStage builder() { } public interface NameStage { + /** + *

      Name of the pricing tier for display and identification purposes.

      + *

      Must be unique within the model. Common patterns: "Standard", "High Volume Tier", "Extended Context"

      + */ IsDefaultStage name(@NotNull String name); Builder from(PricingTierInput other); } public interface IsDefaultStage { + /** + *

      Whether this is the default tier. Exactly one tier per model must be marked as default.

      + *

      Requirements for default tier:

      + *
        + *
      • Must have isDefault=true
      • + *
      • Must have priority=0
      • + *
      • Must have empty conditions array (conditions=[])
      • + *
      + *

      The default tier acts as a fallback when no conditional tiers match.

      + */ PriorityStage isDefault(boolean isDefault); } public interface PriorityStage { + /** + *

      Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).

      + *

      Must be unique within the model. The default tier must have priority=0. + * Conditional tiers should use priority 1, 2, 3, etc. based on their specificity.

      + */ _FinalStage priority(int priority); } public interface _FinalStage { PricingTierInput build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

      Array of conditions that must ALL be met for this tier to match (AND logic).

      + *

      The default tier must have an empty array (conditions=[]). + * Conditional tiers should define one or more conditions that specify when this tier's pricing applies.

      + *

      Each condition specifies a regex pattern, operator, and threshold value for matching against usage details.

      + */ _FinalStage conditions(List conditions); _FinalStage addConditions(PricingTierCondition conditions); _FinalStage addAllConditions(List conditions); + /** + *

      Prices (USD) by usage type for this tier. At least one price must be defined.

      + *

      Common usage types: "input", "output", "total", "request", "image" + * Prices are in USD per unit (e.g., per token).

      + *

      Example: {"input": 0.000003, "output": 0.000015} represents $3 per million input tokens and $15 per million output tokens.

      + */ _FinalStage prices(Map prices); _FinalStage putAllPrices(Map prices); @@ -198,6 +233,8 @@ public Builder from(PricingTierInput other) { } /** + *

      Name of the pricing tier for display and identification purposes.

      + *

      Must be unique within the model. Common patterns: "Standard", "High Volume Tier", "Extended Context"

      *

      Name of the pricing tier for display and identification purposes.

      *

      Must be unique within the model. Common patterns: "Standard", "High Volume Tier", "Extended Context"

      * @return Reference to {@code this} so that method calls can be chained together. @@ -210,6 +247,14 @@ public IsDefaultStage name(@NotNull String name) { } /** + *

      Whether this is the default tier. Exactly one tier per model must be marked as default.

      + *

      Requirements for default tier:

      + *
        + *
      • Must have isDefault=true
      • + *
      • Must have priority=0
      • + *
      • Must have empty conditions array (conditions=[])
      • + *
      + *

      The default tier acts as a fallback when no conditional tiers match.

      *

      Whether this is the default tier. Exactly one tier per model must be marked as default.

      *

      Requirements for default tier:

      *
        @@ -228,6 +273,9 @@ public PriorityStage isDefault(boolean isDefault) { } /** + *

        Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).

        + *

        Must be unique within the model. The default tier must have priority=0. + * Conditional tiers should use priority 1, 2, 3, etc. based on their specificity.

        *

        Priority for tier matching evaluation. Lower numbers = higher priority (evaluated first).

        *

        Must be unique within the model. The default tier must have priority=0. * Conditional tiers should use priority 1, 2, 3, etc. based on their specificity.

        @@ -262,10 +310,18 @@ public _FinalStage prices(String key, Double value) { */ @java.lang.Override public _FinalStage putAllPrices(Map prices) { - this.prices.putAll(prices); + if (prices != null) { + this.prices.putAll(prices); + } return this; } + /** + *

        Prices (USD) by usage type for this tier. At least one price must be defined.

        + *

        Common usage types: "input", "output", "total", "request", "image" + * Prices are in USD per unit (e.g., per token).

        + *

        Example: {"input": 0.000003, "output": 0.000015} represents $3 per million input tokens and $15 per million output tokens.

        + */ @java.lang.Override @JsonSetter( value = "prices", @@ -273,7 +329,9 @@ public _FinalStage putAllPrices(Map prices) { ) public _FinalStage prices(Map prices) { this.prices.clear(); - this.prices.putAll(prices); + if (prices != null) { + this.prices.putAll(prices); + } return this; } @@ -286,7 +344,9 @@ public _FinalStage prices(Map prices) { */ @java.lang.Override public _FinalStage addAllConditions(List conditions) { - this.conditions.addAll(conditions); + if (conditions != null) { + this.conditions.addAll(conditions); + } return this; } @@ -303,6 +363,12 @@ public _FinalStage addConditions(PricingTierCondition conditions) { return this; } + /** + *

        Array of conditions that must ALL be met for this tier to match (AND logic).

        + *

        The default tier must have an empty array (conditions=[]). + * Conditional tiers should define one or more conditions that specify when this tier's pricing applies.

        + *

        Each condition specifies a regex pattern, operator, and threshold value for matching against usage details.

        + */ @java.lang.Override @JsonSetter( value = "conditions", @@ -310,7 +376,9 @@ public _FinalStage addConditions(PricingTierCondition conditions) { ) public _FinalStage conditions(List conditions) { this.conditions.clear(); - this.conditions.addAll(conditions); + if (conditions != null) { + this.conditions.addAll(conditions); + } return this; } @@ -318,5 +386,17 @@ public _FinalStage conditions(List conditions) { public PricingTierInput build() { return new PricingTierInput(name, isDefault, priority, conditions, prices, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/PricingTierOperator.java b/src/main/java/com/langfuse/client/resources/commons/types/PricingTierOperator.java index f659ea4..5e8d39c 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/PricingTierOperator.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/PricingTierOperator.java @@ -4,31 +4,125 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum PricingTierOperator { - GT("gt"), +public final class PricingTierOperator { + public static final PricingTierOperator GTE = new PricingTierOperator(Value.GTE, "gte"); - GTE("gte"), + public static final PricingTierOperator LT = new PricingTierOperator(Value.LT, "lt"); - LT("lt"), + public static final PricingTierOperator GT = new PricingTierOperator(Value.GT, "gt"); - LTE("lte"), + public static final PricingTierOperator EQ = new PricingTierOperator(Value.EQ, "eq"); - EQ("eq"), + public static final PricingTierOperator LTE = new PricingTierOperator(Value.LTE, "lte"); - NEQ("neq"); + public static final PricingTierOperator NEQ = new PricingTierOperator(Value.NEQ, "neq"); - private final String value; + private final Value value; - PricingTierOperator(String value) { + private final String string; + + PricingTierOperator(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof PricingTierOperator && this.string.equals(((PricingTierOperator) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case GTE: + return visitor.visitGte(); + case LT: + return visitor.visitLt(); + case GT: + return visitor.visitGt(); + case EQ: + return visitor.visitEq(); + case LTE: + return visitor.visitLte(); + case NEQ: + return visitor.visitNeq(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static PricingTierOperator valueOf(String value) { + switch (value) { + case "gte": + return GTE; + case "lt": + return LT; + case "gt": + return GT; + case "eq": + return EQ; + case "lte": + return LTE; + case "neq": + return NEQ; + default: + return new PricingTierOperator(Value.UNKNOWN, value); + } + } + + public enum Value { + GT, + + GTE, + + LT, + + LTE, + + EQ, + + NEQ, + + UNKNOWN + } + + public interface Visitor { + T visitGt(); + + T visitGte(); + + T visitLt(); + + T visitLte(); + + T visitEq(); + + T visitNeq(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Score.java b/src/main/java/com/langfuse/client/resources/commons/types/Score.java index c313a72..7b49476 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Score.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Score.java @@ -43,6 +43,10 @@ public static Score boolean_(BooleanScore value) { return new Score(new BooleanValue(value)); } + public static Score correction(CorrectionScore value) { + return new Score(new CorrectionValue(value)); + } + public boolean isNumeric() { return value instanceof NumericValue; } @@ -55,6 +59,10 @@ public boolean isBoolean() { return value instanceof BooleanValue; } + public boolean isCorrection() { + return value instanceof CorrectionValue; + } + public boolean _isUnknown() { return value instanceof _UnknownValue; } @@ -80,6 +88,13 @@ public Optional getBoolean() { return Optional.empty(); } + public Optional getCorrection() { + if (isCorrection()) { + return Optional.of(((CorrectionValue) value).value); + } + return Optional.empty(); + } + public Optional _getUnknown() { if (_isUnknown()) { return Optional.of(((_UnknownValue) value).value); @@ -99,6 +114,8 @@ public interface Visitor { T visitBoolean(BooleanScore boolean_); + T visitCorrection(CorrectionScore correction); + T _visitUnknown(Object unknownType); } @@ -111,7 +128,8 @@ public interface Visitor { @JsonSubTypes({ @JsonSubTypes.Type(NumericValue.class), @JsonSubTypes.Type(CategoricalValue.class), - @JsonSubTypes.Type(BooleanValue.class) + @JsonSubTypes.Type(BooleanValue.class), + @JsonSubTypes.Type(CorrectionValue.class) }) @JsonIgnoreProperties( ignoreUnknown = true @@ -246,6 +264,48 @@ public String toString() { } } + @JsonTypeName("CORRECTION") + @JsonIgnoreProperties("dataType") + private static final class CorrectionValue implements Value { + @JsonUnwrapped + private CorrectionScore value; + + @JsonCreator( + mode = JsonCreator.Mode.PROPERTIES + ) + private CorrectionValue() { + } + + private CorrectionValue(CorrectionScore value) { + this.value = value; + } + + @java.lang.Override + public T visit(Visitor visitor) { + return visitor.visitCorrection(value); + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CorrectionValue && equalTo((CorrectionValue) other); + } + + private boolean equalTo(CorrectionValue other) { + return value.equals(other.value); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value); + } + + @java.lang.Override + public String toString() { + return "Score{" + "value: " + value + "}"; + } + } + @JsonIgnoreProperties("dataType") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfig.java b/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfig.java index 791e067..d2d4e92 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfig.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfig.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Double; import java.lang.Object; @@ -112,16 +115,22 @@ public boolean getIsArchived() { /** * @return Sets minimum value for numerical scores. If not set, the minimum value defaults to -∞ */ - @JsonProperty("minValue") + @JsonIgnore public Optional getMinValue() { + if (minValue == null) { + return Optional.empty(); + } return minValue; } /** * @return Sets maximum value for numerical scores. If not set, the maximum value defaults to +∞ */ - @JsonProperty("maxValue") + @JsonIgnore public Optional getMaxValue() { + if (maxValue == null) { + return Optional.empty(); + } return maxValue; } @@ -133,8 +142,41 @@ public Optional> getCategories() { return categories; } - @JsonProperty("description") + /** + * @return Description of the score config + */ + @JsonIgnore public Optional getDescription() { + if (description == null) { + return Optional.empty(); + } + return description; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("minValue") + private Optional _getMinValue() { + return minValue; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("maxValue") + private Optional _getMaxValue() { + return maxValue; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("description") + private Optional _getDescription() { return description; } @@ -194,27 +236,52 @@ public interface DataTypeStage { } public interface IsArchivedStage { + /** + *

        Whether the score config is archived. Defaults to false

        + */ _FinalStage isArchived(boolean isArchived); } public interface _FinalStage { ScoreConfig build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Sets minimum value for numerical scores. If not set, the minimum value defaults to -∞

        + */ _FinalStage minValue(Optional minValue); _FinalStage minValue(Double minValue); + _FinalStage minValue(Nullable minValue); + + /** + *

        Sets maximum value for numerical scores. If not set, the maximum value defaults to +∞

        + */ _FinalStage maxValue(Optional maxValue); _FinalStage maxValue(Double maxValue); + _FinalStage maxValue(Nullable maxValue); + + /** + *

        Configures custom categories for categorical scores

        + */ _FinalStage categories(Optional> categories); _FinalStage categories(List categories); + /** + *

        Description of the score config

        + */ _FinalStage description(Optional description); _FinalStage description(String description); + + _FinalStage description(Nullable description); } @JsonIgnoreProperties( @@ -308,6 +375,7 @@ public IsArchivedStage dataType(@NotNull ScoreConfigDataType dataType) { } /** + *

        Whether the score config is archived. Defaults to false

        *

        Whether the score config is archived. Defaults to false

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -318,12 +386,37 @@ public _FinalStage isArchived(boolean isArchived) { return this; } + /** + *

        Description of the score config

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage description(Nullable description) { + if (description.isNull()) { + this.description = null; + } + else if (description.isEmpty()) { + this.description = Optional.empty(); + } + else { + this.description = Optional.of(description.get()); + } + return this; + } + + /** + *

        Description of the score config

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage description(String description) { this.description = Optional.ofNullable(description); return this; } + /** + *

        Description of the score config

        + */ @java.lang.Override @JsonSetter( value = "description", @@ -344,6 +437,9 @@ public _FinalStage categories(List categories) { return this; } + /** + *

        Configures custom categories for categorical scores

        + */ @java.lang.Override @JsonSetter( value = "categories", @@ -354,6 +450,24 @@ public _FinalStage categories(Optional> categories) { return this; } + /** + *

        Sets maximum value for numerical scores. If not set, the maximum value defaults to +∞

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage maxValue(Nullable maxValue) { + if (maxValue.isNull()) { + this.maxValue = null; + } + else if (maxValue.isEmpty()) { + this.maxValue = Optional.empty(); + } + else { + this.maxValue = Optional.of(maxValue.get()); + } + return this; + } + /** *

        Sets maximum value for numerical scores. If not set, the maximum value defaults to +∞

        * @return Reference to {@code this} so that method calls can be chained together. @@ -364,6 +478,9 @@ public _FinalStage maxValue(Double maxValue) { return this; } + /** + *

        Sets maximum value for numerical scores. If not set, the maximum value defaults to +∞

        + */ @java.lang.Override @JsonSetter( value = "maxValue", @@ -374,6 +491,24 @@ public _FinalStage maxValue(Optional maxValue) { return this; } + /** + *

        Sets minimum value for numerical scores. If not set, the minimum value defaults to -∞

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage minValue(Nullable minValue) { + if (minValue.isNull()) { + this.minValue = null; + } + else if (minValue.isEmpty()) { + this.minValue = Optional.empty(); + } + else { + this.minValue = Optional.of(minValue.get()); + } + return this; + } + /** *

        Sets minimum value for numerical scores. If not set, the minimum value defaults to -∞

        * @return Reference to {@code this} so that method calls can be chained together. @@ -384,6 +519,9 @@ public _FinalStage minValue(Double minValue) { return this; } + /** + *

        Sets minimum value for numerical scores. If not set, the minimum value defaults to -∞

        + */ @java.lang.Override @JsonSetter( value = "minValue", @@ -398,5 +536,17 @@ public _FinalStage minValue(Optional minValue) { public ScoreConfig build() { return new ScoreConfig(id, name, createdAt, updatedAt, projectId, dataType, isArchived, minValue, maxValue, categories, description, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfigDataType.java b/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfigDataType.java index 8e263f1..8eb7bb1 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfigDataType.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ScoreConfigDataType.java @@ -4,25 +4,95 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum ScoreConfigDataType { - NUMERIC("NUMERIC"), +public final class ScoreConfigDataType { + public static final ScoreConfigDataType CATEGORICAL = new ScoreConfigDataType(Value.CATEGORICAL, "CATEGORICAL"); - BOOLEAN("BOOLEAN"), + public static final ScoreConfigDataType NUMERIC = new ScoreConfigDataType(Value.NUMERIC, "NUMERIC"); - CATEGORICAL("CATEGORICAL"); + public static final ScoreConfigDataType BOOLEAN = new ScoreConfigDataType(Value.BOOLEAN, "BOOLEAN"); - private final String value; + private final Value value; - ScoreConfigDataType(String value) { + private final String string; + + ScoreConfigDataType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ScoreConfigDataType && this.string.equals(((ScoreConfigDataType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case CATEGORICAL: + return visitor.visitCategorical(); + case NUMERIC: + return visitor.visitNumeric(); + case BOOLEAN: + return visitor.visitBoolean(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static ScoreConfigDataType valueOf(String value) { + switch (value) { + case "CATEGORICAL": + return CATEGORICAL; + case "NUMERIC": + return NUMERIC; + case "BOOLEAN": + return BOOLEAN; + default: + return new ScoreConfigDataType(Value.UNKNOWN, value); + } + } + + public enum Value { + NUMERIC, + + BOOLEAN, + + CATEGORICAL, + + UNKNOWN + } + + public interface Visitor { + T visitNumeric(); + + T visitBoolean(); + + T visitCategorical(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ScoreDataType.java b/src/main/java/com/langfuse/client/resources/commons/types/ScoreDataType.java index af86fdf..a905ff9 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ScoreDataType.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ScoreDataType.java @@ -4,27 +4,105 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum ScoreDataType { - NUMERIC("NUMERIC"), +public final class ScoreDataType { + public static final ScoreDataType CATEGORICAL = new ScoreDataType(Value.CATEGORICAL, "CATEGORICAL"); - BOOLEAN("BOOLEAN"), + public static final ScoreDataType CORRECTION = new ScoreDataType(Value.CORRECTION, "CORRECTION"); - CATEGORICAL("CATEGORICAL"), + public static final ScoreDataType NUMERIC = new ScoreDataType(Value.NUMERIC, "NUMERIC"); - CORRECTION("CORRECTION"); + public static final ScoreDataType BOOLEAN = new ScoreDataType(Value.BOOLEAN, "BOOLEAN"); - private final String value; + private final Value value; - ScoreDataType(String value) { + private final String string; + + ScoreDataType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ScoreDataType && this.string.equals(((ScoreDataType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case CATEGORICAL: + return visitor.visitCategorical(); + case CORRECTION: + return visitor.visitCorrection(); + case NUMERIC: + return visitor.visitNumeric(); + case BOOLEAN: + return visitor.visitBoolean(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static ScoreDataType valueOf(String value) { + switch (value) { + case "CATEGORICAL": + return CATEGORICAL; + case "CORRECTION": + return CORRECTION; + case "NUMERIC": + return NUMERIC; + case "BOOLEAN": + return BOOLEAN; + default: + return new ScoreDataType(Value.UNKNOWN, value); + } + } + + public enum Value { + NUMERIC, + + BOOLEAN, + + CATEGORICAL, + + CORRECTION, + + UNKNOWN + } + + public interface Visitor { + T visitNumeric(); + + T visitBoolean(); + + T visitCategorical(); + + T visitCorrection(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/ScoreSource.java b/src/main/java/com/langfuse/client/resources/commons/types/ScoreSource.java index 42b0d2b..e49b4ad 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/ScoreSource.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/ScoreSource.java @@ -4,25 +4,95 @@ package com.langfuse.client.resources.commons.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum ScoreSource { - ANNOTATION("ANNOTATION"), +public final class ScoreSource { + public static final ScoreSource API = new ScoreSource(Value.API, "API"); - API("API"), + public static final ScoreSource ANNOTATION = new ScoreSource(Value.ANNOTATION, "ANNOTATION"); - EVAL("EVAL"); + public static final ScoreSource EVAL = new ScoreSource(Value.EVAL, "EVAL"); - private final String value; + private final Value value; - ScoreSource(String value) { + private final String string; + + ScoreSource(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ScoreSource && this.string.equals(((ScoreSource) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case API: + return visitor.visitApi(); + case ANNOTATION: + return visitor.visitAnnotation(); + case EVAL: + return visitor.visitEval(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static ScoreSource valueOf(String value) { + switch (value) { + case "API": + return API; + case "ANNOTATION": + return ANNOTATION; + case "EVAL": + return EVAL; + default: + return new ScoreSource(Value.UNKNOWN, value); + } + } + + public enum Value { + ANNOTATION, + + API, + + EVAL, + + UNKNOWN + } + + public interface Visitor { + T visitAnnotation(); + + T visitApi(); + + T visitEval(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Session.java b/src/main/java/com/langfuse/client/resources/commons/types/Session.java index cc027e5..a15e1fe 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Session.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Session.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; @@ -19,7 +18,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; -import java.util.Optional; import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) @@ -33,12 +31,12 @@ public final class Session implements ISession { private final String projectId; - private final Optional environment; + private final String environment; private final Map additionalProperties; - private Session(String id, OffsetDateTime createdAt, String projectId, - Optional environment, Map additionalProperties) { + private Session(String id, OffsetDateTime createdAt, String projectId, String environment, + Map additionalProperties) { this.id = id; this.createdAt = createdAt; this.projectId = projectId; @@ -69,7 +67,7 @@ public String getProjectId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -113,28 +111,35 @@ public interface CreatedAtStage { } public interface ProjectIdStage { - _FinalStage projectId(@NotNull String projectId); + EnvironmentStage projectId(@NotNull String projectId); + } + + public interface EnvironmentStage { + /** + *

        The environment from which this session originated.

        + */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { Session build(); - _FinalStage environment(Optional environment); + _FinalStage additionalProperty(String key, Object value); - _FinalStage environment(String environment); + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, CreatedAtStage, ProjectIdStage, _FinalStage { + public static final class Builder implements IdStage, CreatedAtStage, ProjectIdStage, EnvironmentStage, _FinalStage { private String id; private OffsetDateTime createdAt; private String projectId; - private Optional environment = Optional.empty(); + private String environment; @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -167,34 +172,38 @@ public ProjectIdStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("projectId") - public _FinalStage projectId(@NotNull String projectId) { + public EnvironmentStage projectId(@NotNull String projectId) { this.projectId = Objects.requireNonNull(projectId, "projectId must not be null"); return this; } /** + *

        The environment from which this session originated.

        *

        The environment from which this session originated.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public Session build() { + return new Session(id, createdAt, projectId, environment, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); return this; } @java.lang.Override - public Session build() { - return new Session(id, createdAt, projectId, environment, additionalProperties); + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/SessionWithTraces.java b/src/main/java/com/langfuse/client/resources/commons/types/SessionWithTraces.java index 2abdb9e..5da28a2 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/SessionWithTraces.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/SessionWithTraces.java @@ -21,7 +21,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Optional; import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) @@ -35,14 +34,14 @@ public final class SessionWithTraces implements ISession { private final String projectId; - private final Optional environment; + private final String environment; private final List traces; private final Map additionalProperties; private SessionWithTraces(String id, OffsetDateTime createdAt, String projectId, - Optional environment, List traces, Map additionalProperties) { + String environment, List traces, Map additionalProperties) { this.id = id; this.createdAt = createdAt; this.projectId = projectId; @@ -74,7 +73,7 @@ public String getProjectId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -123,15 +122,22 @@ public interface CreatedAtStage { } public interface ProjectIdStage { - _FinalStage projectId(@NotNull String projectId); + EnvironmentStage projectId(@NotNull String projectId); + } + + public interface EnvironmentStage { + /** + *

        The environment from which this session originated.

        + */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { SessionWithTraces build(); - _FinalStage environment(Optional environment); + _FinalStage additionalProperty(String key, Object value); - _FinalStage environment(String environment); + _FinalStage additionalProperties(Map additionalProperties); _FinalStage traces(List traces); @@ -143,16 +149,16 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, CreatedAtStage, ProjectIdStage, _FinalStage { + public static final class Builder implements IdStage, CreatedAtStage, ProjectIdStage, EnvironmentStage, _FinalStage { private String id; private OffsetDateTime createdAt; private String projectId; - private List traces = new ArrayList<>(); + private String environment; - private Optional environment = Optional.empty(); + private List traces = new ArrayList<>(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -186,14 +192,28 @@ public ProjectIdStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("projectId") - public _FinalStage projectId(@NotNull String projectId) { + public EnvironmentStage projectId(@NotNull String projectId) { this.projectId = Objects.requireNonNull(projectId, "projectId must not be null"); return this; } + /** + *

        The environment from which this session originated.

        + *

        The environment from which this session originated.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + @java.lang.Override public _FinalStage addAllTraces(List traces) { - this.traces.addAll(traces); + if (traces != null) { + this.traces.addAll(traces); + } return this; } @@ -210,33 +230,27 @@ public _FinalStage addTraces(Trace traces) { ) public _FinalStage traces(List traces) { this.traces.clear(); - this.traces.addAll(traces); + if (traces != null) { + this.traces.addAll(traces); + } return this; } - /** - *

        The environment from which this session originated.

        - * @return Reference to {@code this} so that method calls can be chained together. - */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; + public SessionWithTraces build() { + return new SessionWithTraces(id, createdAt, projectId, environment, traces, additionalProperties); } @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); return this; } @java.lang.Override - public SessionWithTraces build() { - return new SessionWithTraces(id, createdAt, projectId, environment, traces, additionalProperties); + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Trace.java b/src/main/java/com/langfuse/client/resources/commons/types/Trace.java index 5c6c7fe..2d16f5f 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Trace.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Trace.java @@ -6,17 +6,20 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; -import java.lang.Boolean; import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -49,18 +52,18 @@ public final class Trace implements ITrace { private final Optional metadata; - private final Optional> tags; + private final List tags; - private final Optional public_; + private final boolean public_; - private final Optional environment; + private final String environment; private final Map additionalProperties; private Trace(String id, OffsetDateTime timestamp, Optional name, Optional input, Optional output, Optional sessionId, Optional release, Optional version, Optional userId, Optional metadata, - Optional> tags, Optional public_, Optional environment, + List tags, boolean public_, String environment, Map additionalProperties) { this.id = id; this.timestamp = timestamp; @@ -99,9 +102,12 @@ public OffsetDateTime getTimestamp() { /** * @return The name of the trace */ - @JsonProperty("name") + @JsonIgnore @java.lang.Override public Optional getName() { + if (name == null) { + return Optional.empty(); + } return name; } @@ -126,36 +132,48 @@ public Optional getOutput() { /** * @return The session identifier associated with the trace */ - @JsonProperty("sessionId") + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } /** * @return The release version of the application when the trace was created */ - @JsonProperty("release") + @JsonIgnore @java.lang.Override public Optional getRelease() { + if (release == null) { + return Optional.empty(); + } return release; } /** * @return The version of the trace */ - @JsonProperty("version") + @JsonIgnore @java.lang.Override public Optional getVersion() { + if (version == null) { + return Optional.empty(); + } return version; } /** * @return The user identifier associated with the trace */ - @JsonProperty("userId") + @JsonIgnore @java.lang.Override public Optional getUserId() { + if (userId == null) { + return Optional.empty(); + } return userId; } @@ -169,11 +187,11 @@ public Optional getMetadata() { } /** - * @return The tags associated with the trace. Can be an array of strings or null. + * @return The tags associated with the trace. */ @JsonProperty("tags") @java.lang.Override - public Optional> getTags() { + public List getTags() { return tags; } @@ -182,7 +200,7 @@ public Optional> getTags() { */ @JsonProperty("public") @java.lang.Override - public Optional getPublic() { + public boolean getPublic() { return public_; } @@ -191,10 +209,55 @@ public Optional getPublic() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("name") + private Optional _getName() { + return name; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("release") + private Optional _getRelease() { + return release; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("version") + private Optional _getVersion() { + return version; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("userId") + private Optional _getUserId() { + return userId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -207,7 +270,7 @@ public Map getAdditionalProperties() { } private boolean equalTo(Trace other) { - return id.equals(other.id) && timestamp.equals(other.timestamp) && name.equals(other.name) && input.equals(other.input) && output.equals(other.output) && sessionId.equals(other.sessionId) && release.equals(other.release) && version.equals(other.version) && userId.equals(other.userId) && metadata.equals(other.metadata) && tags.equals(other.tags) && public_.equals(other.public_) && environment.equals(other.environment); + return id.equals(other.id) && timestamp.equals(other.timestamp) && name.equals(other.name) && input.equals(other.input) && output.equals(other.output) && sessionId.equals(other.sessionId) && release.equals(other.release) && version.equals(other.version) && userId.equals(other.userId) && metadata.equals(other.metadata) && tags.equals(other.tags) && public_ == other.public_ && environment.equals(other.environment); } @java.lang.Override @@ -225,76 +288,131 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        The unique identifier of a trace

        + */ TimestampStage id(@NotNull String id); Builder from(Trace other); } public interface TimestampStage { - _FinalStage timestamp(@NotNull OffsetDateTime timestamp); + /** + *

        The timestamp when the trace was created

        + */ + PublicStage timestamp(@NotNull OffsetDateTime timestamp); + } + + public interface PublicStage { + /** + *

        Public traces are accessible via url without login

        + */ + EnvironmentStage public_(boolean public_); + } + + public interface EnvironmentStage { + /** + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { Trace build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The name of the trace

        + */ _FinalStage name(Optional name); _FinalStage name(String name); + _FinalStage name(Nullable name); + + /** + *

        The input data of the trace. Can be any JSON.

        + */ _FinalStage input(Optional input); _FinalStage input(Object input); + /** + *

        The output data of the trace. Can be any JSON.

        + */ _FinalStage output(Optional output); _FinalStage output(Object output); + /** + *

        The session identifier associated with the trace

        + */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

        The release version of the application when the trace was created

        + */ _FinalStage release(Optional release); _FinalStage release(String release); + _FinalStage release(Nullable release); + + /** + *

        The version of the trace

        + */ _FinalStage version(Optional version); _FinalStage version(String version); + _FinalStage version(Nullable version); + + /** + *

        The user identifier associated with the trace

        + */ _FinalStage userId(Optional userId); _FinalStage userId(String userId); + _FinalStage userId(Nullable userId); + + /** + *

        The metadata associated with the trace. Can be any JSON.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); - _FinalStage tags(Optional> tags); - + /** + *

        The tags associated with the trace.

        + */ _FinalStage tags(List tags); - _FinalStage public_(Optional public_); + _FinalStage addTags(String tags); - _FinalStage public_(Boolean public_); - - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage addAllTags(List tags); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TimestampStage, _FinalStage { + public static final class Builder implements IdStage, TimestampStage, PublicStage, EnvironmentStage, _FinalStage { private String id; private OffsetDateTime timestamp; - private Optional environment = Optional.empty(); + private boolean public_; - private Optional public_ = Optional.empty(); + private String environment; - private Optional> tags = Optional.empty(); + private List tags = new ArrayList<>(); private Optional metadata = Optional.empty(); @@ -337,6 +455,7 @@ public Builder from(Trace other) { } /** + *

        The unique identifier of a trace

        *

        The unique identifier of a trace

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -348,73 +467,76 @@ public TimestampStage id(@NotNull String id) { } /** + *

        The timestamp when the trace was created

        *

        The timestamp when the trace was created

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("timestamp") - public _FinalStage timestamp(@NotNull OffsetDateTime timestamp) { + public PublicStage timestamp(@NotNull OffsetDateTime timestamp) { this.timestamp = Objects.requireNonNull(timestamp, "timestamp must not be null"); return this; } /** - *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        Public traces are accessible via url without login

        + *

        Public traces are accessible via url without login

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + @JsonSetter("public") + public EnvironmentStage public_(boolean public_) { + this.public_ = public_; return this; } /** - *

        Public traces are accessible via url without login

        + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage public_(Boolean public_) { - this.public_ = Optional.ofNullable(public_); + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } + /** + *

        The tags associated with the trace.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - @JsonSetter( - value = "public", - nulls = Nulls.SKIP - ) - public _FinalStage public_(Optional public_) { - this.public_ = public_; + public _FinalStage addAllTags(List tags) { + if (tags != null) { + this.tags.addAll(tags); + } return this; } /** - *

        The tags associated with the trace. Can be an array of strings or null.

        + *

        The tags associated with the trace.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage tags(List tags) { - this.tags = Optional.ofNullable(tags); + public _FinalStage addTags(String tags) { + this.tags.add(tags); return this; } + /** + *

        The tags associated with the trace.

        + */ @java.lang.Override @JsonSetter( value = "tags", nulls = Nulls.SKIP ) - public _FinalStage tags(Optional> tags) { - this.tags = tags; + public _FinalStage tags(List tags) { + this.tags.clear(); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -428,6 +550,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        The metadata associated with the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -438,6 +563,24 @@ public _FinalStage metadata(Optional metadata) { return this; } + /** + *

        The user identifier associated with the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage userId(Nullable userId) { + if (userId.isNull()) { + this.userId = null; + } + else if (userId.isEmpty()) { + this.userId = Optional.empty(); + } + else { + this.userId = Optional.of(userId.get()); + } + return this; + } + /** *

        The user identifier associated with the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -448,6 +591,9 @@ public _FinalStage userId(String userId) { return this; } + /** + *

        The user identifier associated with the trace

        + */ @java.lang.Override @JsonSetter( value = "userId", @@ -458,6 +604,24 @@ public _FinalStage userId(Optional userId) { return this; } + /** + *

        The version of the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage version(Nullable version) { + if (version.isNull()) { + this.version = null; + } + else if (version.isEmpty()) { + this.version = Optional.empty(); + } + else { + this.version = Optional.of(version.get()); + } + return this; + } + /** *

        The version of the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -468,6 +632,9 @@ public _FinalStage version(String version) { return this; } + /** + *

        The version of the trace

        + */ @java.lang.Override @JsonSetter( value = "version", @@ -478,6 +645,24 @@ public _FinalStage version(Optional version) { return this; } + /** + *

        The release version of the application when the trace was created

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage release(Nullable release) { + if (release.isNull()) { + this.release = null; + } + else if (release.isEmpty()) { + this.release = Optional.empty(); + } + else { + this.release = Optional.of(release.get()); + } + return this; + } + /** *

        The release version of the application when the trace was created

        * @return Reference to {@code this} so that method calls can be chained together. @@ -488,6 +673,9 @@ public _FinalStage release(String release) { return this; } + /** + *

        The release version of the application when the trace was created

        + */ @java.lang.Override @JsonSetter( value = "release", @@ -498,6 +686,24 @@ public _FinalStage release(Optional release) { return this; } + /** + *

        The session identifier associated with the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + /** *

        The session identifier associated with the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -508,6 +714,9 @@ public _FinalStage sessionId(String sessionId) { return this; } + /** + *

        The session identifier associated with the trace

        + */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -528,6 +737,9 @@ public _FinalStage output(Object output) { return this; } + /** + *

        The output data of the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "output", @@ -548,6 +760,9 @@ public _FinalStage input(Object input) { return this; } + /** + *

        The input data of the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "input", @@ -558,6 +773,24 @@ public _FinalStage input(Optional input) { return this; } + /** + *

        The name of the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage name(Nullable name) { + if (name.isNull()) { + this.name = null; + } + else if (name.isEmpty()) { + this.name = Optional.empty(); + } + else { + this.name = Optional.of(name.get()); + } + return this; + } + /** *

        The name of the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -568,6 +801,9 @@ public _FinalStage name(String name) { return this; } + /** + *

        The name of the trace

        + */ @java.lang.Override @JsonSetter( value = "name", @@ -582,5 +818,17 @@ public _FinalStage name(Optional name) { public Trace build() { return new Trace(id, timestamp, name, input, output, sessionId, release, version, userId, metadata, tags, public_, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/TraceWithDetails.java b/src/main/java/com/langfuse/client/resources/commons/types/TraceWithDetails.java index 3df1c3d..1efa3e5 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/TraceWithDetails.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/TraceWithDetails.java @@ -6,14 +6,17 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; -import java.lang.Boolean; +import java.lang.Double; import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; @@ -50,30 +53,31 @@ public final class TraceWithDetails implements ITrace { private final Optional metadata; - private final Optional> tags; + private final List tags; - private final Optional public_; + private final boolean public_; - private final Optional environment; + private final String environment; private final String htmlPath; - private final double latency; + private final Optional latency; - private final double totalCost; + private final Optional totalCost; - private final List observations; + private final Optional> observations; - private final List scores; + private final Optional> scores; private final Map additionalProperties; private TraceWithDetails(String id, OffsetDateTime timestamp, Optional name, Optional input, Optional output, Optional sessionId, Optional release, Optional version, Optional userId, - Optional metadata, Optional> tags, Optional public_, - Optional environment, String htmlPath, double latency, double totalCost, - List observations, List scores, Map additionalProperties) { + Optional metadata, List tags, boolean public_, String environment, + String htmlPath, Optional latency, Optional totalCost, + Optional> observations, Optional> scores, + Map additionalProperties) { this.id = id; this.timestamp = timestamp; this.name = name; @@ -116,9 +120,12 @@ public OffsetDateTime getTimestamp() { /** * @return The name of the trace */ - @JsonProperty("name") + @JsonIgnore @java.lang.Override public Optional getName() { + if (name == null) { + return Optional.empty(); + } return name; } @@ -143,36 +150,48 @@ public Optional getOutput() { /** * @return The session identifier associated with the trace */ - @JsonProperty("sessionId") + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } /** * @return The release version of the application when the trace was created */ - @JsonProperty("release") + @JsonIgnore @java.lang.Override public Optional getRelease() { + if (release == null) { + return Optional.empty(); + } return release; } /** * @return The version of the trace */ - @JsonProperty("version") + @JsonIgnore @java.lang.Override public Optional getVersion() { + if (version == null) { + return Optional.empty(); + } return version; } /** * @return The user identifier associated with the trace */ - @JsonProperty("userId") + @JsonIgnore @java.lang.Override public Optional getUserId() { + if (userId == null) { + return Optional.empty(); + } return userId; } @@ -186,11 +205,11 @@ public Optional getMetadata() { } /** - * @return The tags associated with the trace. Can be an array of strings or null. + * @return The tags associated with the trace. */ @JsonProperty("tags") @java.lang.Override - public Optional> getTags() { + public List getTags() { return tags; } @@ -199,7 +218,7 @@ public Optional> getTags() { */ @JsonProperty("public") @java.lang.Override - public Optional getPublic() { + public boolean getPublic() { return public_; } @@ -208,7 +227,7 @@ public Optional getPublic() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -223,32 +242,125 @@ public String getHtmlPath() { /** * @return Latency of trace in seconds */ - @JsonProperty("latency") - public double getLatency() { + @JsonIgnore + public Optional getLatency() { + if (latency == null) { + return Optional.empty(); + } return latency; } /** * @return Cost of trace in USD */ - @JsonProperty("totalCost") - public double getTotalCost() { + @JsonIgnore + public Optional getTotalCost() { + if (totalCost == null) { + return Optional.empty(); + } return totalCost; } /** * @return List of observation ids */ - @JsonProperty("observations") - public List getObservations() { + @JsonIgnore + public Optional> getObservations() { + if (observations == null) { + return Optional.empty(); + } return observations; } /** * @return List of score ids */ + @JsonIgnore + public Optional> getScores() { + if (scores == null) { + return Optional.empty(); + } + return scores; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("name") + private Optional _getName() { + return name; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("release") + private Optional _getRelease() { + return release; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("version") + private Optional _getVersion() { + return version; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("userId") + private Optional _getUserId() { + return userId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("latency") + private Optional _getLatency() { + return latency; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("totalCost") + private Optional _getTotalCost() { + return totalCost; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observations") + private Optional> _getObservations() { + return observations; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) @JsonProperty("scores") - public List getScores() { + private Optional> _getScores() { return scores; } @@ -264,7 +376,7 @@ public Map getAdditionalProperties() { } private boolean equalTo(TraceWithDetails other) { - return id.equals(other.id) && timestamp.equals(other.timestamp) && name.equals(other.name) && input.equals(other.input) && output.equals(other.output) && sessionId.equals(other.sessionId) && release.equals(other.release) && version.equals(other.version) && userId.equals(other.userId) && metadata.equals(other.metadata) && tags.equals(other.tags) && public_.equals(other.public_) && environment.equals(other.environment) && htmlPath.equals(other.htmlPath) && latency == other.latency && totalCost == other.totalCost && observations.equals(other.observations) && scores.equals(other.scores); + return id.equals(other.id) && timestamp.equals(other.timestamp) && name.equals(other.name) && input.equals(other.input) && output.equals(other.output) && sessionId.equals(other.sessionId) && release.equals(other.release) && version.equals(other.version) && userId.equals(other.userId) && metadata.equals(other.metadata) && tags.equals(other.tags) && public_ == other.public_ && environment.equals(other.environment) && htmlPath.equals(other.htmlPath) && latency.equals(other.latency) && totalCost.equals(other.totalCost) && observations.equals(other.observations) && scores.equals(other.scores); } @java.lang.Override @@ -282,110 +394,184 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        The unique identifier of a trace

        + */ TimestampStage id(@NotNull String id); Builder from(TraceWithDetails other); } public interface TimestampStage { - HtmlPathStage timestamp(@NotNull OffsetDateTime timestamp); + /** + *

        The timestamp when the trace was created

        + */ + PublicStage timestamp(@NotNull OffsetDateTime timestamp); } - public interface HtmlPathStage { - LatencyStage htmlPath(@NotNull String htmlPath); + public interface PublicStage { + /** + *

        Public traces are accessible via url without login

        + */ + EnvironmentStage public_(boolean public_); } - public interface LatencyStage { - TotalCostStage latency(double latency); + public interface EnvironmentStage { + /** + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ + HtmlPathStage environment(@NotNull String environment); } - public interface TotalCostStage { - _FinalStage totalCost(double totalCost); + public interface HtmlPathStage { + /** + *

        Path of trace in Langfuse UI

        + */ + _FinalStage htmlPath(@NotNull String htmlPath); } public interface _FinalStage { TraceWithDetails build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The name of the trace

        + */ _FinalStage name(Optional name); _FinalStage name(String name); + _FinalStage name(Nullable name); + + /** + *

        The input data of the trace. Can be any JSON.

        + */ _FinalStage input(Optional input); _FinalStage input(Object input); + /** + *

        The output data of the trace. Can be any JSON.

        + */ _FinalStage output(Optional output); _FinalStage output(Object output); + /** + *

        The session identifier associated with the trace

        + */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

        The release version of the application when the trace was created

        + */ _FinalStage release(Optional release); _FinalStage release(String release); + _FinalStage release(Nullable release); + + /** + *

        The version of the trace

        + */ _FinalStage version(Optional version); _FinalStage version(String version); + _FinalStage version(Nullable version); + + /** + *

        The user identifier associated with the trace

        + */ _FinalStage userId(Optional userId); _FinalStage userId(String userId); + _FinalStage userId(Nullable userId); + + /** + *

        The metadata associated with the trace. Can be any JSON.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); - _FinalStage tags(Optional> tags); - + /** + *

        The tags associated with the trace.

        + */ _FinalStage tags(List tags); - _FinalStage public_(Optional public_); + _FinalStage addTags(String tags); + + _FinalStage addAllTags(List tags); + + /** + *

        Latency of trace in seconds

        + */ + _FinalStage latency(Optional latency); + + _FinalStage latency(Double latency); + + _FinalStage latency(Nullable latency); - _FinalStage public_(Boolean public_); + /** + *

        Cost of trace in USD

        + */ + _FinalStage totalCost(Optional totalCost); - _FinalStage environment(Optional environment); + _FinalStage totalCost(Double totalCost); - _FinalStage environment(String environment); + _FinalStage totalCost(Nullable totalCost); + + /** + *

        List of observation ids

        + */ + _FinalStage observations(Optional> observations); _FinalStage observations(List observations); - _FinalStage addObservations(String observations); + _FinalStage observations(Nullable> observations); - _FinalStage addAllObservations(List observations); + /** + *

        List of score ids

        + */ + _FinalStage scores(Optional> scores); _FinalStage scores(List scores); - _FinalStage addScores(String scores); - - _FinalStage addAllScores(List scores); + _FinalStage scores(Nullable> scores); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TimestampStage, HtmlPathStage, LatencyStage, TotalCostStage, _FinalStage { + public static final class Builder implements IdStage, TimestampStage, PublicStage, EnvironmentStage, HtmlPathStage, _FinalStage { private String id; private OffsetDateTime timestamp; - private String htmlPath; + private boolean public_; - private double latency; + private String environment; - private double totalCost; + private String htmlPath; - private List scores = new ArrayList<>(); + private Optional> scores = Optional.empty(); - private List observations = new ArrayList<>(); + private Optional> observations = Optional.empty(); - private Optional environment = Optional.empty(); + private Optional totalCost = Optional.empty(); - private Optional public_ = Optional.empty(); + private Optional latency = Optional.empty(); - private Optional> tags = Optional.empty(); + private List tags = new ArrayList<>(); private Optional metadata = Optional.empty(); @@ -433,6 +619,7 @@ public Builder from(TraceWithDetails other) { } /** + *

        The unique identifier of a trace

        *

        The unique identifier of a trace

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -444,46 +631,50 @@ public TimestampStage id(@NotNull String id) { } /** + *

        The timestamp when the trace was created

        *

        The timestamp when the trace was created

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("timestamp") - public HtmlPathStage timestamp(@NotNull OffsetDateTime timestamp) { + public PublicStage timestamp(@NotNull OffsetDateTime timestamp) { this.timestamp = Objects.requireNonNull(timestamp, "timestamp must not be null"); return this; } /** - *

        Path of trace in Langfuse UI

        + *

        Public traces are accessible via url without login

        + *

        Public traces are accessible via url without login

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("htmlPath") - public LatencyStage htmlPath(@NotNull String htmlPath) { - this.htmlPath = Objects.requireNonNull(htmlPath, "htmlPath must not be null"); + @JsonSetter("public") + public EnvironmentStage public_(boolean public_) { + this.public_ = public_; return this; } /** - *

        Latency of trace in seconds

        + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("latency") - public TotalCostStage latency(double latency) { - this.latency = latency; + @JsonSetter("environment") + public HtmlPathStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } /** - *

        Cost of trace in USD

        + *

        Path of trace in Langfuse UI

        + *

        Path of trace in Langfuse UI

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("totalCost") - public _FinalStage totalCost(double totalCost) { - this.totalCost = totalCost; + @JsonSetter("htmlPath") + public _FinalStage htmlPath(@NotNull String htmlPath) { + this.htmlPath = Objects.requireNonNull(htmlPath, "htmlPath must not be null"); return this; } @@ -492,8 +683,16 @@ public _FinalStage totalCost(double totalCost) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage addAllScores(List scores) { - this.scores.addAll(scores); + public _FinalStage scores(Nullable> scores) { + if (scores.isNull()) { + this.scores = null; + } + else if (scores.isEmpty()) { + this.scores = Optional.empty(); + } + else { + this.scores = Optional.of(scores.get()); + } return this; } @@ -502,19 +701,21 @@ public _FinalStage addAllScores(List scores) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage addScores(String scores) { - this.scores.add(scores); + public _FinalStage scores(List scores) { + this.scores = Optional.ofNullable(scores); return this; } + /** + *

        List of score ids

        + */ @java.lang.Override @JsonSetter( value = "scores", nulls = Nulls.SKIP ) - public _FinalStage scores(List scores) { - this.scores.clear(); - this.scores.addAll(scores); + public _FinalStage scores(Optional> scores) { + this.scores = scores; return this; } @@ -523,8 +724,16 @@ public _FinalStage scores(List scores) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage addAllObservations(List observations) { - this.observations.addAll(observations); + public _FinalStage observations(Nullable> observations) { + if (observations.isNull()) { + this.observations = null; + } + else if (observations.isEmpty()) { + this.observations = Optional.empty(); + } + else { + this.observations = Optional.of(observations.get()); + } return this; } @@ -533,79 +742,141 @@ public _FinalStage addAllObservations(List observations) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage addObservations(String observations) { - this.observations.add(observations); + public _FinalStage observations(List observations) { + this.observations = Optional.ofNullable(observations); return this; } + /** + *

        List of observation ids

        + */ @java.lang.Override @JsonSetter( value = "observations", nulls = Nulls.SKIP ) - public _FinalStage observations(List observations) { - this.observations.clear(); - this.observations.addAll(observations); + public _FinalStage observations(Optional> observations) { + this.observations = observations; return this; } /** - *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        Cost of trace in USD

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage totalCost(Nullable totalCost) { + if (totalCost.isNull()) { + this.totalCost = null; + } + else if (totalCost.isEmpty()) { + this.totalCost = Optional.empty(); + } + else { + this.totalCost = Optional.of(totalCost.get()); + } + return this; + } + + /** + *

        Cost of trace in USD

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + public _FinalStage totalCost(Double totalCost) { + this.totalCost = Optional.ofNullable(totalCost); return this; } + /** + *

        Cost of trace in USD

        + */ @java.lang.Override @JsonSetter( - value = "environment", + value = "totalCost", nulls = Nulls.SKIP ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage totalCost(Optional totalCost) { + this.totalCost = totalCost; return this; } /** - *

        Public traces are accessible via url without login

        + *

        Latency of trace in seconds

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage public_(Boolean public_) { - this.public_ = Optional.ofNullable(public_); + public _FinalStage latency(Nullable latency) { + if (latency.isNull()) { + this.latency = null; + } + else if (latency.isEmpty()) { + this.latency = Optional.empty(); + } + else { + this.latency = Optional.of(latency.get()); + } return this; } + /** + *

        Latency of trace in seconds

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage latency(Double latency) { + this.latency = Optional.ofNullable(latency); + return this; + } + + /** + *

        Latency of trace in seconds

        + */ @java.lang.Override @JsonSetter( - value = "public", + value = "latency", nulls = Nulls.SKIP ) - public _FinalStage public_(Optional public_) { - this.public_ = public_; + public _FinalStage latency(Optional latency) { + this.latency = latency; return this; } /** - *

        The tags associated with the trace. Can be an array of strings or null.

        + *

        The tags associated with the trace.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage tags(List tags) { - this.tags = Optional.ofNullable(tags); + public _FinalStage addAllTags(List tags) { + if (tags != null) { + this.tags.addAll(tags); + } return this; } + /** + *

        The tags associated with the trace.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addTags(String tags) { + this.tags.add(tags); + return this; + } + + /** + *

        The tags associated with the trace.

        + */ @java.lang.Override @JsonSetter( value = "tags", nulls = Nulls.SKIP ) - public _FinalStage tags(Optional> tags) { - this.tags = tags; + public _FinalStage tags(List tags) { + this.tags.clear(); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -619,6 +890,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        The metadata associated with the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -629,6 +903,24 @@ public _FinalStage metadata(Optional metadata) { return this; } + /** + *

        The user identifier associated with the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage userId(Nullable userId) { + if (userId.isNull()) { + this.userId = null; + } + else if (userId.isEmpty()) { + this.userId = Optional.empty(); + } + else { + this.userId = Optional.of(userId.get()); + } + return this; + } + /** *

        The user identifier associated with the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -639,6 +931,9 @@ public _FinalStage userId(String userId) { return this; } + /** + *

        The user identifier associated with the trace

        + */ @java.lang.Override @JsonSetter( value = "userId", @@ -649,6 +944,24 @@ public _FinalStage userId(Optional userId) { return this; } + /** + *

        The version of the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage version(Nullable version) { + if (version.isNull()) { + this.version = null; + } + else if (version.isEmpty()) { + this.version = Optional.empty(); + } + else { + this.version = Optional.of(version.get()); + } + return this; + } + /** *

        The version of the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -659,6 +972,9 @@ public _FinalStage version(String version) { return this; } + /** + *

        The version of the trace

        + */ @java.lang.Override @JsonSetter( value = "version", @@ -669,6 +985,24 @@ public _FinalStage version(Optional version) { return this; } + /** + *

        The release version of the application when the trace was created

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage release(Nullable release) { + if (release.isNull()) { + this.release = null; + } + else if (release.isEmpty()) { + this.release = Optional.empty(); + } + else { + this.release = Optional.of(release.get()); + } + return this; + } + /** *

        The release version of the application when the trace was created

        * @return Reference to {@code this} so that method calls can be chained together. @@ -679,6 +1013,9 @@ public _FinalStage release(String release) { return this; } + /** + *

        The release version of the application when the trace was created

        + */ @java.lang.Override @JsonSetter( value = "release", @@ -689,6 +1026,24 @@ public _FinalStage release(Optional release) { return this; } + /** + *

        The session identifier associated with the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + /** *

        The session identifier associated with the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -699,6 +1054,9 @@ public _FinalStage sessionId(String sessionId) { return this; } + /** + *

        The session identifier associated with the trace

        + */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -719,6 +1077,9 @@ public _FinalStage output(Object output) { return this; } + /** + *

        The output data of the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "output", @@ -739,6 +1100,9 @@ public _FinalStage input(Object input) { return this; } + /** + *

        The input data of the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "input", @@ -749,6 +1113,24 @@ public _FinalStage input(Optional input) { return this; } + /** + *

        The name of the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage name(Nullable name) { + if (name.isNull()) { + this.name = null; + } + else if (name.isEmpty()) { + this.name = Optional.empty(); + } + else { + this.name = Optional.of(name.get()); + } + return this; + } + /** *

        The name of the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -759,6 +1141,9 @@ public _FinalStage name(String name) { return this; } + /** + *

        The name of the trace

        + */ @java.lang.Override @JsonSetter( value = "name", @@ -773,5 +1158,17 @@ public _FinalStage name(Optional name) { public TraceWithDetails build() { return new TraceWithDetails(id, timestamp, name, input, output, sessionId, release, version, userId, metadata, tags, public_, environment, htmlPath, latency, totalCost, observations, scores, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/TraceWithFullDetails.java b/src/main/java/com/langfuse/client/resources/commons/types/TraceWithFullDetails.java index 41aa688..1404012 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/TraceWithFullDetails.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/TraceWithFullDetails.java @@ -6,14 +6,17 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; -import java.lang.Boolean; +import java.lang.Double; import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; @@ -50,17 +53,17 @@ public final class TraceWithFullDetails implements ITrace { private final Optional metadata; - private final Optional> tags; + private final List tags; - private final Optional public_; + private final boolean public_; - private final Optional environment; + private final String environment; private final String htmlPath; - private final double latency; + private final Optional latency; - private final double totalCost; + private final Optional totalCost; private final List observations; @@ -71,8 +74,8 @@ public final class TraceWithFullDetails implements ITrace { private TraceWithFullDetails(String id, OffsetDateTime timestamp, Optional name, Optional input, Optional output, Optional sessionId, Optional release, Optional version, Optional userId, - Optional metadata, Optional> tags, Optional public_, - Optional environment, String htmlPath, double latency, double totalCost, + Optional metadata, List tags, boolean public_, String environment, + String htmlPath, Optional latency, Optional totalCost, List observations, List scores, Map additionalProperties) { this.id = id; @@ -117,9 +120,12 @@ public OffsetDateTime getTimestamp() { /** * @return The name of the trace */ - @JsonProperty("name") + @JsonIgnore @java.lang.Override public Optional getName() { + if (name == null) { + return Optional.empty(); + } return name; } @@ -144,36 +150,48 @@ public Optional getOutput() { /** * @return The session identifier associated with the trace */ - @JsonProperty("sessionId") + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } /** * @return The release version of the application when the trace was created */ - @JsonProperty("release") + @JsonIgnore @java.lang.Override public Optional getRelease() { + if (release == null) { + return Optional.empty(); + } return release; } /** * @return The version of the trace */ - @JsonProperty("version") + @JsonIgnore @java.lang.Override public Optional getVersion() { + if (version == null) { + return Optional.empty(); + } return version; } /** * @return The user identifier associated with the trace */ - @JsonProperty("userId") + @JsonIgnore @java.lang.Override public Optional getUserId() { + if (userId == null) { + return Optional.empty(); + } return userId; } @@ -187,11 +205,11 @@ public Optional getMetadata() { } /** - * @return The tags associated with the trace. Can be an array of strings or null. + * @return The tags associated with the trace. */ @JsonProperty("tags") @java.lang.Override - public Optional> getTags() { + public List getTags() { return tags; } @@ -200,7 +218,7 @@ public Optional> getTags() { */ @JsonProperty("public") @java.lang.Override - public Optional getPublic() { + public boolean getPublic() { return public_; } @@ -209,7 +227,7 @@ public Optional getPublic() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -224,16 +242,22 @@ public String getHtmlPath() { /** * @return Latency of trace in seconds */ - @JsonProperty("latency") - public double getLatency() { + @JsonIgnore + public Optional getLatency() { + if (latency == null) { + return Optional.empty(); + } return latency; } /** * @return Cost of trace in USD */ - @JsonProperty("totalCost") - public double getTotalCost() { + @JsonIgnore + public Optional getTotalCost() { + if (totalCost == null) { + return Optional.empty(); + } return totalCost; } @@ -253,6 +277,69 @@ public List getScores() { return scores; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("name") + private Optional _getName() { + return name; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("release") + private Optional _getRelease() { + return release; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("version") + private Optional _getVersion() { + return version; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("userId") + private Optional _getUserId() { + return userId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("latency") + private Optional _getLatency() { + return latency; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("totalCost") + private Optional _getTotalCost() { + return totalCost; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -265,7 +352,7 @@ public Map getAdditionalProperties() { } private boolean equalTo(TraceWithFullDetails other) { - return id.equals(other.id) && timestamp.equals(other.timestamp) && name.equals(other.name) && input.equals(other.input) && output.equals(other.output) && sessionId.equals(other.sessionId) && release.equals(other.release) && version.equals(other.version) && userId.equals(other.userId) && metadata.equals(other.metadata) && tags.equals(other.tags) && public_.equals(other.public_) && environment.equals(other.environment) && htmlPath.equals(other.htmlPath) && latency == other.latency && totalCost == other.totalCost && observations.equals(other.observations) && scores.equals(other.scores); + return id.equals(other.id) && timestamp.equals(other.timestamp) && name.equals(other.name) && input.equals(other.input) && output.equals(other.output) && sessionId.equals(other.sessionId) && release.equals(other.release) && version.equals(other.version) && userId.equals(other.userId) && metadata.equals(other.metadata) && tags.equals(other.tags) && public_ == other.public_ && environment.equals(other.environment) && htmlPath.equals(other.htmlPath) && latency.equals(other.latency) && totalCost.equals(other.totalCost) && observations.equals(other.observations) && scores.equals(other.scores); } @java.lang.Override @@ -283,80 +370,154 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        The unique identifier of a trace

        + */ TimestampStage id(@NotNull String id); Builder from(TraceWithFullDetails other); } public interface TimestampStage { - HtmlPathStage timestamp(@NotNull OffsetDateTime timestamp); + /** + *

        The timestamp when the trace was created

        + */ + PublicStage timestamp(@NotNull OffsetDateTime timestamp); } - public interface HtmlPathStage { - LatencyStage htmlPath(@NotNull String htmlPath); + public interface PublicStage { + /** + *

        Public traces are accessible via url without login

        + */ + EnvironmentStage public_(boolean public_); } - public interface LatencyStage { - TotalCostStage latency(double latency); + public interface EnvironmentStage { + /** + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ + HtmlPathStage environment(@NotNull String environment); } - public interface TotalCostStage { - _FinalStage totalCost(double totalCost); + public interface HtmlPathStage { + /** + *

        Path of trace in Langfuse UI

        + */ + _FinalStage htmlPath(@NotNull String htmlPath); } public interface _FinalStage { TraceWithFullDetails build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The name of the trace

        + */ _FinalStage name(Optional name); _FinalStage name(String name); + _FinalStage name(Nullable name); + + /** + *

        The input data of the trace. Can be any JSON.

        + */ _FinalStage input(Optional input); _FinalStage input(Object input); + /** + *

        The output data of the trace. Can be any JSON.

        + */ _FinalStage output(Optional output); _FinalStage output(Object output); + /** + *

        The session identifier associated with the trace

        + */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

        The release version of the application when the trace was created

        + */ _FinalStage release(Optional release); _FinalStage release(String release); + _FinalStage release(Nullable release); + + /** + *

        The version of the trace

        + */ _FinalStage version(Optional version); _FinalStage version(String version); + _FinalStage version(Nullable version); + + /** + *

        The user identifier associated with the trace

        + */ _FinalStage userId(Optional userId); _FinalStage userId(String userId); + _FinalStage userId(Nullable userId); + + /** + *

        The metadata associated with the trace. Can be any JSON.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); - _FinalStage tags(Optional> tags); - + /** + *

        The tags associated with the trace.

        + */ _FinalStage tags(List tags); - _FinalStage public_(Optional public_); + _FinalStage addTags(String tags); + + _FinalStage addAllTags(List tags); + + /** + *

        Latency of trace in seconds

        + */ + _FinalStage latency(Optional latency); + + _FinalStage latency(Double latency); - _FinalStage public_(Boolean public_); + _FinalStage latency(Nullable latency); + + /** + *

        Cost of trace in USD

        + */ + _FinalStage totalCost(Optional totalCost); - _FinalStage environment(Optional environment); + _FinalStage totalCost(Double totalCost); - _FinalStage environment(String environment); + _FinalStage totalCost(Nullable totalCost); + /** + *

        List of observations

        + */ _FinalStage observations(List observations); _FinalStage addObservations(ObservationsView observations); _FinalStage addAllObservations(List observations); + /** + *

        List of scores

        + */ _FinalStage scores(List scores); _FinalStage addScores(ScoreV1 scores); @@ -367,26 +528,26 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements IdStage, TimestampStage, HtmlPathStage, LatencyStage, TotalCostStage, _FinalStage { + public static final class Builder implements IdStage, TimestampStage, PublicStage, EnvironmentStage, HtmlPathStage, _FinalStage { private String id; private OffsetDateTime timestamp; - private String htmlPath; + private boolean public_; - private double latency; + private String environment; - private double totalCost; + private String htmlPath; private List scores = new ArrayList<>(); private List observations = new ArrayList<>(); - private Optional environment = Optional.empty(); + private Optional totalCost = Optional.empty(); - private Optional public_ = Optional.empty(); + private Optional latency = Optional.empty(); - private Optional> tags = Optional.empty(); + private List tags = new ArrayList<>(); private Optional metadata = Optional.empty(); @@ -434,6 +595,7 @@ public Builder from(TraceWithFullDetails other) { } /** + *

        The unique identifier of a trace

        *

        The unique identifier of a trace

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -445,46 +607,50 @@ public TimestampStage id(@NotNull String id) { } /** + *

        The timestamp when the trace was created

        *

        The timestamp when the trace was created

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @JsonSetter("timestamp") - public HtmlPathStage timestamp(@NotNull OffsetDateTime timestamp) { + public PublicStage timestamp(@NotNull OffsetDateTime timestamp) { this.timestamp = Objects.requireNonNull(timestamp, "timestamp must not be null"); return this; } /** - *

        Path of trace in Langfuse UI

        + *

        Public traces are accessible via url without login

        + *

        Public traces are accessible via url without login

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("htmlPath") - public LatencyStage htmlPath(@NotNull String htmlPath) { - this.htmlPath = Objects.requireNonNull(htmlPath, "htmlPath must not be null"); + @JsonSetter("public") + public EnvironmentStage public_(boolean public_) { + this.public_ = public_; return this; } /** - *

        Latency of trace in seconds

        + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("latency") - public TotalCostStage latency(double latency) { - this.latency = latency; + @JsonSetter("environment") + public HtmlPathStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); return this; } /** - *

        Cost of trace in USD

        + *

        Path of trace in Langfuse UI

        + *

        Path of trace in Langfuse UI

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("totalCost") - public _FinalStage totalCost(double totalCost) { - this.totalCost = totalCost; + @JsonSetter("htmlPath") + public _FinalStage htmlPath(@NotNull String htmlPath) { + this.htmlPath = Objects.requireNonNull(htmlPath, "htmlPath must not be null"); return this; } @@ -494,7 +660,9 @@ public _FinalStage totalCost(double totalCost) { */ @java.lang.Override public _FinalStage addAllScores(List scores) { - this.scores.addAll(scores); + if (scores != null) { + this.scores.addAll(scores); + } return this; } @@ -508,6 +676,9 @@ public _FinalStage addScores(ScoreV1 scores) { return this; } + /** + *

        List of scores

        + */ @java.lang.Override @JsonSetter( value = "scores", @@ -515,7 +686,9 @@ public _FinalStage addScores(ScoreV1 scores) { ) public _FinalStage scores(List scores) { this.scores.clear(); - this.scores.addAll(scores); + if (scores != null) { + this.scores.addAll(scores); + } return this; } @@ -525,7 +698,9 @@ public _FinalStage scores(List scores) { */ @java.lang.Override public _FinalStage addAllObservations(List observations) { - this.observations.addAll(observations); + if (observations != null) { + this.observations.addAll(observations); + } return this; } @@ -539,6 +714,9 @@ public _FinalStage addObservations(ObservationsView observations) { return this; } + /** + *

        List of observations

        + */ @java.lang.Override @JsonSetter( value = "observations", @@ -546,67 +724,129 @@ public _FinalStage addObservations(ObservationsView observations) { ) public _FinalStage observations(List observations) { this.observations.clear(); - this.observations.addAll(observations); + if (observations != null) { + this.observations.addAll(observations); + } return this; } /** - *

        The environment from which this trace originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        Cost of trace in USD

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage totalCost(Nullable totalCost) { + if (totalCost.isNull()) { + this.totalCost = null; + } + else if (totalCost.isEmpty()) { + this.totalCost = Optional.empty(); + } + else { + this.totalCost = Optional.of(totalCost.get()); + } + return this; + } + + /** + *

        Cost of trace in USD

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); + public _FinalStage totalCost(Double totalCost) { + this.totalCost = Optional.ofNullable(totalCost); return this; } + /** + *

        Cost of trace in USD

        + */ @java.lang.Override @JsonSetter( - value = "environment", + value = "totalCost", nulls = Nulls.SKIP ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage totalCost(Optional totalCost) { + this.totalCost = totalCost; return this; } /** - *

        Public traces are accessible via url without login

        + *

        Latency of trace in seconds

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage latency(Nullable latency) { + if (latency.isNull()) { + this.latency = null; + } + else if (latency.isEmpty()) { + this.latency = Optional.empty(); + } + else { + this.latency = Optional.of(latency.get()); + } + return this; + } + + /** + *

        Latency of trace in seconds

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage public_(Boolean public_) { - this.public_ = Optional.ofNullable(public_); + public _FinalStage latency(Double latency) { + this.latency = Optional.ofNullable(latency); return this; } + /** + *

        Latency of trace in seconds

        + */ @java.lang.Override @JsonSetter( - value = "public", + value = "latency", nulls = Nulls.SKIP ) - public _FinalStage public_(Optional public_) { - this.public_ = public_; + public _FinalStage latency(Optional latency) { + this.latency = latency; return this; } /** - *

        The tags associated with the trace. Can be an array of strings or null.

        + *

        The tags associated with the trace.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage tags(List tags) { - this.tags = Optional.ofNullable(tags); + public _FinalStage addAllTags(List tags) { + if (tags != null) { + this.tags.addAll(tags); + } + return this; + } + + /** + *

        The tags associated with the trace.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addTags(String tags) { + this.tags.add(tags); return this; } + /** + *

        The tags associated with the trace.

        + */ @java.lang.Override @JsonSetter( value = "tags", nulls = Nulls.SKIP ) - public _FinalStage tags(Optional> tags) { - this.tags = tags; + public _FinalStage tags(List tags) { + this.tags.clear(); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -620,6 +860,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        The metadata associated with the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -630,6 +873,24 @@ public _FinalStage metadata(Optional metadata) { return this; } + /** + *

        The user identifier associated with the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage userId(Nullable userId) { + if (userId.isNull()) { + this.userId = null; + } + else if (userId.isEmpty()) { + this.userId = Optional.empty(); + } + else { + this.userId = Optional.of(userId.get()); + } + return this; + } + /** *

        The user identifier associated with the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -640,6 +901,9 @@ public _FinalStage userId(String userId) { return this; } + /** + *

        The user identifier associated with the trace

        + */ @java.lang.Override @JsonSetter( value = "userId", @@ -650,6 +914,24 @@ public _FinalStage userId(Optional userId) { return this; } + /** + *

        The version of the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage version(Nullable version) { + if (version.isNull()) { + this.version = null; + } + else if (version.isEmpty()) { + this.version = Optional.empty(); + } + else { + this.version = Optional.of(version.get()); + } + return this; + } + /** *

        The version of the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -660,6 +942,9 @@ public _FinalStage version(String version) { return this; } + /** + *

        The version of the trace

        + */ @java.lang.Override @JsonSetter( value = "version", @@ -670,6 +955,24 @@ public _FinalStage version(Optional version) { return this; } + /** + *

        The release version of the application when the trace was created

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage release(Nullable release) { + if (release.isNull()) { + this.release = null; + } + else if (release.isEmpty()) { + this.release = Optional.empty(); + } + else { + this.release = Optional.of(release.get()); + } + return this; + } + /** *

        The release version of the application when the trace was created

        * @return Reference to {@code this} so that method calls can be chained together. @@ -680,6 +983,9 @@ public _FinalStage release(String release) { return this; } + /** + *

        The release version of the application when the trace was created

        + */ @java.lang.Override @JsonSetter( value = "release", @@ -690,6 +996,24 @@ public _FinalStage release(Optional release) { return this; } + /** + *

        The session identifier associated with the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + /** *

        The session identifier associated with the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -700,6 +1024,9 @@ public _FinalStage sessionId(String sessionId) { return this; } + /** + *

        The session identifier associated with the trace

        + */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -720,6 +1047,9 @@ public _FinalStage output(Object output) { return this; } + /** + *

        The output data of the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "output", @@ -740,6 +1070,9 @@ public _FinalStage input(Object input) { return this; } + /** + *

        The input data of the trace. Can be any JSON.

        + */ @java.lang.Override @JsonSetter( value = "input", @@ -750,6 +1083,24 @@ public _FinalStage input(Optional input) { return this; } + /** + *

        The name of the trace

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage name(Nullable name) { + if (name.isNull()) { + this.name = null; + } + else if (name.isEmpty()) { + this.name = Optional.empty(); + } + else { + this.name = Optional.of(name.get()); + } + return this; + } + /** *

        The name of the trace

        * @return Reference to {@code this} so that method calls can be chained together. @@ -760,6 +1111,9 @@ public _FinalStage name(String name) { return this; } + /** + *

        The name of the trace

        + */ @java.lang.Override @JsonSetter( value = "name", @@ -774,5 +1128,17 @@ public _FinalStage name(Optional name) { public TraceWithFullDetails build() { return new TraceWithFullDetails(id, timestamp, name, input, output, sessionId, release, version, userId, metadata, tags, public_, environment, htmlPath, latency, totalCost, observations, scores, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/commons/types/Usage.java b/src/main/java/com/langfuse/client/resources/commons/types/Usage.java index c57d21a..6194828 100644 --- a/src/main/java/com/langfuse/client/resources/commons/types/Usage.java +++ b/src/main/java/com/langfuse/client/resources/commons/types/Usage.java @@ -6,15 +6,17 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Double; -import java.lang.Integer; import java.lang.Object; import java.lang.String; import java.util.HashMap; @@ -27,13 +29,13 @@ builder = Usage.Builder.class ) public final class Usage { - private final Optional input; + private final int input; - private final Optional output; + private final int output; - private final Optional total; + private final int total; - private final Optional unit; + private final Optional unit; private final Optional inputCost; @@ -43,9 +45,9 @@ public final class Usage { private final Map additionalProperties; - private Usage(Optional input, Optional output, Optional total, - Optional unit, Optional inputCost, Optional outputCost, - Optional totalCost, Map additionalProperties) { + private Usage(int input, int output, int total, Optional unit, Optional inputCost, + Optional outputCost, Optional totalCost, + Map additionalProperties) { this.input = input; this.output = output; this.total = total; @@ -60,7 +62,7 @@ private Usage(Optional input, Optional output, Optional getInput() { + public int getInput() { return input; } @@ -68,7 +70,7 @@ public Optional getInput() { * @return Number of output units (e.g. tokens) */ @JsonProperty("output") - public Optional getOutput() { + public int getOutput() { return output; } @@ -76,12 +78,18 @@ public Optional getOutput() { * @return Defaults to input+output if not set */ @JsonProperty("total") - public Optional getTotal() { + public int getTotal() { return total; } - @JsonProperty("unit") - public Optional getUnit() { + /** + * @return Unit of measurement + */ + @JsonIgnore + public Optional getUnit() { + if (unit == null) { + return Optional.empty(); + } return unit; } @@ -109,6 +117,15 @@ public Optional getTotalCost() { return totalCost; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("unit") + private Optional _getUnit() { + return unit; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -121,7 +138,7 @@ public Map getAdditionalProperties() { } private boolean equalTo(Usage other) { - return input.equals(other.input) && output.equals(other.output) && total.equals(other.total) && unit.equals(other.unit) && inputCost.equals(other.inputCost) && outputCost.equals(other.outputCost) && totalCost.equals(other.totalCost); + return input == other.input && output == other.output && total == other.total && unit.equals(other.unit) && inputCost.equals(other.inputCost) && outputCost.equals(other.outputCost) && totalCost.equals(other.totalCost); } @java.lang.Override @@ -134,27 +151,88 @@ public String toString() { return ObjectMappers.stringify(this); } - public static Builder builder() { + public static InputStage builder() { return new Builder(); } + public interface InputStage { + /** + *

        Number of input units (e.g. tokens)

        + */ + OutputStage input(int input); + + Builder from(Usage other); + } + + public interface OutputStage { + /** + *

        Number of output units (e.g. tokens)

        + */ + TotalStage output(int output); + } + + public interface TotalStage { + /** + *

        Defaults to input+output if not set

        + */ + _FinalStage total(int total); + } + + public interface _FinalStage { + Usage build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Unit of measurement

        + */ + _FinalStage unit(Optional unit); + + _FinalStage unit(String unit); + + _FinalStage unit(Nullable unit); + + /** + *

        USD input cost

        + */ + _FinalStage inputCost(Optional inputCost); + + _FinalStage inputCost(Double inputCost); + + /** + *

        USD output cost

        + */ + _FinalStage outputCost(Optional outputCost); + + _FinalStage outputCost(Double outputCost); + + /** + *

        USD total cost, defaults to input+output

        + */ + _FinalStage totalCost(Optional totalCost); + + _FinalStage totalCost(Double totalCost); + } + @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder { - private Optional input = Optional.empty(); - - private Optional output = Optional.empty(); + public static final class Builder implements InputStage, OutputStage, TotalStage, _FinalStage { + private int input; - private Optional total = Optional.empty(); + private int output; - private Optional unit = Optional.empty(); + private int total; - private Optional inputCost = Optional.empty(); + private Optional totalCost = Optional.empty(); private Optional outputCost = Optional.empty(); - private Optional totalCost = Optional.empty(); + private Optional inputCost = Optional.empty(); + + private Optional unit = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -162,6 +240,7 @@ public static final class Builder { private Builder() { } + @java.lang.Override public Builder from(Usage other) { input(other.getInput()); output(other.getOutput()); @@ -173,106 +252,167 @@ public Builder from(Usage other) { return this; } - @JsonSetter( - value = "input", - nulls = Nulls.SKIP - ) - public Builder input(Optional input) { + /** + *

        Number of input units (e.g. tokens)

        + *

        Number of input units (e.g. tokens)

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("input") + public OutputStage input(int input) { this.input = input; return this; } - public Builder input(Integer input) { - this.input = Optional.ofNullable(input); + /** + *

        Number of output units (e.g. tokens)

        + *

        Number of output units (e.g. tokens)

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("output") + public TotalStage output(int output) { + this.output = output; return this; } - @JsonSetter( - value = "output", - nulls = Nulls.SKIP - ) - public Builder output(Optional output) { - this.output = output; + /** + *

        Defaults to input+output if not set

        + *

        Defaults to input+output if not set

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("total") + public _FinalStage total(int total) { + this.total = total; return this; } - public Builder output(Integer output) { - this.output = Optional.ofNullable(output); + /** + *

        USD total cost, defaults to input+output

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage totalCost(Double totalCost) { + this.totalCost = Optional.ofNullable(totalCost); return this; } + /** + *

        USD total cost, defaults to input+output

        + */ + @java.lang.Override @JsonSetter( - value = "total", + value = "totalCost", nulls = Nulls.SKIP ) - public Builder total(Optional total) { - this.total = total; + public _FinalStage totalCost(Optional totalCost) { + this.totalCost = totalCost; return this; } - public Builder total(Integer total) { - this.total = Optional.ofNullable(total); + /** + *

        USD output cost

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputCost(Double outputCost) { + this.outputCost = Optional.ofNullable(outputCost); return this; } + /** + *

        USD output cost

        + */ + @java.lang.Override @JsonSetter( - value = "unit", + value = "outputCost", nulls = Nulls.SKIP ) - public Builder unit(Optional unit) { - this.unit = unit; + public _FinalStage outputCost(Optional outputCost) { + this.outputCost = outputCost; return this; } - public Builder unit(ModelUsageUnit unit) { - this.unit = Optional.ofNullable(unit); + /** + *

        USD input cost

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage inputCost(Double inputCost) { + this.inputCost = Optional.ofNullable(inputCost); return this; } + /** + *

        USD input cost

        + */ + @java.lang.Override @JsonSetter( value = "inputCost", nulls = Nulls.SKIP ) - public Builder inputCost(Optional inputCost) { + public _FinalStage inputCost(Optional inputCost) { this.inputCost = inputCost; return this; } - public Builder inputCost(Double inputCost) { - this.inputCost = Optional.ofNullable(inputCost); + /** + *

        Unit of measurement

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage unit(Nullable unit) { + if (unit.isNull()) { + this.unit = null; + } + else if (unit.isEmpty()) { + this.unit = Optional.empty(); + } + else { + this.unit = Optional.of(unit.get()); + } return this; } - @JsonSetter( - value = "outputCost", - nulls = Nulls.SKIP - ) - public Builder outputCost(Optional outputCost) { - this.outputCost = outputCost; - return this; - } - - public Builder outputCost(Double outputCost) { - this.outputCost = Optional.ofNullable(outputCost); + /** + *

        Unit of measurement

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage unit(String unit) { + this.unit = Optional.ofNullable(unit); return this; } + /** + *

        Unit of measurement

        + */ + @java.lang.Override @JsonSetter( - value = "totalCost", + value = "unit", nulls = Nulls.SKIP ) - public Builder totalCost(Optional totalCost) { - this.totalCost = totalCost; + public _FinalStage unit(Optional unit) { + this.unit = unit; return this; } - public Builder totalCost(Double totalCost) { - this.totalCost = Optional.ofNullable(totalCost); + @java.lang.Override + public Usage build() { + return new Usage(input, output, total, unit, inputCost, outputCost, totalCost, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); return this; } - public Usage build() { - return new Usage(input, output, total, unit, inputCost, outputCost, totalCost, additionalProperties); + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/AsyncDatasetItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetitems/AsyncDatasetItemsClient.java new file mode 100644 index 0000000..6c79f98 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasetitems/AsyncDatasetItemsClient.java @@ -0,0 +1,110 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasetitems; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.DatasetItem; +import com.langfuse.client.resources.datasetitems.requests.GetDatasetItemsRequest; +import com.langfuse.client.resources.datasetitems.types.CreateDatasetItemRequest; +import com.langfuse.client.resources.datasetitems.types.DeleteDatasetItemResponse; +import com.langfuse.client.resources.datasetitems.types.PaginatedDatasetItems; + +public class AsyncDatasetItemsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawDatasetItemsClient rawClient; + + public AsyncDatasetItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawDatasetItemsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawDatasetItemsClient withRawResponse() { + return this.rawClient; + } + + /** + * Create a dataset item + */ + public CompletableFuture create(CreateDatasetItemRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a dataset item + */ + public CompletableFuture create(CreateDatasetItemRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a dataset item + */ + public CompletableFuture get(String id) { + return this.rawClient.get(id).thenApply(response -> response.body()); + } + + /** + * Get a dataset item + */ + public CompletableFuture get(String id, RequestOptions requestOptions) { + return this.rawClient.get(id, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture list(GetDatasetItemsRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture list(GetDatasetItemsRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public CompletableFuture delete(String id) { + return this.rawClient.delete(id).thenApply(response -> response.body()); + } + + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public CompletableFuture delete(String id, + RequestOptions requestOptions) { + return this.rawClient.delete(id, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/AsyncRawDatasetItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetitems/AsyncRawDatasetItemsClient.java new file mode 100644 index 0000000..9a80853 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasetitems/AsyncRawDatasetItemsClient.java @@ -0,0 +1,390 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasetitems; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.DatasetItem; +import com.langfuse.client.resources.datasetitems.requests.GetDatasetItemsRequest; +import com.langfuse.client.resources.datasetitems.types.CreateDatasetItemRequest; +import com.langfuse.client.resources.datasetitems.types.DeleteDatasetItemResponse; +import com.langfuse.client.resources.datasetitems.types.PaginatedDatasetItems; + +public class AsyncRawDatasetItemsClient { + protected final ClientOptions clientOptions; + + public AsyncRawDatasetItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a dataset item + */ + public CompletableFuture> create( + CreateDatasetItemRequest request) { + return create(request,null); + } + + /** + * Create a dataset item + */ + public CompletableFuture> create( + CreateDatasetItemRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetItem.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a dataset item + */ + public CompletableFuture> get(String id) { + return get(id,null); + } + + /** + * Get a dataset item + */ + public CompletableFuture> get(String id, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetItem.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture> list() { + return list(GetDatasetItemsRequest.builder().build()); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture> list( + RequestOptions requestOptions) { + return list(GetDatasetItemsRequest.builder().build(),requestOptions); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture> list( + GetDatasetItemsRequest request) { + return list(request,null); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public CompletableFuture> list( + GetDatasetItemsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items");if (request.getDatasetName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "datasetName", request.getDatasetName().get(), false); + } + if (request.getSourceTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sourceTraceId", request.getSourceTraceId().get(), false); + } + if (request.getSourceObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sourceObservationId", request.getSourceObservationId().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasetItems.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public CompletableFuture> delete( + String id) { + return delete(id,null); + } + + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public CompletableFuture> delete( + String id, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteDatasetItemResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/DatasetItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetitems/DatasetItemsClient.java index 47b4e88..5c4da09 100644 --- a/src/main/java/com/langfuse/client/resources/datasetitems/DatasetItemsClient.java +++ b/src/main/java/com/langfuse/client/resources/datasetitems/DatasetItemsClient.java @@ -4,29 +4,9 @@ package com.langfuse.client.resources.datasetitems; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.DatasetItem; import com.langfuse.client.resources.datasetitems.requests.GetDatasetItemsRequest; import com.langfuse.client.resources.datasetitems.types.CreateDatasetItemRequest; @@ -36,240 +16,91 @@ public class DatasetItemsClient { protected final ClientOptions clientOptions; + private final RawDatasetItemsClient rawClient; + public DatasetItemsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawDatasetItemsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawDatasetItemsClient withRawResponse() { + return this.rawClient; } /** * Create a dataset item */ public DatasetItem create(CreateDatasetItemRequest request) { - return create(request,null); + return this.rawClient.create(request).body(); } /** * Create a dataset item */ public DatasetItem create(CreateDatasetItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("dataset-items") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * Get a dataset item */ public DatasetItem get(String id) { - return get(id,null); + return this.rawClient.get(id).body(); } /** * Get a dataset item */ public DatasetItem get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("dataset-items") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.get(id, requestOptions).body(); } /** - * Get dataset items + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. */ public PaginatedDatasetItems list() { - return list(GetDatasetItemsRequest.builder().build()); + return this.rawClient.list().body(); } /** - * Get dataset items + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public PaginatedDatasetItems list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).body(); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. */ public PaginatedDatasetItems list(GetDatasetItemsRequest request) { - return list(request,null); + return this.rawClient.list(request).body(); } /** - * Get dataset items + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. */ public PaginatedDatasetItems list(GetDatasetItemsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("dataset-items");if (request.getDatasetName().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "datasetName", request.getDatasetName().get(), false); - } - if (request.getSourceTraceId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "sourceTraceId", request.getSourceTraceId().get(), false); - } - if (request.getSourceObservationId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "sourceObservationId", request.getSourceObservationId().get(), false); - } - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedDatasetItems.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.list(request, requestOptions).body(); + } - /** - * Delete a dataset item and all its run items. This action is irreversible. - */ - public DeleteDatasetItemResponse delete(String id) { - return delete(id,null); - } + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public DeleteDatasetItemResponse delete(String id) { + return this.rawClient.delete(id).body(); + } - /** - * Delete a dataset item and all its run items. This action is irreversible. - */ - public DeleteDatasetItemResponse delete(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("dataset-items") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeleteDatasetItemResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public DeleteDatasetItemResponse delete(String id, RequestOptions requestOptions) { + return this.rawClient.delete(id, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/RawDatasetItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetitems/RawDatasetItemsClient.java new file mode 100644 index 0000000..af9bcad --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasetitems/RawDatasetItemsClient.java @@ -0,0 +1,309 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasetitems; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.DatasetItem; +import com.langfuse.client.resources.datasetitems.requests.GetDatasetItemsRequest; +import com.langfuse.client.resources.datasetitems.types.CreateDatasetItemRequest; +import com.langfuse.client.resources.datasetitems.types.DeleteDatasetItemResponse; +import com.langfuse.client.resources.datasetitems.types.PaginatedDatasetItems; + +public class RawDatasetItemsClient { + protected final ClientOptions clientOptions; + + public RawDatasetItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a dataset item + */ + public LangfuseClientHttpResponse create(CreateDatasetItemRequest request) { + return create(request,null); + } + + /** + * Create a dataset item + */ + public LangfuseClientHttpResponse create(CreateDatasetItemRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetItem.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a dataset item + */ + public LangfuseClientHttpResponse get(String id) { + return get(id,null); + } + + /** + * Get a dataset item + */ + public LangfuseClientHttpResponse get(String id, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetItem.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public LangfuseClientHttpResponse list() { + return list(GetDatasetItemsRequest.builder().build()); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public LangfuseClientHttpResponse list(RequestOptions requestOptions) { + return list(GetDatasetItemsRequest.builder().build(),requestOptions); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public LangfuseClientHttpResponse list( + GetDatasetItemsRequest request) { + return list(request,null); + } + + /** + * Get dataset items. Optionally specify a version to get the items as they existed at that point in time. + * Note: If version parameter is provided, datasetName must also be provided. + */ + public LangfuseClientHttpResponse list(GetDatasetItemsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items");if (request.getDatasetName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "datasetName", request.getDatasetName().get(), false); + } + if (request.getSourceTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sourceTraceId", request.getSourceTraceId().get(), false); + } + if (request.getSourceObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sourceObservationId", request.getSourceObservationId().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasetItems.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public LangfuseClientHttpResponse delete(String id) { + return delete(id,null); + } + + /** + * Delete a dataset item and all its run items. This action is irreversible. + */ + public LangfuseClientHttpResponse delete(String id, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-items") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteDatasetItemResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/requests/GetDatasetItemsRequest.java b/src/main/java/com/langfuse/client/resources/datasetitems/requests/GetDatasetItemsRequest.java index 5fe77a7..6b53a36 100644 --- a/src/main/java/com/langfuse/client/resources/datasetitems/requests/GetDatasetItemsRequest.java +++ b/src/main/java/com/langfuse/client/resources/datasetitems/requests/GetDatasetItemsRequest.java @@ -16,6 +16,7 @@ import java.lang.Integer; import java.lang.Object; import java.lang.String; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -32,6 +33,8 @@ public final class GetDatasetItemsRequest { private final Optional sourceObservationId; + private final Optional version; + private final Optional page; private final Optional limit; @@ -39,11 +42,12 @@ public final class GetDatasetItemsRequest { private final Map additionalProperties; private GetDatasetItemsRequest(Optional datasetName, Optional sourceTraceId, - Optional sourceObservationId, Optional page, Optional limit, - Map additionalProperties) { + Optional sourceObservationId, Optional version, + Optional page, Optional limit, Map additionalProperties) { this.datasetName = datasetName; this.sourceTraceId = sourceTraceId; this.sourceObservationId = sourceObservationId; + this.version = version; this.page = page; this.limit = limit; this.additionalProperties = additionalProperties; @@ -64,6 +68,16 @@ public Optional getSourceObservationId() { return sourceObservationId; } + /** + * @return ISO 8601 timestamp (RFC 3339, Section 5.6) in UTC (e.g., "2026-01-21T14:35:42Z"). + * If provided, returns state of dataset at this timestamp. + * If not provided, returns the latest version. Requires datasetName to be specified. + */ + @JsonProperty("version") + public Optional getVersion() { + return version; + } + /** * @return page number, starts at 1 */ @@ -92,12 +106,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(GetDatasetItemsRequest other) { - return datasetName.equals(other.datasetName) && sourceTraceId.equals(other.sourceTraceId) && sourceObservationId.equals(other.sourceObservationId) && page.equals(other.page) && limit.equals(other.limit); + return datasetName.equals(other.datasetName) && sourceTraceId.equals(other.sourceTraceId) && sourceObservationId.equals(other.sourceObservationId) && version.equals(other.version) && page.equals(other.page) && limit.equals(other.limit); } @java.lang.Override public int hashCode() { - return Objects.hash(this.datasetName, this.sourceTraceId, this.sourceObservationId, this.page, this.limit); + return Objects.hash(this.datasetName, this.sourceTraceId, this.sourceObservationId, this.version, this.page, this.limit); } @java.lang.Override @@ -119,6 +133,8 @@ public static final class Builder { private Optional sourceObservationId = Optional.empty(); + private Optional version = Optional.empty(); + private Optional page = Optional.empty(); private Optional limit = Optional.empty(); @@ -133,6 +149,7 @@ public Builder from(GetDatasetItemsRequest other) { datasetName(other.getDatasetName()); sourceTraceId(other.getSourceTraceId()); sourceObservationId(other.getSourceObservationId()); + version(other.getVersion()); page(other.getPage()); limit(other.getLimit()); return this; @@ -180,6 +197,28 @@ public Builder sourceObservationId(String sourceObservationId) { return this; } + /** + *

        ISO 8601 timestamp (RFC 3339, Section 5.6) in UTC (e.g., "2026-01-21T14:35:42Z"). + * If provided, returns state of dataset at this timestamp. + * If not provided, returns the latest version. Requires datasetName to be specified.

        + */ + @JsonSetter( + value = "version", + nulls = Nulls.SKIP + ) + public Builder version(Optional version) { + this.version = version; + return this; + } + + public Builder version(OffsetDateTime version) { + this.version = Optional.ofNullable(version); + return this; + } + + /** + *

        page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -194,6 +233,9 @@ public Builder page(Integer page) { return this; } + /** + *

        limit of items per page

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -209,7 +251,17 @@ public Builder limit(Integer limit) { } public GetDatasetItemsRequest build() { - return new GetDatasetItemsRequest(datasetName, sourceTraceId, sourceObservationId, page, limit, additionalProperties); + return new GetDatasetItemsRequest(datasetName, sourceTraceId, sourceObservationId, version, page, limit, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/types/CreateDatasetItemRequest.java b/src/main/java/com/langfuse/client/resources/datasetitems/types/CreateDatasetItemRequest.java index aecf1bf..b49cadc 100644 --- a/src/main/java/com/langfuse/client/resources/datasetitems/types/CreateDatasetItemRequest.java +++ b/src/main/java/com/langfuse/client/resources/datasetitems/types/CreateDatasetItemRequest.java @@ -144,6 +144,10 @@ public interface DatasetNameStage { public interface _FinalStage { CreateDatasetItemRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage input(Optional input); _FinalStage input(Object input); @@ -164,10 +168,16 @@ public interface _FinalStage { _FinalStage sourceObservationId(String sourceObservationId); + /** + *

        Dataset items are upserted on their id. Id needs to be unique (project-level) and cannot be reused across datasets.

        + */ _FinalStage id(Optional id); _FinalStage id(String id); + /** + *

        Defaults to ACTIVE for newly created items

        + */ _FinalStage status(Optional status); _FinalStage status(DatasetStatus status); @@ -229,6 +239,9 @@ public _FinalStage status(DatasetStatus status) { return this; } + /** + *

        Defaults to ACTIVE for newly created items

        + */ @java.lang.Override @JsonSetter( value = "status", @@ -249,6 +262,9 @@ public _FinalStage id(String id) { return this; } + /** + *

        Dataset items are upserted on their id. Id needs to be unique (project-level) and cannot be reused across datasets.

        + */ @java.lang.Override @JsonSetter( value = "id", @@ -343,5 +359,17 @@ public _FinalStage input(Optional input) { public CreateDatasetItemRequest build() { return new CreateDatasetItemRequest(datasetName, input, expectedOutput, metadata, sourceTraceId, sourceObservationId, id, status, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/types/DeleteDatasetItemResponse.java b/src/main/java/com/langfuse/client/resources/datasetitems/types/DeleteDatasetItemResponse.java index 417a93d..ad0f79b 100644 --- a/src/main/java/com/langfuse/client/resources/datasetitems/types/DeleteDatasetItemResponse.java +++ b/src/main/java/com/langfuse/client/resources/datasetitems/types/DeleteDatasetItemResponse.java @@ -71,6 +71,9 @@ public static MessageStage builder() { } public interface MessageStage { + /** + *

        Success message after deletion

        + */ _FinalStage message(@NotNull String message); Builder from(DeleteDatasetItemResponse other); @@ -78,6 +81,10 @@ public interface MessageStage { public interface _FinalStage { DeleteDatasetItemResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -99,6 +106,7 @@ public Builder from(DeleteDatasetItemResponse other) { } /** + *

        Success message after deletion

        *

        Success message after deletion

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -113,5 +121,17 @@ public _FinalStage message(@NotNull String message) { public DeleteDatasetItemResponse build() { return new DeleteDatasetItemResponse(message, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasetitems/types/PaginatedDatasetItems.java b/src/main/java/com/langfuse/client/resources/datasetitems/types/PaginatedDatasetItems.java index 1d54117..925f6e6 100644 --- a/src/main/java/com/langfuse/client/resources/datasetitems/types/PaginatedDatasetItems.java +++ b/src/main/java/com/langfuse/client/resources/datasetitems/types/PaginatedDatasetItems.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedDatasetItems build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(DatasetItem data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(DatasetItem data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public PaginatedDatasetItems build() { return new PaginatedDatasetItems(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasetrunitems/AsyncDatasetRunItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetrunitems/AsyncDatasetRunItemsClient.java new file mode 100644 index 0000000..850de79 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasetrunitems/AsyncDatasetRunItemsClient.java @@ -0,0 +1,61 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasetrunitems; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.DatasetRunItem; +import com.langfuse.client.resources.datasetrunitems.requests.ListDatasetRunItemsRequest; +import com.langfuse.client.resources.datasetrunitems.types.CreateDatasetRunItemRequest; +import com.langfuse.client.resources.datasetrunitems.types.PaginatedDatasetRunItems; + +public class AsyncDatasetRunItemsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawDatasetRunItemsClient rawClient; + + public AsyncDatasetRunItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawDatasetRunItemsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawDatasetRunItemsClient withRawResponse() { + return this.rawClient; + } + + /** + * Create a dataset run item + */ + public CompletableFuture create(CreateDatasetRunItemRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a dataset run item + */ + public CompletableFuture create(CreateDatasetRunItemRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * List dataset run items + */ + public CompletableFuture list(ListDatasetRunItemsRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * List dataset run items + */ + public CompletableFuture list(ListDatasetRunItemsRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/datasetrunitems/AsyncRawDatasetRunItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetrunitems/AsyncRawDatasetRunItemsClient.java new file mode 100644 index 0000000..bd6b141 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasetrunitems/AsyncRawDatasetRunItemsClient.java @@ -0,0 +1,211 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasetrunitems; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.DatasetRunItem; +import com.langfuse.client.resources.datasetrunitems.requests.ListDatasetRunItemsRequest; +import com.langfuse.client.resources.datasetrunitems.types.CreateDatasetRunItemRequest; +import com.langfuse.client.resources.datasetrunitems.types.PaginatedDatasetRunItems; + +public class AsyncRawDatasetRunItemsClient { + protected final ClientOptions clientOptions; + + public AsyncRawDatasetRunItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a dataset run item + */ + public CompletableFuture> create( + CreateDatasetRunItemRequest request) { + return create(request,null); + } + + /** + * Create a dataset run item + */ + public CompletableFuture> create( + CreateDatasetRunItemRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-run-items");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetRunItem.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * List dataset run items + */ + public CompletableFuture> list( + ListDatasetRunItemsRequest request) { + return list(request,null); + } + + /** + * List dataset run items + */ + public CompletableFuture> list( + ListDatasetRunItemsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-run-items");QueryStringMapper.addQueryParameter(httpUrl, "datasetId", request.getDatasetId(), false); + QueryStringMapper.addQueryParameter(httpUrl, "runName", request.getRunName(), false); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasetRunItems.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/datasetrunitems/DatasetRunItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetrunitems/DatasetRunItemsClient.java index 175deaa..59f61f5 100644 --- a/src/main/java/com/langfuse/client/resources/datasetrunitems/DatasetRunItemsClient.java +++ b/src/main/java/com/langfuse/client/resources/datasetrunitems/DatasetRunItemsClient.java @@ -4,29 +4,8 @@ package com.langfuse.client.resources.datasetrunitems; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.DatasetRunItem; import com.langfuse.client.resources.datasetrunitems.requests.ListDatasetRunItemsRequest; import com.langfuse.client.resources.datasetrunitems.types.CreateDatasetRunItemRequest; @@ -35,73 +14,39 @@ public class DatasetRunItemsClient { protected final ClientOptions clientOptions; + private final RawDatasetRunItemsClient rawClient; + public DatasetRunItemsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawDatasetRunItemsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawDatasetRunItemsClient withRawResponse() { + return this.rawClient; } /** * Create a dataset run item */ public DatasetRunItem create(CreateDatasetRunItemRequest request) { - return create(request,null); + return this.rawClient.create(request).body(); } /** * Create a dataset run item */ public DatasetRunItem create(CreateDatasetRunItemRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("dataset-run-items") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetRunItem.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * List dataset run items */ public PaginatedDatasetRunItems list(ListDatasetRunItemsRequest request) { - return list(request,null); + return this.rawClient.list(request).body(); } /** @@ -109,49 +54,6 @@ public PaginatedDatasetRunItems list(ListDatasetRunItemsRequest request) { */ public PaginatedDatasetRunItems list(ListDatasetRunItemsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("dataset-run-items");QueryStringMapper.addQueryParameter(httpUrl, "datasetId", request.getDatasetId(), false); - QueryStringMapper.addQueryParameter(httpUrl, "runName", request.getRunName(), false); - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedDatasetRunItems.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.list(request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/datasetrunitems/RawDatasetRunItemsClient.java b/src/main/java/com/langfuse/client/resources/datasetrunitems/RawDatasetRunItemsClient.java new file mode 100644 index 0000000..f151e88 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasetrunitems/RawDatasetRunItemsClient.java @@ -0,0 +1,169 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasetrunitems; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.DatasetRunItem; +import com.langfuse.client.resources.datasetrunitems.requests.ListDatasetRunItemsRequest; +import com.langfuse.client.resources.datasetrunitems.types.CreateDatasetRunItemRequest; +import com.langfuse.client.resources.datasetrunitems.types.PaginatedDatasetRunItems; + +public class RawDatasetRunItemsClient { + protected final ClientOptions clientOptions; + + public RawDatasetRunItemsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a dataset run item + */ + public LangfuseClientHttpResponse create(CreateDatasetRunItemRequest request) { + return create(request,null); + } + + /** + * Create a dataset run item + */ + public LangfuseClientHttpResponse create(CreateDatasetRunItemRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-run-items");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetRunItem.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * List dataset run items + */ + public LangfuseClientHttpResponse list( + ListDatasetRunItemsRequest request) { + return list(request,null); + } + + /** + * List dataset run items + */ + public LangfuseClientHttpResponse list( + ListDatasetRunItemsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("dataset-run-items");QueryStringMapper.addQueryParameter(httpUrl, "datasetId", request.getDatasetId(), false); + QueryStringMapper.addQueryParameter(httpUrl, "runName", request.getRunName(), false); + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasetRunItems.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/datasetrunitems/requests/ListDatasetRunItemsRequest.java b/src/main/java/com/langfuse/client/resources/datasetrunitems/requests/ListDatasetRunItemsRequest.java index e784ca8..03190c7 100644 --- a/src/main/java/com/langfuse/client/resources/datasetrunitems/requests/ListDatasetRunItemsRequest.java +++ b/src/main/java/com/langfuse/client/resources/datasetrunitems/requests/ListDatasetRunItemsRequest.java @@ -114,10 +114,20 @@ public interface RunNameStage { public interface _FinalStage { ListDatasetRunItemsRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        page number, starts at 1

        + */ _FinalStage page(Optional page); _FinalStage page(Integer page); + /** + *

        limit of items per page

        + */ _FinalStage limit(Optional limit); _FinalStage limit(Integer limit); @@ -174,6 +184,9 @@ public _FinalStage limit(Integer limit) { return this; } + /** + *

        limit of items per page

        + */ @java.lang.Override @JsonSetter( value = "limit", @@ -194,6 +207,9 @@ public _FinalStage page(Integer page) { return this; } + /** + *

        page number, starts at 1

        + */ @java.lang.Override @JsonSetter( value = "page", @@ -208,5 +224,17 @@ public _FinalStage page(Optional page) { public ListDatasetRunItemsRequest build() { return new ListDatasetRunItemsRequest(datasetId, runName, page, limit, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasetrunitems/types/CreateDatasetRunItemRequest.java b/src/main/java/com/langfuse/client/resources/datasetrunitems/types/CreateDatasetRunItemRequest.java index 0b0da73..cdcc96a 100644 --- a/src/main/java/com/langfuse/client/resources/datasetrunitems/types/CreateDatasetRunItemRequest.java +++ b/src/main/java/com/langfuse/client/resources/datasetrunitems/types/CreateDatasetRunItemRequest.java @@ -15,6 +15,7 @@ import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -38,17 +39,21 @@ public final class CreateDatasetRunItemRequest { private final Optional traceId; + private final Optional datasetVersion; + private final Map additionalProperties; private CreateDatasetRunItemRequest(String runName, Optional runDescription, Optional metadata, String datasetItemId, Optional observationId, - Optional traceId, Map additionalProperties) { + Optional traceId, Optional datasetVersion, + Map additionalProperties) { this.runName = runName; this.runDescription = runDescription; this.metadata = metadata; this.datasetItemId = datasetItemId; this.observationId = observationId; this.traceId = traceId; + this.datasetVersion = datasetVersion; this.additionalProperties = additionalProperties; } @@ -91,6 +96,17 @@ public Optional getTraceId() { return traceId; } + /** + * @return ISO 8601 timestamp (RFC 3339, Section 5.6) in UTC (e.g., "2026-01-21T14:35:42Z"). + * Specifies the dataset version to use for this experiment run. + * If provided, the experiment will use dataset items as they existed at or before this timestamp. + * If not provided, uses the latest version of dataset items. + */ + @JsonProperty("datasetVersion") + public Optional getDatasetVersion() { + return datasetVersion; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -103,12 +119,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(CreateDatasetRunItemRequest other) { - return runName.equals(other.runName) && runDescription.equals(other.runDescription) && metadata.equals(other.metadata) && datasetItemId.equals(other.datasetItemId) && observationId.equals(other.observationId) && traceId.equals(other.traceId); + return runName.equals(other.runName) && runDescription.equals(other.runDescription) && metadata.equals(other.metadata) && datasetItemId.equals(other.datasetItemId) && observationId.equals(other.observationId) && traceId.equals(other.traceId) && datasetVersion.equals(other.datasetVersion); } @java.lang.Override public int hashCode() { - return Objects.hash(this.runName, this.runDescription, this.metadata, this.datasetItemId, this.observationId, this.traceId); + return Objects.hash(this.runName, this.runDescription, this.metadata, this.datasetItemId, this.observationId, this.traceId, this.datasetVersion); } @java.lang.Override @@ -133,10 +149,20 @@ public interface DatasetItemIdStage { public interface _FinalStage { CreateDatasetRunItemRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Description of the run. If run exists, description will be updated.

        + */ _FinalStage runDescription(Optional runDescription); _FinalStage runDescription(String runDescription); + /** + *

        Metadata of the dataset run, updates run if run already exists

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -145,9 +171,22 @@ public interface _FinalStage { _FinalStage observationId(String observationId); + /** + *

        traceId should always be provided. For compatibility with older SDK versions it can also be inferred from the provided observationId.

        + */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + + /** + *

        ISO 8601 timestamp (RFC 3339, Section 5.6) in UTC (e.g., "2026-01-21T14:35:42Z"). + * Specifies the dataset version to use for this experiment run. + * If provided, the experiment will use dataset items as they existed at or before this timestamp. + * If not provided, uses the latest version of dataset items.

        + */ + _FinalStage datasetVersion(Optional datasetVersion); + + _FinalStage datasetVersion(OffsetDateTime datasetVersion); } @JsonIgnoreProperties( @@ -158,6 +197,8 @@ public static final class Builder implements RunNameStage, DatasetItemIdStage, _ private String datasetItemId; + private Optional datasetVersion = Optional.empty(); + private Optional traceId = Optional.empty(); private Optional observationId = Optional.empty(); @@ -180,6 +221,7 @@ public Builder from(CreateDatasetRunItemRequest other) { datasetItemId(other.getDatasetItemId()); observationId(other.getObservationId()); traceId(other.getTraceId()); + datasetVersion(other.getDatasetVersion()); return this; } @@ -197,6 +239,35 @@ public _FinalStage datasetItemId(@NotNull String datasetItemId) { return this; } + /** + *

        ISO 8601 timestamp (RFC 3339, Section 5.6) in UTC (e.g., "2026-01-21T14:35:42Z"). + * Specifies the dataset version to use for this experiment run. + * If provided, the experiment will use dataset items as they existed at or before this timestamp. + * If not provided, uses the latest version of dataset items.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetVersion(OffsetDateTime datasetVersion) { + this.datasetVersion = Optional.ofNullable(datasetVersion); + return this; + } + + /** + *

        ISO 8601 timestamp (RFC 3339, Section 5.6) in UTC (e.g., "2026-01-21T14:35:42Z"). + * Specifies the dataset version to use for this experiment run. + * If provided, the experiment will use dataset items as they existed at or before this timestamp. + * If not provided, uses the latest version of dataset items.

        + */ + @java.lang.Override + @JsonSetter( + value = "datasetVersion", + nulls = Nulls.SKIP + ) + public _FinalStage datasetVersion(Optional datasetVersion) { + this.datasetVersion = datasetVersion; + return this; + } + /** *

        traceId should always be provided. For compatibility with older SDK versions it can also be inferred from the provided observationId.

        * @return Reference to {@code this} so that method calls can be chained together. @@ -207,6 +278,9 @@ public _FinalStage traceId(String traceId) { return this; } + /** + *

        traceId should always be provided. For compatibility with older SDK versions it can also be inferred from the provided observationId.

        + */ @java.lang.Override @JsonSetter( value = "traceId", @@ -243,6 +317,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Metadata of the dataset run, updates run if run already exists

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -263,6 +340,9 @@ public _FinalStage runDescription(String runDescription) { return this; } + /** + *

        Description of the run. If run exists, description will be updated.

        + */ @java.lang.Override @JsonSetter( value = "runDescription", @@ -275,7 +355,19 @@ public _FinalStage runDescription(Optional runDescription) { @java.lang.Override public CreateDatasetRunItemRequest build() { - return new CreateDatasetRunItemRequest(runName, runDescription, metadata, datasetItemId, observationId, traceId, additionalProperties); + return new CreateDatasetRunItemRequest(runName, runDescription, metadata, datasetItemId, observationId, traceId, datasetVersion, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/datasetrunitems/types/PaginatedDatasetRunItems.java b/src/main/java/com/langfuse/client/resources/datasetrunitems/types/PaginatedDatasetRunItems.java index fce1c56..af04426 100644 --- a/src/main/java/com/langfuse/client/resources/datasetrunitems/types/PaginatedDatasetRunItems.java +++ b/src/main/java/com/langfuse/client/resources/datasetrunitems/types/PaginatedDatasetRunItems.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedDatasetRunItems build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(DatasetRunItem data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(DatasetRunItem data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public PaginatedDatasetRunItems build() { return new PaginatedDatasetRunItems(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasets/AsyncDatasetsClient.java b/src/main/java/com/langfuse/client/resources/datasets/AsyncDatasetsClient.java new file mode 100644 index 0000000..906b549 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasets/AsyncDatasetsClient.java @@ -0,0 +1,155 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasets; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.Dataset; +import com.langfuse.client.resources.commons.types.DatasetRunWithItems; +import com.langfuse.client.resources.datasets.requests.GetDatasetRunsRequest; +import com.langfuse.client.resources.datasets.requests.GetDatasetsRequest; +import com.langfuse.client.resources.datasets.types.CreateDatasetRequest; +import com.langfuse.client.resources.datasets.types.DeleteDatasetRunResponse; +import com.langfuse.client.resources.datasets.types.PaginatedDatasetRuns; +import com.langfuse.client.resources.datasets.types.PaginatedDatasets; + +public class AsyncDatasetsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawDatasetsClient rawClient; + + public AsyncDatasetsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawDatasetsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawDatasetsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get all datasets + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * Get all datasets + */ + public CompletableFuture list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all datasets + */ + public CompletableFuture list(GetDatasetsRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * Get all datasets + */ + public CompletableFuture list(GetDatasetsRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a dataset + */ + public CompletableFuture get(String datasetName) { + return this.rawClient.get(datasetName).thenApply(response -> response.body()); + } + + /** + * Get a dataset + */ + public CompletableFuture get(String datasetName, RequestOptions requestOptions) { + return this.rawClient.get(datasetName, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create a dataset + */ + public CompletableFuture create(CreateDatasetRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a dataset + */ + public CompletableFuture create(CreateDatasetRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a dataset run and its items + */ + public CompletableFuture getRun(String datasetName, String runName) { + return this.rawClient.getRun(datasetName, runName).thenApply(response -> response.body()); + } + + /** + * Get a dataset run and its items + */ + public CompletableFuture getRun(String datasetName, String runName, + RequestOptions requestOptions) { + return this.rawClient.getRun(datasetName, runName, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public CompletableFuture deleteRun(String datasetName, String runName) { + return this.rawClient.deleteRun(datasetName, runName).thenApply(response -> response.body()); + } + + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public CompletableFuture deleteRun(String datasetName, String runName, + RequestOptions requestOptions) { + return this.rawClient.deleteRun(datasetName, runName, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get dataset runs + */ + public CompletableFuture getRuns(String datasetName) { + return this.rawClient.getRuns(datasetName).thenApply(response -> response.body()); + } + + /** + * Get dataset runs + */ + public CompletableFuture getRuns(String datasetName, + RequestOptions requestOptions) { + return this.rawClient.getRuns(datasetName, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get dataset runs + */ + public CompletableFuture getRuns(String datasetName, + GetDatasetRunsRequest request) { + return this.rawClient.getRuns(datasetName, request).thenApply(response -> response.body()); + } + + /** + * Get dataset runs + */ + public CompletableFuture getRuns(String datasetName, + GetDatasetRunsRequest request, RequestOptions requestOptions) { + return this.rawClient.getRuns(datasetName, request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/datasets/AsyncRawDatasetsClient.java b/src/main/java/com/langfuse/client/resources/datasets/AsyncRawDatasetsClient.java new file mode 100644 index 0000000..3268886 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasets/AsyncRawDatasetsClient.java @@ -0,0 +1,554 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasets; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Dataset; +import com.langfuse.client.resources.commons.types.DatasetRunWithItems; +import com.langfuse.client.resources.datasets.requests.GetDatasetRunsRequest; +import com.langfuse.client.resources.datasets.requests.GetDatasetsRequest; +import com.langfuse.client.resources.datasets.types.CreateDatasetRequest; +import com.langfuse.client.resources.datasets.types.DeleteDatasetRunResponse; +import com.langfuse.client.resources.datasets.types.PaginatedDatasetRuns; +import com.langfuse.client.resources.datasets.types.PaginatedDatasets; + +public class AsyncRawDatasetsClient { + protected final ClientOptions clientOptions; + + public AsyncRawDatasetsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all datasets + */ + public CompletableFuture> list() { + return list(GetDatasetsRequest.builder().build()); + } + + /** + * Get all datasets + */ + public CompletableFuture> list( + RequestOptions requestOptions) { + return list(GetDatasetsRequest.builder().build(),requestOptions); + } + + /** + * Get all datasets + */ + public CompletableFuture> list( + GetDatasetsRequest request) { + return list(request,null); + } + + /** + * Get all datasets + */ + public CompletableFuture> list( + GetDatasetsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/datasets");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasets.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a dataset + */ + public CompletableFuture> get(String datasetName) { + return get(datasetName,null); + } + + /** + * Get a dataset + */ + public CompletableFuture> get(String datasetName, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/datasets") + .addPathSegment(datasetName);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Dataset.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create a dataset + */ + public CompletableFuture> create( + CreateDatasetRequest request) { + return create(request,null); + } + + /** + * Create a dataset + */ + public CompletableFuture> create( + CreateDatasetRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/datasets");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Dataset.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a dataset run and its items + */ + public CompletableFuture> getRun( + String datasetName, String runName) { + return getRun(datasetName,runName,null); + } + + /** + * Get a dataset run and its items + */ + public CompletableFuture> getRun( + String datasetName, String runName, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("datasets") + .addPathSegment(datasetName) + .addPathSegments("runs") + .addPathSegment(runName);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetRunWithItems.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public CompletableFuture> deleteRun( + String datasetName, String runName) { + return deleteRun(datasetName,runName,null); + } + + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public CompletableFuture> deleteRun( + String datasetName, String runName, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("datasets") + .addPathSegment(datasetName) + .addPathSegments("runs") + .addPathSegment(runName);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteDatasetRunResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get dataset runs + */ + public CompletableFuture> getRuns( + String datasetName) { + return getRuns(datasetName,GetDatasetRunsRequest.builder().build()); + } + + /** + * Get dataset runs + */ + public CompletableFuture> getRuns( + String datasetName, RequestOptions requestOptions) { + return getRuns(datasetName,GetDatasetRunsRequest.builder().build(),requestOptions); + } + + /** + * Get dataset runs + */ + public CompletableFuture> getRuns( + String datasetName, GetDatasetRunsRequest request) { + return getRuns(datasetName,request,null); + } + + /** + * Get dataset runs + */ + public CompletableFuture> getRuns( + String datasetName, GetDatasetRunsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("datasets") + .addPathSegment(datasetName) + .addPathSegments("runs");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasetRuns.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/datasets/DatasetsClient.java b/src/main/java/com/langfuse/client/resources/datasets/DatasetsClient.java index f5a7fd5..b4b18df 100644 --- a/src/main/java/com/langfuse/client/resources/datasets/DatasetsClient.java +++ b/src/main/java/com/langfuse/client/resources/datasets/DatasetsClient.java @@ -4,29 +4,9 @@ package com.langfuse.client.resources.datasets; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.Dataset; import com.langfuse.client.resources.commons.types.DatasetRunWithItems; import com.langfuse.client.resources.datasets.requests.GetDatasetRunsRequest; @@ -39,354 +19,132 @@ public class DatasetsClient { protected final ClientOptions clientOptions; + private final RawDatasetsClient rawClient; + public DatasetsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawDatasetsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawDatasetsClient withRawResponse() { + return this.rawClient; } /** * Get all datasets */ public PaginatedDatasets list() { - return list(GetDatasetsRequest.builder().build()); + return this.rawClient.list().body(); + } + + /** + * Get all datasets + */ + public PaginatedDatasets list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).body(); } /** * Get all datasets */ public PaginatedDatasets list(GetDatasetsRequest request) { - return list(request,null); + return this.rawClient.list(request).body(); } /** * Get all datasets */ public PaginatedDatasets list(GetDatasetsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("v2/datasets");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedDatasets.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.list(request, requestOptions).body(); + } + + /** + * Get a dataset + */ + public Dataset get(String datasetName) { + return this.rawClient.get(datasetName).body(); + } - /** - * Get a dataset - */ - public Dataset get(String datasetName) { - return get(datasetName,null); - } + /** + * Get a dataset + */ + public Dataset get(String datasetName, RequestOptions requestOptions) { + return this.rawClient.get(datasetName, requestOptions).body(); + } - /** - * Get a dataset - */ - public Dataset get(String datasetName, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("v2/datasets") - .addPathSegment(datasetName) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Dataset.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Create a dataset + */ + public Dataset create(CreateDatasetRequest request) { + return this.rawClient.create(request).body(); + } - /** - * Create a dataset - */ - public Dataset create(CreateDatasetRequest request) { - return create(request,null); - } + /** + * Create a dataset + */ + public Dataset create(CreateDatasetRequest request, RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).body(); + } - /** - * Create a dataset - */ - public Dataset create(CreateDatasetRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("v2/datasets") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Dataset.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a dataset run and its items + */ + public DatasetRunWithItems getRun(String datasetName, String runName) { + return this.rawClient.getRun(datasetName, runName).body(); + } - /** - * Get a dataset run and its items - */ - public DatasetRunWithItems getRun(String datasetName, String runName) { - return getRun(datasetName,runName,null); - } + /** + * Get a dataset run and its items + */ + public DatasetRunWithItems getRun(String datasetName, String runName, + RequestOptions requestOptions) { + return this.rawClient.getRun(datasetName, runName, requestOptions).body(); + } - /** - * Get a dataset run and its items - */ - public DatasetRunWithItems getRun(String datasetName, String runName, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("datasets") - .addPathSegment(datasetName) - .addPathSegments("runs") - .addPathSegment(runName) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetRunWithItems.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public DeleteDatasetRunResponse deleteRun(String datasetName, String runName) { + return this.rawClient.deleteRun(datasetName, runName).body(); + } - /** - * Delete a dataset run and all its run items. This action is irreversible. - */ - public DeleteDatasetRunResponse deleteRun(String datasetName, String runName) { - return deleteRun(datasetName,runName,null); - } + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public DeleteDatasetRunResponse deleteRun(String datasetName, String runName, + RequestOptions requestOptions) { + return this.rawClient.deleteRun(datasetName, runName, requestOptions).body(); + } - /** - * Delete a dataset run and all its run items. This action is irreversible. - */ - public DeleteDatasetRunResponse deleteRun(String datasetName, String runName, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("datasets") - .addPathSegment(datasetName) - .addPathSegments("runs") - .addPathSegment(runName) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeleteDatasetRunResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get dataset runs + */ + public PaginatedDatasetRuns getRuns(String datasetName) { + return this.rawClient.getRuns(datasetName).body(); + } - /** - * Get dataset runs - */ - public PaginatedDatasetRuns getRuns(String datasetName) { - return getRuns(datasetName,GetDatasetRunsRequest.builder().build()); - } + /** + * Get dataset runs + */ + public PaginatedDatasetRuns getRuns(String datasetName, RequestOptions requestOptions) { + return this.rawClient.getRuns(datasetName, requestOptions).body(); + } - /** - * Get dataset runs - */ - public PaginatedDatasetRuns getRuns(String datasetName, GetDatasetRunsRequest request) { - return getRuns(datasetName,request,null); - } + /** + * Get dataset runs + */ + public PaginatedDatasetRuns getRuns(String datasetName, GetDatasetRunsRequest request) { + return this.rawClient.getRuns(datasetName, request).body(); + } - /** - * Get dataset runs - */ - public PaginatedDatasetRuns getRuns(String datasetName, GetDatasetRunsRequest request, - RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("datasets") - .addPathSegment(datasetName) - .addPathSegments("runs");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedDatasetRuns.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - } + /** + * Get dataset runs + */ + public PaginatedDatasetRuns getRuns(String datasetName, GetDatasetRunsRequest request, + RequestOptions requestOptions) { + return this.rawClient.getRuns(datasetName, request, requestOptions).body(); + } +} diff --git a/src/main/java/com/langfuse/client/resources/datasets/RawDatasetsClient.java b/src/main/java/com/langfuse/client/resources/datasets/RawDatasetsClient.java new file mode 100644 index 0000000..a468ed2 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/datasets/RawDatasetsClient.java @@ -0,0 +1,437 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.datasets; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Dataset; +import com.langfuse.client.resources.commons.types.DatasetRunWithItems; +import com.langfuse.client.resources.datasets.requests.GetDatasetRunsRequest; +import com.langfuse.client.resources.datasets.requests.GetDatasetsRequest; +import com.langfuse.client.resources.datasets.types.CreateDatasetRequest; +import com.langfuse.client.resources.datasets.types.DeleteDatasetRunResponse; +import com.langfuse.client.resources.datasets.types.PaginatedDatasetRuns; +import com.langfuse.client.resources.datasets.types.PaginatedDatasets; + +public class RawDatasetsClient { + protected final ClientOptions clientOptions; + + public RawDatasetsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all datasets + */ + public LangfuseClientHttpResponse list() { + return list(GetDatasetsRequest.builder().build()); + } + + /** + * Get all datasets + */ + public LangfuseClientHttpResponse list(RequestOptions requestOptions) { + return list(GetDatasetsRequest.builder().build(),requestOptions); + } + + /** + * Get all datasets + */ + public LangfuseClientHttpResponse list(GetDatasetsRequest request) { + return list(request,null); + } + + /** + * Get all datasets + */ + public LangfuseClientHttpResponse list(GetDatasetsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/datasets");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasets.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a dataset + */ + public LangfuseClientHttpResponse get(String datasetName) { + return get(datasetName,null); + } + + /** + * Get a dataset + */ + public LangfuseClientHttpResponse get(String datasetName, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/datasets") + .addPathSegment(datasetName);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Dataset.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create a dataset + */ + public LangfuseClientHttpResponse create(CreateDatasetRequest request) { + return create(request,null); + } + + /** + * Create a dataset + */ + public LangfuseClientHttpResponse create(CreateDatasetRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/datasets");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Dataset.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a dataset run and its items + */ + public LangfuseClientHttpResponse getRun(String datasetName, + String runName) { + return getRun(datasetName,runName,null); + } + + /** + * Get a dataset run and its items + */ + public LangfuseClientHttpResponse getRun(String datasetName, + String runName, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("datasets") + .addPathSegment(datasetName) + .addPathSegments("runs") + .addPathSegment(runName);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetRunWithItems.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public LangfuseClientHttpResponse deleteRun(String datasetName, + String runName) { + return deleteRun(datasetName,runName,null); + } + + /** + * Delete a dataset run and all its run items. This action is irreversible. + */ + public LangfuseClientHttpResponse deleteRun(String datasetName, + String runName, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("datasets") + .addPathSegment(datasetName) + .addPathSegments("runs") + .addPathSegment(runName);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteDatasetRunResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get dataset runs + */ + public LangfuseClientHttpResponse getRuns(String datasetName) { + return getRuns(datasetName,GetDatasetRunsRequest.builder().build()); + } + + /** + * Get dataset runs + */ + public LangfuseClientHttpResponse getRuns(String datasetName, + RequestOptions requestOptions) { + return getRuns(datasetName,GetDatasetRunsRequest.builder().build(),requestOptions); + } + + /** + * Get dataset runs + */ + public LangfuseClientHttpResponse getRuns(String datasetName, + GetDatasetRunsRequest request) { + return getRuns(datasetName,request,null); + } + + /** + * Get dataset runs + */ + public LangfuseClientHttpResponse getRuns(String datasetName, + GetDatasetRunsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("datasets") + .addPathSegment(datasetName) + .addPathSegments("runs");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedDatasetRuns.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetRunsRequest.java b/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetRunsRequest.java index 086eb7c..cb91a47 100644 --- a/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetRunsRequest.java +++ b/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetRunsRequest.java @@ -104,6 +104,9 @@ public Builder from(GetDatasetRunsRequest other) { return this; } + /** + *

        page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder page(Integer page) { return this; } + /** + *

        limit of items per page

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder limit(Integer limit) { public GetDatasetRunsRequest build() { return new GetDatasetRunsRequest(page, limit, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetsRequest.java b/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetsRequest.java index 72e2b18..9f62262 100644 --- a/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetsRequest.java +++ b/src/main/java/com/langfuse/client/resources/datasets/requests/GetDatasetsRequest.java @@ -104,6 +104,9 @@ public Builder from(GetDatasetsRequest other) { return this; } + /** + *

        page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder page(Integer page) { return this; } + /** + *

        limit of items per page

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder limit(Integer limit) { public GetDatasetsRequest build() { return new GetDatasetsRequest(page, limit, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasets/types/CreateDatasetRequest.java b/src/main/java/com/langfuse/client/resources/datasets/types/CreateDatasetRequest.java index 3d33dd1..d98b839 100644 --- a/src/main/java/com/langfuse/client/resources/datasets/types/CreateDatasetRequest.java +++ b/src/main/java/com/langfuse/client/resources/datasets/types/CreateDatasetRequest.java @@ -118,6 +118,10 @@ public interface NameStage { public interface _FinalStage { CreateDatasetRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage description(Optional description); _FinalStage description(String description); @@ -126,10 +130,16 @@ public interface _FinalStage { _FinalStage metadata(Object metadata); + /** + *

        JSON Schema for validating dataset item inputs. When set, all new and existing dataset items will be validated against this schema.

        + */ _FinalStage inputSchema(Optional inputSchema); _FinalStage inputSchema(Object inputSchema); + /** + *

        JSON Schema for validating dataset item expected outputs. When set, all new and existing dataset items will be validated against this schema.

        + */ _FinalStage expectedOutputSchema(Optional expectedOutputSchema); _FinalStage expectedOutputSchema(Object expectedOutputSchema); @@ -182,6 +192,9 @@ public _FinalStage expectedOutputSchema(Object expectedOutputSchema) { return this; } + /** + *

        JSON Schema for validating dataset item expected outputs. When set, all new and existing dataset items will be validated against this schema.

        + */ @java.lang.Override @JsonSetter( value = "expectedOutputSchema", @@ -202,6 +215,9 @@ public _FinalStage inputSchema(Object inputSchema) { return this; } + /** + *

        JSON Schema for validating dataset item inputs. When set, all new and existing dataset items will be validated against this schema.

        + */ @java.lang.Override @JsonSetter( value = "inputSchema", @@ -248,5 +264,17 @@ public _FinalStage description(Optional description) { public CreateDatasetRequest build() { return new CreateDatasetRequest(name, description, metadata, inputSchema, expectedOutputSchema, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasets/types/DeleteDatasetRunResponse.java b/src/main/java/com/langfuse/client/resources/datasets/types/DeleteDatasetRunResponse.java index 458e49f..06c318f 100644 --- a/src/main/java/com/langfuse/client/resources/datasets/types/DeleteDatasetRunResponse.java +++ b/src/main/java/com/langfuse/client/resources/datasets/types/DeleteDatasetRunResponse.java @@ -75,6 +75,10 @@ public interface MessageStage { public interface _FinalStage { DeleteDatasetRunResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -106,5 +110,17 @@ public _FinalStage message(@NotNull String message) { public DeleteDatasetRunResponse build() { return new DeleteDatasetRunResponse(message, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasetRuns.java b/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasetRuns.java index 76bc737..10aadd4 100644 --- a/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasetRuns.java +++ b/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasetRuns.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedDatasetRuns build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(DatasetRun data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(DatasetRun data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public PaginatedDatasetRuns build() { return new PaginatedDatasetRuns(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasets.java b/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasets.java index 2ac9ef1..29161f9 100644 --- a/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasets.java +++ b/src/main/java/com/langfuse/client/resources/datasets/types/PaginatedDatasets.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedDatasets build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(Dataset data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(Dataset data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public PaginatedDatasets build() { return new PaginatedDatasets(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/health/AsyncHealthClient.java b/src/main/java/com/langfuse/client/resources/health/AsyncHealthClient.java new file mode 100644 index 0000000..7eb13ef --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/health/AsyncHealthClient.java @@ -0,0 +1,42 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.health; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.health.types.HealthResponse; + +public class AsyncHealthClient { + protected final ClientOptions clientOptions; + + private final AsyncRawHealthClient rawClient; + + public AsyncHealthClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawHealthClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawHealthClient withRawResponse() { + return this.rawClient; + } + + /** + * Check health of API and database + */ + public CompletableFuture health() { + return this.rawClient.health().thenApply(response -> response.body()); + } + + /** + * Check health of API and database + */ + public CompletableFuture health(RequestOptions requestOptions) { + return this.rawClient.health(requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/health/AsyncRawHealthClient.java b/src/main/java/com/langfuse/client/resources/health/AsyncRawHealthClient.java new file mode 100644 index 0000000..21acfbc --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/health/AsyncRawHealthClient.java @@ -0,0 +1,117 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.health; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.health.errors.ServiceUnavailableError; +import com.langfuse.client.resources.health.types.HealthResponse; + +public class AsyncRawHealthClient { + protected final ClientOptions clientOptions; + + public AsyncRawHealthClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Check health of API and database + */ + public CompletableFuture> health() { + return health(null); + } + + /** + * Check health of API and database + */ + public CompletableFuture> health( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("health");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, HealthResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 503:future.completeExceptionally(new ServiceUnavailableError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/health/HealthClient.java b/src/main/java/com/langfuse/client/resources/health/HealthClient.java index a7fcda6..80d34e8 100644 --- a/src/main/java/com/langfuse/client/resources/health/HealthClient.java +++ b/src/main/java/com/langfuse/client/resources/health/HealthClient.java @@ -4,85 +4,38 @@ package com.langfuse.client.resources.health; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; -import com.langfuse.client.resources.health.errors.ServiceUnavailableError; import com.langfuse.client.resources.health.types.HealthResponse; public class HealthClient { protected final ClientOptions clientOptions; + private final RawHealthClient rawClient; + public HealthClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawHealthClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawHealthClient withRawResponse() { + return this.rawClient; } /** * Check health of API and database */ public HealthResponse health() { - return health(null); + return this.rawClient.health().body(); } /** * Check health of API and database */ public HealthResponse health(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("health") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), HealthResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 503:throw new ServiceUnavailableError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.health(requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/health/RawHealthClient.java b/src/main/java/com/langfuse/client/resources/health/RawHealthClient.java new file mode 100644 index 0000000..44b6625 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/health/RawHealthClient.java @@ -0,0 +1,92 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.health; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.health.errors.ServiceUnavailableError; +import com.langfuse.client.resources.health.types.HealthResponse; + +public class RawHealthClient { + protected final ClientOptions clientOptions; + + public RawHealthClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Check health of API and database + */ + public LangfuseClientHttpResponse health() { + return health(null); + } + + /** + * Check health of API and database + */ + public LangfuseClientHttpResponse health(RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("health");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, HealthResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 503:throw new ServiceUnavailableError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/health/errors/ServiceUnavailableError.java b/src/main/java/com/langfuse/client/resources/health/errors/ServiceUnavailableError.java index 961fa83..3344983 100644 --- a/src/main/java/com/langfuse/client/resources/health/errors/ServiceUnavailableError.java +++ b/src/main/java/com/langfuse/client/resources/health/errors/ServiceUnavailableError.java @@ -6,9 +6,14 @@ import com.langfuse.client.core.LangfuseClientApiException; import java.lang.Object; +import okhttp3.Response; public final class ServiceUnavailableError extends LangfuseClientApiException { public ServiceUnavailableError(Object body) { super("ServiceUnavailableError", 503, body); } + + public ServiceUnavailableError(Object body, Response rawResponse) { + super("ServiceUnavailableError", 503, body, rawResponse); + } } diff --git a/src/main/java/com/langfuse/client/resources/health/types/HealthResponse.java b/src/main/java/com/langfuse/client/resources/health/types/HealthResponse.java index a0e7ad0..5eaa7c9 100644 --- a/src/main/java/com/langfuse/client/resources/health/types/HealthResponse.java +++ b/src/main/java/com/langfuse/client/resources/health/types/HealthResponse.java @@ -79,6 +79,9 @@ public static VersionStage builder() { } public interface VersionStage { + /** + *

        Langfuse server version

        + */ StatusStage version(@NotNull String version); Builder from(HealthResponse other); @@ -90,6 +93,10 @@ public interface StatusStage { public interface _FinalStage { HealthResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -114,6 +121,7 @@ public Builder from(HealthResponse other) { } /** + *

        Langfuse server version

        *

        Langfuse server version

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -135,5 +143,17 @@ public _FinalStage status(@NotNull String status) { public HealthResponse build() { return new HealthResponse(version, status, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/AsyncIngestionClient.java b/src/main/java/com/langfuse/client/resources/ingestion/AsyncIngestionClient.java new file mode 100644 index 0000000..35d3366 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/ingestion/AsyncIngestionClient.java @@ -0,0 +1,70 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.ingestion; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.ingestion.requests.IngestionRequest; +import com.langfuse.client.resources.ingestion.types.IngestionResponse; + +public class AsyncIngestionClient { + protected final ClientOptions clientOptions; + + private final AsyncRawIngestionClient rawClient; + + public AsyncIngestionClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawIngestionClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawIngestionClient withRawResponse() { + return this.rawClient; + } + + /** + * Legacy endpoint for batch ingestion for Langfuse Observability. + *

        -> Please use the OpenTelemetry endpoint (/api/public/otel/v1/traces). Learn more: https://langfuse.com/integrations/native/opentelemetry

        + *

        Within each batch, there can be multiple events. + * Each event has a type, an id, a timestamp, metadata and a body. + * Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace. + * We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request. + * The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App. + * I.e. if you want to update a trace, you'd use the same body id, but separate event IDs.

        + *

        Notes:

        + *
          + *
        • Introduction to data model: https://langfuse.com/docs/observability/data-model
        • + *
        • Batch sizes are limited to 3.5 MB in total. You need to adjust the number of events per batch accordingly.
        • + *
        • The API does not return a 4xx status code for input errors. Instead, it responds with a 207 status code, which includes a list of the encountered errors.
        • + *
        + */ + public CompletableFuture batch(IngestionRequest request) { + return this.rawClient.batch(request).thenApply(response -> response.body()); + } + + /** + * Legacy endpoint for batch ingestion for Langfuse Observability. + *

        -> Please use the OpenTelemetry endpoint (/api/public/otel/v1/traces). Learn more: https://langfuse.com/integrations/native/opentelemetry

        + *

        Within each batch, there can be multiple events. + * Each event has a type, an id, a timestamp, metadata and a body. + * Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace. + * We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request. + * The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App. + * I.e. if you want to update a trace, you'd use the same body id, but separate event IDs.

        + *

        Notes:

        + *
          + *
        • Introduction to data model: https://langfuse.com/docs/observability/data-model
        • + *
        • Batch sizes are limited to 3.5 MB in total. You need to adjust the number of events per batch accordingly.
        • + *
        • The API does not return a 4xx status code for input errors. Instead, it responds with a 207 status code, which includes a list of the encountered errors.
        • + *
        + */ + public CompletableFuture batch(IngestionRequest request, + RequestOptions requestOptions) { + return this.rawClient.batch(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/ingestion/AsyncRawIngestionClient.java b/src/main/java/com/langfuse/client/resources/ingestion/AsyncRawIngestionClient.java new file mode 100644 index 0000000..9648bd6 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/ingestion/AsyncRawIngestionClient.java @@ -0,0 +1,152 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.ingestion; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.ingestion.requests.IngestionRequest; +import com.langfuse.client.resources.ingestion.types.IngestionResponse; + +public class AsyncRawIngestionClient { + protected final ClientOptions clientOptions; + + public AsyncRawIngestionClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Legacy endpoint for batch ingestion for Langfuse Observability. + *

        -> Please use the OpenTelemetry endpoint (/api/public/otel/v1/traces). Learn more: https://langfuse.com/integrations/native/opentelemetry

        + *

        Within each batch, there can be multiple events. + * Each event has a type, an id, a timestamp, metadata and a body. + * Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace. + * We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request. + * The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App. + * I.e. if you want to update a trace, you'd use the same body id, but separate event IDs.

        + *

        Notes:

        + *
          + *
        • Introduction to data model: https://langfuse.com/docs/observability/data-model
        • + *
        • Batch sizes are limited to 3.5 MB in total. You need to adjust the number of events per batch accordingly.
        • + *
        • The API does not return a 4xx status code for input errors. Instead, it responds with a 207 status code, which includes a list of the encountered errors.
        • + *
        + */ + public CompletableFuture> batch( + IngestionRequest request) { + return batch(request,null); + } + + /** + * Legacy endpoint for batch ingestion for Langfuse Observability. + *

        -> Please use the OpenTelemetry endpoint (/api/public/otel/v1/traces). Learn more: https://langfuse.com/integrations/native/opentelemetry

        + *

        Within each batch, there can be multiple events. + * Each event has a type, an id, a timestamp, metadata and a body. + * Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace. + * We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request. + * The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App. + * I.e. if you want to update a trace, you'd use the same body id, but separate event IDs.

        + *

        Notes:

        + *
          + *
        • Introduction to data model: https://langfuse.com/docs/observability/data-model
        • + *
        • Batch sizes are limited to 3.5 MB in total. You need to adjust the number of events per batch accordingly.
        • + *
        • The API does not return a 4xx status code for input errors. Instead, it responds with a 207 status code, which includes a list of the encountered errors.
        • + *
        + */ + public CompletableFuture> batch( + IngestionRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("ingestion");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, IngestionResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/IngestionClient.java b/src/main/java/com/langfuse/client/resources/ingestion/IngestionClient.java index 27bff82..1ae0be4 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/IngestionClient.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/IngestionClient.java @@ -4,36 +4,26 @@ package com.langfuse.client.resources.ingestion; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.ingestion.requests.IngestionRequest; import com.langfuse.client.resources.ingestion.types.IngestionResponse; public class IngestionClient { protected final ClientOptions clientOptions; + private final RawIngestionClient rawClient; + public IngestionClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawIngestionClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawIngestionClient withRawResponse() { + return this.rawClient; } /** @@ -53,7 +43,7 @@ public IngestionClient(ClientOptions clientOptions) { * */ public IngestionResponse batch(IngestionRequest request) { - return batch(request,null); + return this.rawClient.batch(request).body(); } /** @@ -73,50 +63,6 @@ public IngestionResponse batch(IngestionRequest request) { * */ public IngestionResponse batch(IngestionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("ingestion") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), IngestionResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.batch(request, requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/RawIngestionClient.java b/src/main/java/com/langfuse/client/resources/ingestion/RawIngestionClient.java new file mode 100644 index 0000000..a9e3cc1 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/ingestion/RawIngestionClient.java @@ -0,0 +1,128 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.ingestion; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.ingestion.requests.IngestionRequest; +import com.langfuse.client.resources.ingestion.types.IngestionResponse; + +public class RawIngestionClient { + protected final ClientOptions clientOptions; + + public RawIngestionClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Legacy endpoint for batch ingestion for Langfuse Observability. + *

        -> Please use the OpenTelemetry endpoint (/api/public/otel/v1/traces). Learn more: https://langfuse.com/integrations/native/opentelemetry

        + *

        Within each batch, there can be multiple events. + * Each event has a type, an id, a timestamp, metadata and a body. + * Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace. + * We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request. + * The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App. + * I.e. if you want to update a trace, you'd use the same body id, but separate event IDs.

        + *

        Notes:

        + *
          + *
        • Introduction to data model: https://langfuse.com/docs/observability/data-model
        • + *
        • Batch sizes are limited to 3.5 MB in total. You need to adjust the number of events per batch accordingly.
        • + *
        • The API does not return a 4xx status code for input errors. Instead, it responds with a 207 status code, which includes a list of the encountered errors.
        • + *
        + */ + public LangfuseClientHttpResponse batch(IngestionRequest request) { + return batch(request,null); + } + + /** + * Legacy endpoint for batch ingestion for Langfuse Observability. + *

        -> Please use the OpenTelemetry endpoint (/api/public/otel/v1/traces). Learn more: https://langfuse.com/integrations/native/opentelemetry

        + *

        Within each batch, there can be multiple events. + * Each event has a type, an id, a timestamp, metadata and a body. + * Internally, we refer to this as the "event envelope" as it tells us something about the event but not the trace. + * We use the event id within this envelope to deduplicate messages to avoid processing the same event twice, i.e. the event id should be unique per request. + * The event.body.id is the ID of the actual trace and will be used for updates and will be visible within the Langfuse App. + * I.e. if you want to update a trace, you'd use the same body id, but separate event IDs.

        + *

        Notes:

        + *
          + *
        • Introduction to data model: https://langfuse.com/docs/observability/data-model
        • + *
        • Batch sizes are limited to 3.5 MB in total. You need to adjust the number of events per batch accordingly.
        • + *
        • The API does not return a 4xx status code for input errors. Instead, it responds with a 207 status code, which includes a list of the encountered errors.
        • + *
        + */ + public LangfuseClientHttpResponse batch(IngestionRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("ingestion");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, IngestionResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/requests/IngestionRequest.java b/src/main/java/com/langfuse/client/resources/ingestion/requests/IngestionRequest.java index e73b571..975f5aa 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/requests/IngestionRequest.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/requests/IngestionRequest.java @@ -106,13 +106,18 @@ public Builder from(IngestionRequest other) { return this; } + /** + *

        Batch of tracing events to be ingested. Discriminated by attribute type.

        + */ @JsonSetter( value = "batch", nulls = Nulls.SKIP ) public Builder batch(List batch) { this.batch.clear(); - this.batch.addAll(batch); + if (batch != null) { + this.batch.addAll(batch); + } return this; } @@ -122,10 +127,15 @@ public Builder addBatch(IngestionEvent batch) { } public Builder addAllBatch(List batch) { - this.batch.addAll(batch); + if (batch != null) { + this.batch.addAll(batch); + } return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @JsonSetter( value = "metadata", nulls = Nulls.SKIP @@ -143,5 +153,15 @@ public Builder metadata(Object metadata) { public IngestionRequest build() { return new IngestionRequest(batch, metadata, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/BaseEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/BaseEvent.java index 1d66997..9c56db1 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/BaseEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/BaseEvent.java @@ -99,18 +99,31 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(BaseEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ _FinalStage timestamp(@NotNull String timestamp); } public interface _FinalStage { BaseEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -141,6 +154,7 @@ public Builder from(BaseEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -152,6 +166,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -172,6 +187,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -186,5 +204,17 @@ public _FinalStage metadata(Optional metadata) { public BaseEvent build() { return new BaseEvent(id, timestamp, metadata, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventBody.java index b7b0951..2328755 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventBody.java @@ -395,5 +395,15 @@ public Builder environment(String environment) { public CreateEventBody build() { return new CreateEventBody(id, traceId, name, startTime, metadata, input, output, level, statusMessage, parentObservationId, version, environment, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventEvent.java index 3b97ba4..90f15fd 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateEventEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(CreateEventEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { CreateEventEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(CreateEventEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public CreateEventEvent build() { return new CreateEventEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationBody.java index 42b5b0e..1f06423 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationBody.java @@ -629,5 +629,15 @@ public Builder promptVersion(Integer promptVersion) { public CreateGenerationBody build() { return new CreateGenerationBody(endTime, id, traceId, name, startTime, metadata, input, output, level, statusMessage, parentObservationId, version, environment, completionStartTime, model, modelParameters, usage, usageDetails, costDetails, promptName, promptVersion, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationEvent.java index b7f89d1..6e406ca 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateGenerationEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(CreateGenerationEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { CreateGenerationEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(CreateGenerationEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public CreateGenerationEvent build() { return new CreateGenerationEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateObservationEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateObservationEvent.java index 300dd7f..3303700 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateObservationEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateObservationEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(CreateObservationEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { CreateObservationEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(CreateObservationEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public CreateObservationEvent build() { return new CreateObservationEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanBody.java index 0e5c30e..ee967ce 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanBody.java @@ -422,5 +422,15 @@ public Builder environment(String environment) { public CreateSpanBody build() { return new CreateSpanBody(endTime, id, traceId, name, startTime, metadata, input, output, level, statusMessage, parentObservationId, version, environment, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanEvent.java index 7b46842..cbf5989 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/CreateSpanEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(CreateSpanEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { CreateSpanEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(CreateSpanEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public CreateSpanEvent build() { return new CreateSpanEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionError.java b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionError.java index 58747c3..b6f8093 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionError.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionError.java @@ -107,6 +107,10 @@ public interface StatusStage { public interface _FinalStage { IngestionError build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage message(Optional message); _FinalStage message(String message); @@ -193,5 +197,17 @@ public _FinalStage message(Optional message) { public IngestionError build() { return new IngestionError(id, status, message, error, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionResponse.java b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionResponse.java index 24f4f28..f02749d 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionResponse.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionResponse.java @@ -104,7 +104,9 @@ public Builder from(IngestionResponse other) { ) public Builder successes(List successes) { this.successes.clear(); - this.successes.addAll(successes); + if (successes != null) { + this.successes.addAll(successes); + } return this; } @@ -114,7 +116,9 @@ public Builder addSuccesses(IngestionSuccess successes) { } public Builder addAllSuccesses(List successes) { - this.successes.addAll(successes); + if (successes != null) { + this.successes.addAll(successes); + } return this; } @@ -124,7 +128,9 @@ public Builder addAllSuccesses(List successes) { ) public Builder errors(List errors) { this.errors.clear(); - this.errors.addAll(errors); + if (errors != null) { + this.errors.addAll(errors); + } return this; } @@ -134,12 +140,24 @@ public Builder addErrors(IngestionError errors) { } public Builder addAllErrors(List errors) { - this.errors.addAll(errors); + if (errors != null) { + this.errors.addAll(errors); + } return this; } public IngestionResponse build() { return new IngestionResponse(successes, errors, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionSuccess.java b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionSuccess.java index 4691d39..47883bf 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionSuccess.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionSuccess.java @@ -87,6 +87,10 @@ public interface StatusStage { public interface _FinalStage { IngestionSuccess build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -128,5 +132,17 @@ public _FinalStage status(int status) { public IngestionSuccess build() { return new IngestionSuccess(id, status, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionUsage.java b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionUsage.java index b08e0d4..98673a1 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionUsage.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/IngestionUsage.java @@ -12,10 +12,11 @@ import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.langfuse.client.core.ObjectMappers; import java.io.IOException; -import java.lang.IllegalArgumentException; import java.lang.IllegalStateException; import java.lang.Object; +import java.lang.RuntimeException; import java.lang.String; +import java.lang.SuppressWarnings; import java.util.Objects; import com.langfuse.client.resources.commons.types.Usage; @@ -37,6 +38,7 @@ public Object get() { return this.value; } + @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if(this.type == 0) { return visitor.visit((Usage) this.value); @@ -91,11 +93,11 @@ public IngestionUsage deserialize(JsonParser p, DeserializationContext context) Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, Usage.class)); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, OpenAiUsage.class)); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationBody.java index 8881d33..c24874b 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationBody.java @@ -225,6 +225,10 @@ public interface TypeStage { public interface _FinalStage { ObservationBody build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage id(Optional id); _FinalStage id(String id); @@ -646,5 +650,17 @@ public _FinalStage id(Optional id) { public ObservationBody build() { return new ObservationBody(id, traceId, type, name, startTime, endTime, completionStartTime, model, modelParameters, input, version, metadata, output, usage, level, statusMessage, parentObservationId, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationType.java b/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationType.java index 7c63e9e..4294989 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationType.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/ObservationType.java @@ -4,39 +4,165 @@ package com.langfuse.client.resources.ingestion.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum ObservationType { - SPAN("SPAN"), +public final class ObservationType { + public static final ObservationType AGENT = new ObservationType(Value.AGENT, "AGENT"); - GENERATION("GENERATION"), + public static final ObservationType TOOL = new ObservationType(Value.TOOL, "TOOL"); - EVENT("EVENT"), + public static final ObservationType CHAIN = new ObservationType(Value.CHAIN, "CHAIN"); - AGENT("AGENT"), + public static final ObservationType EVALUATOR = new ObservationType(Value.EVALUATOR, "EVALUATOR"); - TOOL("TOOL"), + public static final ObservationType SPAN = new ObservationType(Value.SPAN, "SPAN"); - CHAIN("CHAIN"), + public static final ObservationType GENERATION = new ObservationType(Value.GENERATION, "GENERATION"); - RETRIEVER("RETRIEVER"), + public static final ObservationType GUARDRAIL = new ObservationType(Value.GUARDRAIL, "GUARDRAIL"); - EVALUATOR("EVALUATOR"), + public static final ObservationType EVENT = new ObservationType(Value.EVENT, "EVENT"); - EMBEDDING("EMBEDDING"), + public static final ObservationType EMBEDDING = new ObservationType(Value.EMBEDDING, "EMBEDDING"); - GUARDRAIL("GUARDRAIL"); + public static final ObservationType RETRIEVER = new ObservationType(Value.RETRIEVER, "RETRIEVER"); - private final String value; + private final Value value; - ObservationType(String value) { + private final String string; + + ObservationType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ObservationType && this.string.equals(((ObservationType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case AGENT: + return visitor.visitAgent(); + case TOOL: + return visitor.visitTool(); + case CHAIN: + return visitor.visitChain(); + case EVALUATOR: + return visitor.visitEvaluator(); + case SPAN: + return visitor.visitSpan(); + case GENERATION: + return visitor.visitGeneration(); + case GUARDRAIL: + return visitor.visitGuardrail(); + case EVENT: + return visitor.visitEvent(); + case EMBEDDING: + return visitor.visitEmbedding(); + case RETRIEVER: + return visitor.visitRetriever(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static ObservationType valueOf(String value) { + switch (value) { + case "AGENT": + return AGENT; + case "TOOL": + return TOOL; + case "CHAIN": + return CHAIN; + case "EVALUATOR": + return EVALUATOR; + case "SPAN": + return SPAN; + case "GENERATION": + return GENERATION; + case "GUARDRAIL": + return GUARDRAIL; + case "EVENT": + return EVENT; + case "EMBEDDING": + return EMBEDDING; + case "RETRIEVER": + return RETRIEVER; + default: + return new ObservationType(Value.UNKNOWN, value); + } + } + + public enum Value { + SPAN, + + GENERATION, + + EVENT, + + AGENT, + + TOOL, + + CHAIN, + + RETRIEVER, + + EVALUATOR, + + EMBEDDING, + + GUARDRAIL, + + UNKNOWN + } + + public interface Visitor { + T visitSpan(); + + T visitGeneration(); + + T visitEvent(); + + T visitAgent(); + + T visitTool(); + + T visitChain(); + + T visitRetriever(); + + T visitEvaluator(); + + T visitEmbedding(); + + T visitGuardrail(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiCompletionUsageSchema.java b/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiCompletionUsageSchema.java index e5d7530..faf875d 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiCompletionUsageSchema.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiCompletionUsageSchema.java @@ -121,6 +121,10 @@ public interface TotalTokensStage { public interface _FinalStage { OpenAiCompletionUsageSchema build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage promptTokensDetails(Optional>> promptTokensDetails); _FinalStage promptTokensDetails(Map> promptTokensDetails); @@ -221,5 +225,17 @@ public _FinalStage promptTokensDetails( public OpenAiCompletionUsageSchema build() { return new OpenAiCompletionUsageSchema(promptTokens, completionTokens, totalTokens, promptTokensDetails, completionTokensDetails, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiResponseUsageSchema.java b/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiResponseUsageSchema.java index 5c914d4..0c4c774 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiResponseUsageSchema.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiResponseUsageSchema.java @@ -121,6 +121,10 @@ public interface TotalTokensStage { public interface _FinalStage { OpenAiResponseUsageSchema build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage inputTokensDetails(Optional>> inputTokensDetails); _FinalStage inputTokensDetails(Map> inputTokensDetails); @@ -219,5 +223,17 @@ public _FinalStage inputTokensDetails( public OpenAiResponseUsageSchema build() { return new OpenAiResponseUsageSchema(inputTokens, outputTokens, totalTokens, inputTokensDetails, outputTokensDetails, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiUsage.java b/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiUsage.java index 102e7b7..9610d68 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiUsage.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/OpenAiUsage.java @@ -154,5 +154,15 @@ public Builder totalTokens(Integer totalTokens) { public OpenAiUsage build() { return new OpenAiUsage(promptTokens, completionTokens, totalTokens, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/OptionalObservationBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/OptionalObservationBody.java index a0b6925..595b5fd 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/OptionalObservationBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/OptionalObservationBody.java @@ -369,5 +369,15 @@ public Builder environment(String environment) { public OptionalObservationBody build() { return new OptionalObservationBody(traceId, name, startTime, metadata, input, output, level, statusMessage, parentObservationId, version, environment, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreBody.java index 34c7f94..e5df9aa 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreBody.java @@ -187,18 +187,28 @@ public static NameStage builder() { } public interface NameStage { + /** + *

        The name of the score. Always overrides "output" for correction scores.

        + */ ValueStage name(@NotNull String name); Builder from(ScoreBody other); } public interface ValueStage { + /** + *

        The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)

        + */ _FinalStage value(@NotNull CreateScoreValue value); } public interface _FinalStage { ScoreBody build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage id(Optional id); _FinalStage id(String id); @@ -223,6 +233,9 @@ public interface _FinalStage { _FinalStage environment(String environment); + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); @@ -235,10 +248,16 @@ public interface _FinalStage { _FinalStage metadata(Object metadata); + /** + *

        When set, must match the score value's type. If not set, will be inferred from the score value or config

        + */ _FinalStage dataType(Optional dataType); _FinalStage dataType(ScoreDataType dataType); + /** + *

        Reference a score config on a score. When set, the score name must equal the config name and scores must comply with the config's range and data type. For categorical scores, the value must map to a config category. Numeric scores might be constrained by the score config's max and min values

        + */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); @@ -299,6 +318,7 @@ public Builder from(ScoreBody other) { } /** + *

        The name of the score. Always overrides "output" for correction scores.

        *

        The name of the score. Always overrides "output" for correction scores.

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -310,6 +330,7 @@ public ValueStage name(@NotNull String name) { } /** + *

        The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)

        *

        The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -330,6 +351,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

        Reference a score config on a score. When set, the score name must equal the config name and scores must comply with the config's range and data type. For categorical scores, the value must map to a config category. Numeric scores might be constrained by the score config's max and min values

        + */ @java.lang.Override @JsonSetter( value = "configId", @@ -350,6 +374,9 @@ public _FinalStage dataType(ScoreDataType dataType) { return this; } + /** + *

        When set, must match the score value's type. If not set, will be inferred from the score value or config

        + */ @java.lang.Override @JsonSetter( value = "dataType", @@ -402,6 +429,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ @java.lang.Override @JsonSetter( value = "queueId", @@ -512,5 +542,17 @@ public _FinalStage id(Optional id) { public ScoreBody build() { return new ScoreBody(id, traceId, sessionId, observationId, datasetRunId, name, environment, queueId, value, comment, metadata, dataType, configId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreEvent.java index 0441fba..9ebbfe5 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/ScoreEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(ScoreEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { ScoreEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(ScoreEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public ScoreEvent build() { return new ScoreEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogBody.java index 3521378..ec20420 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogBody.java @@ -74,6 +74,10 @@ public interface LogStage { public interface _FinalStage { SdkLogBody build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -105,5 +109,17 @@ public _FinalStage log(Object log) { public SdkLogBody build() { return new SdkLogBody(log, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogEvent.java index 7d8b44e..8e97046 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/SdkLogEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(SdkLogEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { SdkLogEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(SdkLogEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public SdkLogEvent build() { return new SdkLogEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/TraceBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/TraceBody.java index e162ec8..c4d1edb 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/TraceBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/TraceBody.java @@ -395,6 +395,9 @@ public Builder environment(String environment) { return this; } + /** + *

        Make trace publicly accessible via url

        + */ @JsonSetter( value = "public", nulls = Nulls.SKIP @@ -412,5 +415,15 @@ public Builder public_(Boolean public_) { public TraceBody build() { return new TraceBody(id, timestamp, name, userId, input, output, sessionId, release, version, metadata, tags, environment, public_, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/TraceEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/TraceEvent.java index 5cf32a9..7afe632 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/TraceEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/TraceEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(TraceEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { TraceEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(TraceEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public TraceEvent build() { return new TraceEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateEventBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateEventBody.java index 3224a3b..609cf41 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateEventBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateEventBody.java @@ -184,6 +184,10 @@ public interface IdStage { public interface _FinalStage { UpdateEventBody build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); @@ -467,5 +471,17 @@ public _FinalStage traceId(Optional traceId) { public UpdateEventBody build() { return new UpdateEventBody(id, traceId, name, startTime, metadata, input, output, level, statusMessage, parentObservationId, version, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationBody.java index 04ab1c2..afbffd4 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationBody.java @@ -265,6 +265,10 @@ public interface IdStage { public interface _FinalStage { UpdateGenerationBody build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage endTime(Optional endTime); _FinalStage endTime(OffsetDateTime endTime); @@ -755,5 +759,17 @@ public _FinalStage endTime(Optional endTime) { public UpdateGenerationBody build() { return new UpdateGenerationBody(endTime, id, traceId, name, startTime, metadata, input, output, level, statusMessage, parentObservationId, version, environment, completionStartTime, model, modelParameters, usage, promptName, usageDetails, costDetails, promptVersion, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationEvent.java index 3c0388e..e00c8b4 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateGenerationEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(UpdateGenerationEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { UpdateGenerationEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(UpdateGenerationEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public UpdateGenerationEvent build() { return new UpdateGenerationEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateObservationEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateObservationEvent.java index e893202..4d4cefe 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateObservationEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateObservationEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(UpdateObservationEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { UpdateObservationEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(UpdateObservationEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public UpdateObservationEvent build() { return new UpdateObservationEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanBody.java b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanBody.java index c41e387..8947fa7 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanBody.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanBody.java @@ -194,6 +194,10 @@ public interface IdStage { public interface _FinalStage { UpdateSpanBody build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage endTime(Optional endTime); _FinalStage endTime(OffsetDateTime endTime); @@ -500,5 +504,17 @@ public _FinalStage endTime(Optional endTime) { public UpdateSpanBody build() { return new UpdateSpanBody(endTime, id, traceId, name, startTime, metadata, input, output, level, statusMessage, parentObservationId, version, environment, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanEvent.java b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanEvent.java index ab35005..8315d78 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanEvent.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/UpdateSpanEvent.java @@ -107,12 +107,18 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        UUID v4 that identifies the event

        + */ TimestampStage id(@NotNull String id); Builder from(UpdateSpanEvent other); } public interface TimestampStage { + /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        + */ BodyStage timestamp(@NotNull String timestamp); } @@ -123,6 +129,13 @@ public interface BodyStage { public interface _FinalStage { UpdateSpanEvent build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ _FinalStage metadata(Optional metadata); _FinalStage metadata(Object metadata); @@ -156,6 +169,7 @@ public Builder from(UpdateSpanEvent other) { } /** + *

        UUID v4 that identifies the event

        *

        UUID v4 that identifies the event

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -167,6 +181,7 @@ public TimestampStage id(@NotNull String id) { } /** + *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        *

        Datetime (ISO 8601) of event creation in client. Should be as close to actual event creation in client as possible, this timestamp will be used for ordering of events in future release. Resolution: milliseconds (required), microseconds (optimal).

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -194,6 +209,9 @@ public _FinalStage metadata(Object metadata) { return this; } + /** + *

        Optional. Metadata field used by the Langfuse SDKs for debugging.

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -208,5 +226,17 @@ public _FinalStage metadata(Optional metadata) { public UpdateSpanEvent build() { return new UpdateSpanEvent(id, timestamp, metadata, body, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/ingestion/types/UsageDetails.java b/src/main/java/com/langfuse/client/resources/ingestion/types/UsageDetails.java index 438819d..c37b734 100644 --- a/src/main/java/com/langfuse/client/resources/ingestion/types/UsageDetails.java +++ b/src/main/java/com/langfuse/client/resources/ingestion/types/UsageDetails.java @@ -13,11 +13,12 @@ import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.langfuse.client.core.ObjectMappers; import java.io.IOException; -import java.lang.IllegalArgumentException; import java.lang.IllegalStateException; import java.lang.Integer; import java.lang.Object; +import java.lang.RuntimeException; import java.lang.String; +import java.lang.SuppressWarnings; import java.util.Map; import java.util.Objects; @@ -39,6 +40,7 @@ public Object get() { return this.value; } + @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if(this.type == 0) { return visitor.visit((Map) this.value); @@ -101,15 +103,15 @@ public UsageDetails deserialize(JsonParser p, DeserializationContext context) th Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, OpenAiCompletionUsageSchema.class)); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, OpenAiResponseUsageSchema.class)); - } catch(IllegalArgumentException e) { + } catch(RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/AsyncLlmConnectionsClient.java b/src/main/java/com/langfuse/client/resources/llmconnections/AsyncLlmConnectionsClient.java new file mode 100644 index 0000000..ae7c069 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/llmconnections/AsyncLlmConnectionsClient.java @@ -0,0 +1,75 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.llmconnections; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.llmconnections.requests.GetLlmConnectionsRequest; +import com.langfuse.client.resources.llmconnections.types.LlmConnection; +import com.langfuse.client.resources.llmconnections.types.PaginatedLlmConnections; +import com.langfuse.client.resources.llmconnections.types.UpsertLlmConnectionRequest; + +public class AsyncLlmConnectionsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawLlmConnectionsClient rawClient; + + public AsyncLlmConnectionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawLlmConnectionsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawLlmConnectionsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture list(GetLlmConnectionsRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture list(GetLlmConnectionsRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public CompletableFuture upsert(UpsertLlmConnectionRequest request) { + return this.rawClient.upsert(request).thenApply(response -> response.body()); + } + + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public CompletableFuture upsert(UpsertLlmConnectionRequest request, + RequestOptions requestOptions) { + return this.rawClient.upsert(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/AsyncRawLlmConnectionsClient.java b/src/main/java/com/langfuse/client/resources/llmconnections/AsyncRawLlmConnectionsClient.java new file mode 100644 index 0000000..9331efb --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/llmconnections/AsyncRawLlmConnectionsClient.java @@ -0,0 +1,224 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.llmconnections; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.llmconnections.requests.GetLlmConnectionsRequest; +import com.langfuse.client.resources.llmconnections.types.LlmConnection; +import com.langfuse.client.resources.llmconnections.types.PaginatedLlmConnections; +import com.langfuse.client.resources.llmconnections.types.UpsertLlmConnectionRequest; + +public class AsyncRawLlmConnectionsClient { + protected final ClientOptions clientOptions; + + public AsyncRawLlmConnectionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture> list() { + return list(GetLlmConnectionsRequest.builder().build()); + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture> list( + RequestOptions requestOptions) { + return list(GetLlmConnectionsRequest.builder().build(),requestOptions); + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture> list( + GetLlmConnectionsRequest request) { + return list(request,null); + } + + /** + * Get all LLM connections in a project + */ + public CompletableFuture> list( + GetLlmConnectionsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("llm-connections");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedLlmConnections.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public CompletableFuture> upsert( + UpsertLlmConnectionRequest request) { + return upsert(request,null); + } + + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public CompletableFuture> upsert( + UpsertLlmConnectionRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("llm-connections");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, LlmConnection.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/LlmConnectionsClient.java b/src/main/java/com/langfuse/client/resources/llmconnections/LlmConnectionsClient.java index cb27009..0d21f98 100644 --- a/src/main/java/com/langfuse/client/resources/llmconnections/LlmConnectionsClient.java +++ b/src/main/java/com/langfuse/client/resources/llmconnections/LlmConnectionsClient.java @@ -4,29 +4,8 @@ package com.langfuse.client.resources.llmconnections; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.llmconnections.requests.GetLlmConnectionsRequest; import com.langfuse.client.resources.llmconnections.types.LlmConnection; import com.langfuse.client.resources.llmconnections.types.PaginatedLlmConnections; @@ -35,22 +14,39 @@ public class LlmConnectionsClient { protected final ClientOptions clientOptions; + private final RawLlmConnectionsClient rawClient; + public LlmConnectionsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawLlmConnectionsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawLlmConnectionsClient withRawResponse() { + return this.rawClient; } /** * Get all LLM connections in a project */ public PaginatedLlmConnections list() { - return list(GetLlmConnectionsRequest.builder().build()); + return this.rawClient.list().body(); + } + + /** + * Get all LLM connections in a project + */ + public PaginatedLlmConnections list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).body(); } /** * Get all LLM connections in a project */ public PaginatedLlmConnections list(GetLlmConnectionsRequest request) { - return list(request,null); + return this.rawClient.list(request).body(); } /** @@ -58,105 +54,20 @@ public PaginatedLlmConnections list(GetLlmConnectionsRequest request) { */ public PaginatedLlmConnections list(GetLlmConnectionsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("llm-connections");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedLlmConnections.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.list(request, requestOptions).body(); + } - /** - * Create or update an LLM connection. The connection is upserted on provider. - */ - public LlmConnection upsert(UpsertLlmConnectionRequest request) { - return upsert(request,null); - } + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public LlmConnection upsert(UpsertLlmConnectionRequest request) { + return this.rawClient.upsert(request).body(); + } - /** - * Create or update an LLM connection. The connection is upserted on provider. - */ - public LlmConnection upsert(UpsertLlmConnectionRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("llm-connections") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), LlmConnection.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public LlmConnection upsert(UpsertLlmConnectionRequest request, RequestOptions requestOptions) { + return this.rawClient.upsert(request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/RawLlmConnectionsClient.java b/src/main/java/com/langfuse/client/resources/llmconnections/RawLlmConnectionsClient.java new file mode 100644 index 0000000..7240cc6 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/llmconnections/RawLlmConnectionsClient.java @@ -0,0 +1,181 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.llmconnections; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.llmconnections.requests.GetLlmConnectionsRequest; +import com.langfuse.client.resources.llmconnections.types.LlmConnection; +import com.langfuse.client.resources.llmconnections.types.PaginatedLlmConnections; +import com.langfuse.client.resources.llmconnections.types.UpsertLlmConnectionRequest; + +public class RawLlmConnectionsClient { + protected final ClientOptions clientOptions; + + public RawLlmConnectionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all LLM connections in a project + */ + public LangfuseClientHttpResponse list() { + return list(GetLlmConnectionsRequest.builder().build()); + } + + /** + * Get all LLM connections in a project + */ + public LangfuseClientHttpResponse list(RequestOptions requestOptions) { + return list(GetLlmConnectionsRequest.builder().build(),requestOptions); + } + + /** + * Get all LLM connections in a project + */ + public LangfuseClientHttpResponse list( + GetLlmConnectionsRequest request) { + return list(request,null); + } + + /** + * Get all LLM connections in a project + */ + public LangfuseClientHttpResponse list(GetLlmConnectionsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("llm-connections");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedLlmConnections.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public LangfuseClientHttpResponse upsert(UpsertLlmConnectionRequest request) { + return upsert(request,null); + } + + /** + * Create or update an LLM connection. The connection is upserted on provider. + */ + public LangfuseClientHttpResponse upsert(UpsertLlmConnectionRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("llm-connections");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, LlmConnection.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/requests/GetLlmConnectionsRequest.java b/src/main/java/com/langfuse/client/resources/llmconnections/requests/GetLlmConnectionsRequest.java index 3207c65..97e5ce1 100644 --- a/src/main/java/com/langfuse/client/resources/llmconnections/requests/GetLlmConnectionsRequest.java +++ b/src/main/java/com/langfuse/client/resources/llmconnections/requests/GetLlmConnectionsRequest.java @@ -104,6 +104,9 @@ public Builder from(GetLlmConnectionsRequest other) { return this; } + /** + *

        page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder page(Integer page) { return this; } + /** + *

        limit of items per page

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder limit(Integer limit) { public GetLlmConnectionsRequest build() { return new GetLlmConnectionsRequest(page, limit, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmAdapter.java b/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmAdapter.java index e794c35..6f3f0ac 100644 --- a/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmAdapter.java +++ b/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmAdapter.java @@ -4,31 +4,125 @@ package com.langfuse.client.resources.llmconnections.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum LlmAdapter { - ANTHROPIC("anthropic"), +public final class LlmAdapter { + public static final LlmAdapter ANTHROPIC = new LlmAdapter(Value.ANTHROPIC, "anthropic"); - OPEN_AI("openai"), + public static final LlmAdapter AZURE = new LlmAdapter(Value.AZURE, "azure"); - AZURE("azure"), + public static final LlmAdapter GOOGLE_AI_STUDIO = new LlmAdapter(Value.GOOGLE_AI_STUDIO, "google-ai-studio"); - BEDROCK("bedrock"), + public static final LlmAdapter BEDROCK = new LlmAdapter(Value.BEDROCK, "bedrock"); - GOOGLE_VERTEX_AI("google-vertex-ai"), + public static final LlmAdapter GOOGLE_VERTEX_AI = new LlmAdapter(Value.GOOGLE_VERTEX_AI, "google-vertex-ai"); - GOOGLE_AI_STUDIO("google-ai-studio"); + public static final LlmAdapter OPEN_AI = new LlmAdapter(Value.OPEN_AI, "openai"); - private final String value; + private final Value value; - LlmAdapter(String value) { + private final String string; + + LlmAdapter(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof LlmAdapter && this.string.equals(((LlmAdapter) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ANTHROPIC: + return visitor.visitAnthropic(); + case AZURE: + return visitor.visitAzure(); + case GOOGLE_AI_STUDIO: + return visitor.visitGoogleAiStudio(); + case BEDROCK: + return visitor.visitBedrock(); + case GOOGLE_VERTEX_AI: + return visitor.visitGoogleVertexAi(); + case OPEN_AI: + return visitor.visitOpenAi(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static LlmAdapter valueOf(String value) { + switch (value) { + case "anthropic": + return ANTHROPIC; + case "azure": + return AZURE; + case "google-ai-studio": + return GOOGLE_AI_STUDIO; + case "bedrock": + return BEDROCK; + case "google-vertex-ai": + return GOOGLE_VERTEX_AI; + case "openai": + return OPEN_AI; + default: + return new LlmAdapter(Value.UNKNOWN, value); + } + } + + public enum Value { + ANTHROPIC, + + OPEN_AI, + + AZURE, + + BEDROCK, + + GOOGLE_VERTEX_AI, + + GOOGLE_AI_STUDIO, + + UNKNOWN + } + + public interface Visitor { + T visitAnthropic(); + + T visitOpenAi(); + + T visitAzure(); + + T visitBedrock(); + + T visitGoogleVertexAi(); + + T visitGoogleAiStudio(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmConnection.java b/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmConnection.java index 98d828d..fc18ee5 100644 --- a/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmConnection.java +++ b/src/main/java/com/langfuse/client/resources/llmconnections/types/LlmConnection.java @@ -186,18 +186,30 @@ public interface IdStage { } public interface ProviderStage { + /** + *

        Provider name (e.g., 'openai', 'my-gateway'). Must be unique in project, used for upserting.

        + */ AdapterStage provider(@NotNull String provider); } public interface AdapterStage { + /** + *

        The adapter used to interface with the LLM

        + */ DisplaySecretKeyStage adapter(@NotNull String adapter); } public interface DisplaySecretKeyStage { + /** + *

        Masked version of the secret key for display purposes

        + */ WithDefaultModelsStage displaySecretKey(@NotNull String displaySecretKey); } public interface WithDefaultModelsStage { + /** + *

        Whether to include default models for this adapter

        + */ CreatedAtStage withDefaultModels(boolean withDefaultModels); } @@ -212,22 +224,38 @@ public interface UpdatedAtStage { public interface _FinalStage { LlmConnection build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Custom base URL for the LLM API

        + */ _FinalStage baseUrl(Optional baseUrl); _FinalStage baseUrl(String baseUrl); + /** + *

        List of custom model names available for this connection

        + */ _FinalStage customModels(List customModels); _FinalStage addCustomModels(String customModels); _FinalStage addAllCustomModels(List customModels); + /** + *

        Keys of extra headers sent with requests (values excluded for security)

        + */ _FinalStage extraHeaderKeys(List extraHeaderKeys); _FinalStage addExtraHeaderKeys(String extraHeaderKeys); _FinalStage addAllExtraHeaderKeys(List extraHeaderKeys); + /** + *

        Adapter-specific configuration. Required for Bedrock ({"region":"us-east-1"}), optional for VertexAI ({"location":"us-central1"}), not used by other adapters.

        + */ _FinalStage config(Optional> config); _FinalStage config(Map config); @@ -289,6 +317,7 @@ public ProviderStage id(@NotNull String id) { } /** + *

        Provider name (e.g., 'openai', 'my-gateway'). Must be unique in project, used for upserting.

        *

        Provider name (e.g., 'openai', 'my-gateway'). Must be unique in project, used for upserting.

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -300,6 +329,7 @@ public AdapterStage provider(@NotNull String provider) { } /** + *

        The adapter used to interface with the LLM

        *

        The adapter used to interface with the LLM

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -311,6 +341,7 @@ public DisplaySecretKeyStage adapter(@NotNull String adapter) { } /** + *

        Masked version of the secret key for display purposes

        *

        Masked version of the secret key for display purposes

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -322,6 +353,7 @@ public WithDefaultModelsStage displaySecretKey(@NotNull String displaySecretKey) } /** + *

        Whether to include default models for this adapter

        *

        Whether to include default models for this adapter

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -356,6 +388,9 @@ public _FinalStage config(Map config) { return this; } + /** + *

        Adapter-specific configuration. Required for Bedrock ({"region":"us-east-1"}), optional for VertexAI ({"location":"us-central1"}), not used by other adapters.

        + */ @java.lang.Override @JsonSetter( value = "config", @@ -372,7 +407,9 @@ public _FinalStage config(Optional> config) { */ @java.lang.Override public _FinalStage addAllExtraHeaderKeys(List extraHeaderKeys) { - this.extraHeaderKeys.addAll(extraHeaderKeys); + if (extraHeaderKeys != null) { + this.extraHeaderKeys.addAll(extraHeaderKeys); + } return this; } @@ -386,6 +423,9 @@ public _FinalStage addExtraHeaderKeys(String extraHeaderKeys) { return this; } + /** + *

        Keys of extra headers sent with requests (values excluded for security)

        + */ @java.lang.Override @JsonSetter( value = "extraHeaderKeys", @@ -393,7 +433,9 @@ public _FinalStage addExtraHeaderKeys(String extraHeaderKeys) { ) public _FinalStage extraHeaderKeys(List extraHeaderKeys) { this.extraHeaderKeys.clear(); - this.extraHeaderKeys.addAll(extraHeaderKeys); + if (extraHeaderKeys != null) { + this.extraHeaderKeys.addAll(extraHeaderKeys); + } return this; } @@ -403,7 +445,9 @@ public _FinalStage extraHeaderKeys(List extraHeaderKeys) { */ @java.lang.Override public _FinalStage addAllCustomModels(List customModels) { - this.customModels.addAll(customModels); + if (customModels != null) { + this.customModels.addAll(customModels); + } return this; } @@ -417,6 +461,9 @@ public _FinalStage addCustomModels(String customModels) { return this; } + /** + *

        List of custom model names available for this connection

        + */ @java.lang.Override @JsonSetter( value = "customModels", @@ -424,7 +471,9 @@ public _FinalStage addCustomModels(String customModels) { ) public _FinalStage customModels(List customModels) { this.customModels.clear(); - this.customModels.addAll(customModels); + if (customModels != null) { + this.customModels.addAll(customModels); + } return this; } @@ -438,6 +487,9 @@ public _FinalStage baseUrl(String baseUrl) { return this; } + /** + *

        Custom base URL for the LLM API

        + */ @java.lang.Override @JsonSetter( value = "baseURL", @@ -452,5 +504,17 @@ public _FinalStage baseUrl(Optional baseUrl) { public LlmConnection build() { return new LlmConnection(id, provider, adapter, displaySecretKey, baseUrl, customModels, withDefaultModels, extraHeaderKeys, config, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/types/PaginatedLlmConnections.java b/src/main/java/com/langfuse/client/resources/llmconnections/types/PaginatedLlmConnections.java index 23fd18f..eb0b1a9 100644 --- a/src/main/java/com/langfuse/client/resources/llmconnections/types/PaginatedLlmConnections.java +++ b/src/main/java/com/langfuse/client/resources/llmconnections/types/PaginatedLlmConnections.java @@ -89,6 +89,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedLlmConnections build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(LlmConnection data); @@ -126,7 +130,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -143,7 +149,9 @@ public _FinalStage addData(LlmConnection data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -151,5 +159,17 @@ public _FinalStage data(List data) { public PaginatedLlmConnections build() { return new PaginatedLlmConnections(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/llmconnections/types/UpsertLlmConnectionRequest.java b/src/main/java/com/langfuse/client/resources/llmconnections/types/UpsertLlmConnectionRequest.java index 3001037..ada9adc 100644 --- a/src/main/java/com/langfuse/client/resources/llmconnections/types/UpsertLlmConnectionRequest.java +++ b/src/main/java/com/langfuse/client/resources/llmconnections/types/UpsertLlmConnectionRequest.java @@ -155,38 +155,66 @@ public static ProviderStage builder() { } public interface ProviderStage { + /** + *

        Provider name (e.g., 'openai', 'my-gateway'). Must be unique in project, used for upserting.

        + */ AdapterStage provider(@NotNull String provider); Builder from(UpsertLlmConnectionRequest other); } public interface AdapterStage { + /** + *

        The adapter used to interface with the LLM

        + */ SecretKeyStage adapter(@NotNull LlmAdapter adapter); } public interface SecretKeyStage { + /** + *

        Secret key for the LLM API.

        + */ _FinalStage secretKey(@NotNull String secretKey); } public interface _FinalStage { UpsertLlmConnectionRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Custom base URL for the LLM API

        + */ _FinalStage baseUrl(Optional baseUrl); _FinalStage baseUrl(String baseUrl); + /** + *

        List of custom model names

        + */ _FinalStage customModels(Optional> customModels); _FinalStage customModels(List customModels); + /** + *

        Whether to include default models. Default is true.

        + */ _FinalStage withDefaultModels(Optional withDefaultModels); _FinalStage withDefaultModels(Boolean withDefaultModels); + /** + *

        Extra headers to send with requests

        + */ _FinalStage extraHeaders(Optional> extraHeaders); _FinalStage extraHeaders(Map extraHeaders); + /** + *

        Adapter-specific configuration. Validation rules: - Bedrock: Required. Must be {"region": "<aws-region>"} (e.g., {"region":"us-east-1"}) - VertexAI: Optional. If provided, must be {"location": "<gcp-location>"} (e.g., {"location":"us-central1"}) - Other adapters: Not supported. Omit this field or set to null.

        + */ _FinalStage config(Optional> config); _FinalStage config(Map config); @@ -232,6 +260,7 @@ public Builder from(UpsertLlmConnectionRequest other) { } /** + *

        Provider name (e.g., 'openai', 'my-gateway'). Must be unique in project, used for upserting.

        *

        Provider name (e.g., 'openai', 'my-gateway'). Must be unique in project, used for upserting.

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -243,6 +272,7 @@ public AdapterStage provider(@NotNull String provider) { } /** + *

        The adapter used to interface with the LLM

        *

        The adapter used to interface with the LLM

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -254,6 +284,7 @@ public SecretKeyStage adapter(@NotNull LlmAdapter adapter) { } /** + *

        Secret key for the LLM API.

        *

        Secret key for the LLM API.

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -274,6 +305,9 @@ public _FinalStage config(Map config) { return this; } + /** + *

        Adapter-specific configuration. Validation rules: - Bedrock: Required. Must be {"region": "<aws-region>"} (e.g., {"region":"us-east-1"}) - VertexAI: Optional. If provided, must be {"location": "<gcp-location>"} (e.g., {"location":"us-central1"}) - Other adapters: Not supported. Omit this field or set to null.

        + */ @java.lang.Override @JsonSetter( value = "config", @@ -294,6 +328,9 @@ public _FinalStage extraHeaders(Map extraHeaders) { return this; } + /** + *

        Extra headers to send with requests

        + */ @java.lang.Override @JsonSetter( value = "extraHeaders", @@ -314,6 +351,9 @@ public _FinalStage withDefaultModels(Boolean withDefaultModels) { return this; } + /** + *

        Whether to include default models. Default is true.

        + */ @java.lang.Override @JsonSetter( value = "withDefaultModels", @@ -334,6 +374,9 @@ public _FinalStage customModels(List customModels) { return this; } + /** + *

        List of custom model names

        + */ @java.lang.Override @JsonSetter( value = "customModels", @@ -354,6 +397,9 @@ public _FinalStage baseUrl(String baseUrl) { return this; } + /** + *

        Custom base URL for the LLM API

        + */ @java.lang.Override @JsonSetter( value = "baseURL", @@ -368,5 +414,17 @@ public _FinalStage baseUrl(Optional baseUrl) { public UpsertLlmConnectionRequest build() { return new UpsertLlmConnectionRequest(provider, adapter, secretKey, baseUrl, customModels, withDefaultModels, extraHeaders, config, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/media/AsyncMediaClient.java b/src/main/java/com/langfuse/client/resources/media/AsyncMediaClient.java new file mode 100644 index 0000000..6b4234e --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/media/AsyncMediaClient.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.media; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.media.types.GetMediaResponse; +import com.langfuse.client.resources.media.types.GetMediaUploadUrlRequest; +import com.langfuse.client.resources.media.types.GetMediaUploadUrlResponse; +import com.langfuse.client.resources.media.types.PatchMediaBody; + +public class AsyncMediaClient { + protected final ClientOptions clientOptions; + + private final AsyncRawMediaClient rawClient; + + public AsyncMediaClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawMediaClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawMediaClient withRawResponse() { + return this.rawClient; + } + + /** + * Get a media record + */ + public CompletableFuture get(String mediaId) { + return this.rawClient.get(mediaId).thenApply(response -> response.body()); + } + + /** + * Get a media record + */ + public CompletableFuture get(String mediaId, RequestOptions requestOptions) { + return this.rawClient.get(mediaId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Patch a media record + */ + public CompletableFuture patch(String mediaId, PatchMediaBody request) { + return this.rawClient.patch(mediaId, request).thenApply(response -> response.body()); + } + + /** + * Patch a media record + */ + public CompletableFuture patch(String mediaId, PatchMediaBody request, + RequestOptions requestOptions) { + return this.rawClient.patch(mediaId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a presigned upload URL for a media record + */ + public CompletableFuture getUploadUrl( + GetMediaUploadUrlRequest request) { + return this.rawClient.getUploadUrl(request).thenApply(response -> response.body()); + } + + /** + * Get a presigned upload URL for a media record + */ + public CompletableFuture getUploadUrl(GetMediaUploadUrlRequest request, + RequestOptions requestOptions) { + return this.rawClient.getUploadUrl(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/media/AsyncRawMediaClient.java b/src/main/java/com/langfuse/client/resources/media/AsyncRawMediaClient.java new file mode 100644 index 0000000..544c11c --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/media/AsyncRawMediaClient.java @@ -0,0 +1,286 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.media; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.media.types.GetMediaResponse; +import com.langfuse.client.resources.media.types.GetMediaUploadUrlRequest; +import com.langfuse.client.resources.media.types.GetMediaUploadUrlResponse; +import com.langfuse.client.resources.media.types.PatchMediaBody; + +public class AsyncRawMediaClient { + protected final ClientOptions clientOptions; + + public AsyncRawMediaClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a media record + */ + public CompletableFuture> get(String mediaId) { + return get(mediaId,null); + } + + /** + * Get a media record + */ + public CompletableFuture> get(String mediaId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("media") + .addPathSegment(mediaId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetMediaResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Patch a media record + */ + public CompletableFuture> patch(String mediaId, + PatchMediaBody request) { + return patch(mediaId,request,null); + } + + /** + * Patch a media record + */ + public CompletableFuture> patch(String mediaId, + PatchMediaBody request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("media") + .addPathSegment(mediaId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a presigned upload URL for a media record + */ + public CompletableFuture> getUploadUrl( + GetMediaUploadUrlRequest request) { + return getUploadUrl(request,null); + } + + /** + * Get a presigned upload URL for a media record + */ + public CompletableFuture> getUploadUrl( + GetMediaUploadUrlRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("media");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetMediaUploadUrlResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/media/MediaClient.java b/src/main/java/com/langfuse/client/resources/media/MediaClient.java index 3c57dc8..945bed7 100644 --- a/src/main/java/com/langfuse/client/resources/media/MediaClient.java +++ b/src/main/java/com/langfuse/client/resources/media/MediaClient.java @@ -4,28 +4,9 @@ package com.langfuse.client.resources.media; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.media.types.GetMediaResponse; import com.langfuse.client.resources.media.types.GetMediaUploadUrlRequest; import com.langfuse.client.resources.media.types.GetMediaUploadUrlResponse; @@ -34,126 +15,53 @@ public class MediaClient { protected final ClientOptions clientOptions; + private final RawMediaClient rawClient; + public MediaClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawMediaClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawMediaClient withRawResponse() { + return this.rawClient; } /** * Get a media record */ public GetMediaResponse get(String mediaId) { - return get(mediaId,null); + return this.rawClient.get(mediaId).body(); } /** * Get a media record */ public GetMediaResponse get(String mediaId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("media") - .addPathSegment(mediaId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetMediaResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.get(mediaId, requestOptions).body(); } /** * Patch a media record */ public void patch(String mediaId, PatchMediaBody request) { - patch(mediaId,request,null); + this.rawClient.patch(mediaId, request).body(); } /** * Patch a media record */ public void patch(String mediaId, PatchMediaBody request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("media") - .addPathSegment(mediaId) - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + this.rawClient.patch(mediaId, request, requestOptions).body(); } /** * Get a presigned upload URL for a media record */ public GetMediaUploadUrlResponse getUploadUrl(GetMediaUploadUrlRequest request) { - return getUploadUrl(request,null); + return this.rawClient.getUploadUrl(request).body(); } /** @@ -161,50 +69,6 @@ public GetMediaUploadUrlResponse getUploadUrl(GetMediaUploadUrlRequest request) */ public GetMediaUploadUrlResponse getUploadUrl(GetMediaUploadUrlRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("media") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetMediaUploadUrlResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getUploadUrl(request, requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/media/RawMediaClient.java b/src/main/java/com/langfuse/client/resources/media/RawMediaClient.java new file mode 100644 index 0000000..6292128 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/media/RawMediaClient.java @@ -0,0 +1,226 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.media; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import java.lang.Void; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.media.types.GetMediaResponse; +import com.langfuse.client.resources.media.types.GetMediaUploadUrlRequest; +import com.langfuse.client.resources.media.types.GetMediaUploadUrlResponse; +import com.langfuse.client.resources.media.types.PatchMediaBody; + +public class RawMediaClient { + protected final ClientOptions clientOptions; + + public RawMediaClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a media record + */ + public LangfuseClientHttpResponse get(String mediaId) { + return get(mediaId,null); + } + + /** + * Get a media record + */ + public LangfuseClientHttpResponse get(String mediaId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("media") + .addPathSegment(mediaId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetMediaResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Patch a media record + */ + public LangfuseClientHttpResponse patch(String mediaId, PatchMediaBody request) { + return patch(mediaId,request,null); + } + + /** + * Patch a media record + */ + public LangfuseClientHttpResponse patch(String mediaId, PatchMediaBody request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("media") + .addPathSegment(mediaId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a presigned upload URL for a media record + */ + public LangfuseClientHttpResponse getUploadUrl( + GetMediaUploadUrlRequest request) { + return getUploadUrl(request,null); + } + + /** + * Get a presigned upload URL for a media record + */ + public LangfuseClientHttpResponse getUploadUrl( + GetMediaUploadUrlRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("media");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetMediaUploadUrlResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/media/types/GetMediaResponse.java b/src/main/java/com/langfuse/client/resources/media/types/GetMediaResponse.java index 387c706..f0c5249 100644 --- a/src/main/java/com/langfuse/client/resources/media/types/GetMediaResponse.java +++ b/src/main/java/com/langfuse/client/resources/media/types/GetMediaResponse.java @@ -129,33 +129,55 @@ public static MediaIdStage builder() { } public interface MediaIdStage { + /** + *

        The unique langfuse identifier of a media record

        + */ ContentTypeStage mediaId(@NotNull String mediaId); Builder from(GetMediaResponse other); } public interface ContentTypeStage { + /** + *

        The MIME type of the media record

        + */ ContentLengthStage contentType(@NotNull String contentType); } public interface ContentLengthStage { + /** + *

        The size of the media record in bytes

        + */ UploadedAtStage contentLength(int contentLength); } public interface UploadedAtStage { + /** + *

        The date and time when the media record was uploaded

        + */ UrlStage uploadedAt(@NotNull OffsetDateTime uploadedAt); } public interface UrlStage { + /** + *

        The download URL of the media record

        + */ UrlExpiryStage url(@NotNull String url); } public interface UrlExpiryStage { + /** + *

        The expiry date and time of the media record download URL

        + */ _FinalStage urlExpiry(@NotNull String urlExpiry); } public interface _FinalStage { GetMediaResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -192,6 +214,7 @@ public Builder from(GetMediaResponse other) { } /** + *

        The unique langfuse identifier of a media record

        *

        The unique langfuse identifier of a media record

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -203,6 +226,7 @@ public ContentTypeStage mediaId(@NotNull String mediaId) { } /** + *

        The MIME type of the media record

        *

        The MIME type of the media record

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -214,6 +238,7 @@ public ContentLengthStage contentType(@NotNull String contentType) { } /** + *

        The size of the media record in bytes

        *

        The size of the media record in bytes

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -225,6 +250,7 @@ public UploadedAtStage contentLength(int contentLength) { } /** + *

        The date and time when the media record was uploaded

        *

        The date and time when the media record was uploaded

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -236,6 +262,7 @@ public UrlStage uploadedAt(@NotNull OffsetDateTime uploadedAt) { } /** + *

        The download URL of the media record

        *

        The download URL of the media record

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -247,6 +274,7 @@ public UrlExpiryStage url(@NotNull String url) { } /** + *

        The expiry date and time of the media record download URL

        *

        The expiry date and time of the media record download URL

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -261,5 +289,17 @@ public _FinalStage urlExpiry(@NotNull String urlExpiry) { public GetMediaResponse build() { return new GetMediaResponse(mediaId, contentType, contentLength, uploadedAt, url, urlExpiry, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlRequest.java b/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlRequest.java index 2643ae5..b2b2feb 100644 --- a/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlRequest.java +++ b/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlRequest.java @@ -127,6 +127,9 @@ public static TraceIdStage builder() { } public interface TraceIdStage { + /** + *

        The trace ID associated with the media record

        + */ ContentTypeStage traceId(@NotNull String traceId); Builder from(GetMediaUploadUrlRequest other); @@ -137,20 +140,36 @@ public interface ContentTypeStage { } public interface ContentLengthStage { + /** + *

        The size of the media record in bytes

        + */ Sha256HashStage contentLength(int contentLength); } public interface Sha256HashStage { + /** + *

        The SHA-256 hash of the media record

        + */ FieldStage sha256Hash(@NotNull String sha256Hash); } public interface FieldStage { + /** + *

        The trace / observation field the media record is associated with. This can be one of input, output, metadata

        + */ _FinalStage field(@NotNull String field); } public interface _FinalStage { GetMediaUploadUrlRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The observation ID associated with the media record. If the media record is associated directly with a trace, this will be null.

        + */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); @@ -190,6 +209,7 @@ public Builder from(GetMediaUploadUrlRequest other) { } /** + *

        The trace ID associated with the media record

        *

        The trace ID associated with the media record

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -208,6 +228,7 @@ public ContentLengthStage contentType(@NotNull MediaContentType contentType) { } /** + *

        The size of the media record in bytes

        *

        The size of the media record in bytes

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -219,6 +240,7 @@ public Sha256HashStage contentLength(int contentLength) { } /** + *

        The SHA-256 hash of the media record

        *

        The SHA-256 hash of the media record

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -230,6 +252,7 @@ public FieldStage sha256Hash(@NotNull String sha256Hash) { } /** + *

        The trace / observation field the media record is associated with. This can be one of input, output, metadata

        *

        The trace / observation field the media record is associated with. This can be one of input, output, metadata

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -250,6 +273,9 @@ public _FinalStage observationId(String observationId) { return this; } + /** + *

        The observation ID associated with the media record. If the media record is associated directly with a trace, this will be null.

        + */ @java.lang.Override @JsonSetter( value = "observationId", @@ -264,5 +290,17 @@ public _FinalStage observationId(Optional observationId) { public GetMediaUploadUrlRequest build() { return new GetMediaUploadUrlRequest(traceId, observationId, contentType, contentLength, sha256Hash, field, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlResponse.java b/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlResponse.java index de88cb8..2ddb7b7 100644 --- a/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlResponse.java +++ b/src/main/java/com/langfuse/client/resources/media/types/GetMediaUploadUrlResponse.java @@ -85,6 +85,9 @@ public static MediaIdStage builder() { } public interface MediaIdStage { + /** + *

        The unique langfuse identifier of a media record

        + */ _FinalStage mediaId(@NotNull String mediaId); Builder from(GetMediaUploadUrlResponse other); @@ -93,6 +96,13 @@ public interface MediaIdStage { public interface _FinalStage { GetMediaUploadUrlResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The presigned upload URL. If the asset is already uploaded, this will be null

        + */ _FinalStage uploadUrl(Optional uploadUrl); _FinalStage uploadUrl(String uploadUrl); @@ -120,6 +130,7 @@ public Builder from(GetMediaUploadUrlResponse other) { } /** + *

        The unique langfuse identifier of a media record

        *

        The unique langfuse identifier of a media record

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -140,6 +151,9 @@ public _FinalStage uploadUrl(String uploadUrl) { return this; } + /** + *

        The presigned upload URL. If the asset is already uploaded, this will be null

        + */ @java.lang.Override @JsonSetter( value = "uploadUrl", @@ -154,5 +168,17 @@ public _FinalStage uploadUrl(Optional uploadUrl) { public GetMediaUploadUrlResponse build() { return new GetMediaUploadUrlResponse(uploadUrl, mediaId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/media/types/MediaContentType.java b/src/main/java/com/langfuse/client/resources/media/types/MediaContentType.java index e20aa46..201812d 100644 --- a/src/main/java/com/langfuse/client/resources/media/types/MediaContentType.java +++ b/src/main/java/com/langfuse/client/resources/media/types/MediaContentType.java @@ -4,123 +4,585 @@ package com.langfuse.client.resources.media.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum MediaContentType { - IMAGE_PNG("image/png"), +public final class MediaContentType { + public static final MediaContentType APPLICATION_OPENXML_SPREADSHEET = new MediaContentType(Value.APPLICATION_OPENXML_SPREADSHEET, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - IMAGE_JPEG("image/jpeg"), + public static final MediaContentType VIDEO_MP4 = new MediaContentType(Value.VIDEO_MP4, "video/mp4"); - IMAGE_JPG("image/jpg"), + public static final MediaContentType APPLICATION_RTF = new MediaContentType(Value.APPLICATION_RTF, "application/rtf"); - IMAGE_WEBP("image/webp"), + public static final MediaContentType AUDIO_OPUS = new MediaContentType(Value.AUDIO_OPUS, "audio/opus"); - IMAGE_GIF("image/gif"), + public static final MediaContentType AUDIO_MP3 = new MediaContentType(Value.AUDIO_MP3, "audio/mp3"); - IMAGE_SVG_XML("image/svg+xml"), + public static final MediaContentType IMAGE_TIFF = new MediaContentType(Value.IMAGE_TIFF, "image/tiff"); - IMAGE_TIFF("image/tiff"), + public static final MediaContentType APPLICATION_XML = new MediaContentType(Value.APPLICATION_XML, "application/xml"); - IMAGE_BMP("image/bmp"), + public static final MediaContentType AUDIO_MP4 = new MediaContentType(Value.AUDIO_MP4, "audio/mp4"); - IMAGE_AVIF("image/avif"), + public static final MediaContentType TEXT_X_PYTHON = new MediaContentType(Value.TEXT_X_PYTHON, "text/x-python"); - IMAGE_HEIC("image/heic"), + public static final MediaContentType AUDIO_WEBM = new MediaContentType(Value.AUDIO_WEBM, "audio/webm"); - AUDIO_MPEG("audio/mpeg"), + public static final MediaContentType AUDIO_MPEG = new MediaContentType(Value.AUDIO_MPEG, "audio/mpeg"); - AUDIO_MP_3("audio/mp3"), + public static final MediaContentType IMAGE_JPG = new MediaContentType(Value.IMAGE_JPG, "image/jpg"); - AUDIO_WAV("audio/wav"), + public static final MediaContentType APPLICATION_X_TAR = new MediaContentType(Value.APPLICATION_X_TAR, "application/x-tar"); - AUDIO_OGG("audio/ogg"), + public static final MediaContentType TEXT_CSS = new MediaContentType(Value.TEXT_CSS, "text/css"); - AUDIO_OGA("audio/oga"), + public static final MediaContentType VIDEO_X_MATROSKA = new MediaContentType(Value.VIDEO_X_MATROSKA, "video/x-matroska"); - AUDIO_AAC("audio/aac"), + public static final MediaContentType AUDIO_FLAC = new MediaContentType(Value.AUDIO_FLAC, "audio/flac"); - AUDIO_MP_4("audio/mp4"), + public static final MediaContentType AUDIO_AAC = new MediaContentType(Value.AUDIO_AAC, "audio/aac"); - AUDIO_FLAC("audio/flac"), + public static final MediaContentType IMAGE_JPEG = new MediaContentType(Value.IMAGE_JPEG, "image/jpeg"); - AUDIO_OPUS("audio/opus"), + public static final MediaContentType VIDEO_X_MSVIDEO = new MediaContentType(Value.VIDEO_X_MSVIDEO, "video/x-msvideo"); - AUDIO_WEBM("audio/webm"), + public static final MediaContentType AUDIO_WAV = new MediaContentType(Value.AUDIO_WAV, "audio/wav"); - VIDEO_MP_4("video/mp4"), + public static final MediaContentType IMAGE_AVIF = new MediaContentType(Value.IMAGE_AVIF, "image/avif"); - VIDEO_WEBM("video/webm"), + public static final MediaContentType APPLICATION_X_YAML = new MediaContentType(Value.APPLICATION_X_YAML, "application/x-yaml"); - VIDEO_OGG("video/ogg"), + public static final MediaContentType APPLICATION_X_NDJSON = new MediaContentType(Value.APPLICATION_X_NDJSON, "application/x-ndjson"); - VIDEO_MPEG("video/mpeg"), + public static final MediaContentType IMAGE_GIF = new MediaContentType(Value.IMAGE_GIF, "image/gif"); - VIDEO_QUICKTIME("video/quicktime"), + public static final MediaContentType IMAGE_BMP = new MediaContentType(Value.IMAGE_BMP, "image/bmp"); - VIDEO_X_MSVIDEO("video/x-msvideo"), + public static final MediaContentType APPLICATION_X7Z_COMPRESSED = new MediaContentType(Value.APPLICATION_X7Z_COMPRESSED, "application/x-7z-compressed"); - VIDEO_X_MATROSKA("video/x-matroska"), + public static final MediaContentType TEXT_HTML = new MediaContentType(Value.TEXT_HTML, "text/html"); - TEXT_PLAIN("text/plain"), + public static final MediaContentType VIDEO_QUICKTIME = new MediaContentType(Value.VIDEO_QUICKTIME, "video/quicktime"); - TEXT_HTML("text/html"), + public static final MediaContentType VIDEO_OGG = new MediaContentType(Value.VIDEO_OGG, "video/ogg"); - TEXT_CSS("text/css"), + public static final MediaContentType IMAGE_WEBP = new MediaContentType(Value.IMAGE_WEBP, "image/webp"); - TEXT_CSV("text/csv"), + public static final MediaContentType APPLICATION_PARQUET = new MediaContentType(Value.APPLICATION_PARQUET, "application/vnd.apache.parquet"); - TEXT_MARKDOWN("text/markdown"), + public static final MediaContentType APPLICATION_GZIP = new MediaContentType(Value.APPLICATION_GZIP, "application/gzip"); - TEXT_X_PYTHON("text/x-python"), + public static final MediaContentType APPLICATION_ZIP = new MediaContentType(Value.APPLICATION_ZIP, "application/zip"); - APPLICATION_JAVASCRIPT("application/javascript"), + public static final MediaContentType IMAGE_PNG = new MediaContentType(Value.IMAGE_PNG, "image/png"); - TEXT_X_TYPESCRIPT("text/x-typescript"), + public static final MediaContentType VIDEO_MPEG = new MediaContentType(Value.VIDEO_MPEG, "video/mpeg"); - APPLICATION_X_YAML("application/x-yaml"), + public static final MediaContentType IMAGE_SVG_XML = new MediaContentType(Value.IMAGE_SVG_XML, "image/svg+xml"); - APPLICATION_PDF("application/pdf"), + public static final MediaContentType TEXT_MARKDOWN = new MediaContentType(Value.TEXT_MARKDOWN, "text/markdown"); - APPLICATION_MSWORD("application/msword"), + public static final MediaContentType TEXT_PLAIN = new MediaContentType(Value.TEXT_PLAIN, "text/plain"); - APPLICATION_MS_EXCEL("application/vnd.ms-excel"), + public static final MediaContentType APPLICATION_PDF = new MediaContentType(Value.APPLICATION_PDF, "application/pdf"); - APPLICATION_OPENXML_SPREADSHEET("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), + public static final MediaContentType AUDIO_OGG = new MediaContentType(Value.AUDIO_OGG, "audio/ogg"); - APPLICATION_ZIP("application/zip"), + public static final MediaContentType APPLICATION_JSON = new MediaContentType(Value.APPLICATION_JSON, "application/json"); - APPLICATION_JSON("application/json"), + public static final MediaContentType APPLICATION_OPENXML_PRESENTATION = new MediaContentType(Value.APPLICATION_OPENXML_PRESENTATION, "application/vnd.openxmlformats-officedocument.presentationml.presentation"); - APPLICATION_XML("application/xml"), + public static final MediaContentType APPLICATION_MS_EXCEL = new MediaContentType(Value.APPLICATION_MS_EXCEL, "application/vnd.ms-excel"); - APPLICATION_OCTET_STREAM("application/octet-stream"), + public static final MediaContentType IMAGE_HEIC = new MediaContentType(Value.IMAGE_HEIC, "image/heic"); - APPLICATION_OPENXML_WORD("application/vnd.openxmlformats-officedocument.wordprocessingml.document"), + public static final MediaContentType APPLICATION_JAVASCRIPT = new MediaContentType(Value.APPLICATION_JAVASCRIPT, "application/javascript"); - APPLICATION_OPENXML_PRESENTATION("application/vnd.openxmlformats-officedocument.presentationml.presentation"), + public static final MediaContentType AUDIO_OGA = new MediaContentType(Value.AUDIO_OGA, "audio/oga"); - APPLICATION_RTF("application/rtf"), + public static final MediaContentType APPLICATION_OPENXML_WORD = new MediaContentType(Value.APPLICATION_OPENXML_WORD, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); - APPLICATION_X_NDJSON("application/x-ndjson"), + public static final MediaContentType APPLICATION_OCTET_STREAM = new MediaContentType(Value.APPLICATION_OCTET_STREAM, "application/octet-stream"); - APPLICATION_PARQUET("application/vnd.apache.parquet"), + public static final MediaContentType VIDEO_WEBM = new MediaContentType(Value.VIDEO_WEBM, "video/webm"); - APPLICATION_GZIP("application/gzip"), + public static final MediaContentType TEXT_CSV = new MediaContentType(Value.TEXT_CSV, "text/csv"); - APPLICATION_X_TAR("application/x-tar"), + public static final MediaContentType APPLICATION_MSWORD = new MediaContentType(Value.APPLICATION_MSWORD, "application/msword"); - APPLICATION_X_7_Z_COMPRESSED("application/x-7z-compressed"); + public static final MediaContentType TEXT_X_TYPESCRIPT = new MediaContentType(Value.TEXT_X_TYPESCRIPT, "text/x-typescript"); - private final String value; + private final Value value; - MediaContentType(String value) { + private final String string; + + MediaContentType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof MediaContentType && this.string.equals(((MediaContentType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case APPLICATION_OPENXML_SPREADSHEET: + return visitor.visitApplicationOpenxmlSpreadsheet(); + case VIDEO_MP4: + return visitor.visitVideoMp4(); + case APPLICATION_RTF: + return visitor.visitApplicationRtf(); + case AUDIO_OPUS: + return visitor.visitAudioOpus(); + case AUDIO_MP3: + return visitor.visitAudioMp3(); + case IMAGE_TIFF: + return visitor.visitImageTiff(); + case APPLICATION_XML: + return visitor.visitApplicationXml(); + case AUDIO_MP4: + return visitor.visitAudioMp4(); + case TEXT_X_PYTHON: + return visitor.visitTextXPython(); + case AUDIO_WEBM: + return visitor.visitAudioWebm(); + case AUDIO_MPEG: + return visitor.visitAudioMpeg(); + case IMAGE_JPG: + return visitor.visitImageJpg(); + case APPLICATION_X_TAR: + return visitor.visitApplicationXTar(); + case TEXT_CSS: + return visitor.visitTextCss(); + case VIDEO_X_MATROSKA: + return visitor.visitVideoXMatroska(); + case AUDIO_FLAC: + return visitor.visitAudioFlac(); + case AUDIO_AAC: + return visitor.visitAudioAac(); + case IMAGE_JPEG: + return visitor.visitImageJpeg(); + case VIDEO_X_MSVIDEO: + return visitor.visitVideoXMsvideo(); + case AUDIO_WAV: + return visitor.visitAudioWav(); + case IMAGE_AVIF: + return visitor.visitImageAvif(); + case APPLICATION_X_YAML: + return visitor.visitApplicationXYaml(); + case APPLICATION_X_NDJSON: + return visitor.visitApplicationXNdjson(); + case IMAGE_GIF: + return visitor.visitImageGif(); + case IMAGE_BMP: + return visitor.visitImageBmp(); + case APPLICATION_X7Z_COMPRESSED: + return visitor.visitApplicationX7ZCompressed(); + case TEXT_HTML: + return visitor.visitTextHtml(); + case VIDEO_QUICKTIME: + return visitor.visitVideoQuicktime(); + case VIDEO_OGG: + return visitor.visitVideoOgg(); + case IMAGE_WEBP: + return visitor.visitImageWebp(); + case APPLICATION_PARQUET: + return visitor.visitApplicationParquet(); + case APPLICATION_GZIP: + return visitor.visitApplicationGzip(); + case APPLICATION_ZIP: + return visitor.visitApplicationZip(); + case IMAGE_PNG: + return visitor.visitImagePng(); + case VIDEO_MPEG: + return visitor.visitVideoMpeg(); + case IMAGE_SVG_XML: + return visitor.visitImageSvgXml(); + case TEXT_MARKDOWN: + return visitor.visitTextMarkdown(); + case TEXT_PLAIN: + return visitor.visitTextPlain(); + case APPLICATION_PDF: + return visitor.visitApplicationPdf(); + case AUDIO_OGG: + return visitor.visitAudioOgg(); + case APPLICATION_JSON: + return visitor.visitApplicationJson(); + case APPLICATION_OPENXML_PRESENTATION: + return visitor.visitApplicationOpenxmlPresentation(); + case APPLICATION_MS_EXCEL: + return visitor.visitApplicationMsExcel(); + case IMAGE_HEIC: + return visitor.visitImageHeic(); + case APPLICATION_JAVASCRIPT: + return visitor.visitApplicationJavascript(); + case AUDIO_OGA: + return visitor.visitAudioOga(); + case APPLICATION_OPENXML_WORD: + return visitor.visitApplicationOpenxmlWord(); + case APPLICATION_OCTET_STREAM: + return visitor.visitApplicationOctetStream(); + case VIDEO_WEBM: + return visitor.visitVideoWebm(); + case TEXT_CSV: + return visitor.visitTextCsv(); + case APPLICATION_MSWORD: + return visitor.visitApplicationMsword(); + case TEXT_X_TYPESCRIPT: + return visitor.visitTextXTypescript(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static MediaContentType valueOf(String value) { + switch (value) { + case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": + return APPLICATION_OPENXML_SPREADSHEET; + case "video/mp4": + return VIDEO_MP4; + case "application/rtf": + return APPLICATION_RTF; + case "audio/opus": + return AUDIO_OPUS; + case "audio/mp3": + return AUDIO_MP3; + case "image/tiff": + return IMAGE_TIFF; + case "application/xml": + return APPLICATION_XML; + case "audio/mp4": + return AUDIO_MP4; + case "text/x-python": + return TEXT_X_PYTHON; + case "audio/webm": + return AUDIO_WEBM; + case "audio/mpeg": + return AUDIO_MPEG; + case "image/jpg": + return IMAGE_JPG; + case "application/x-tar": + return APPLICATION_X_TAR; + case "text/css": + return TEXT_CSS; + case "video/x-matroska": + return VIDEO_X_MATROSKA; + case "audio/flac": + return AUDIO_FLAC; + case "audio/aac": + return AUDIO_AAC; + case "image/jpeg": + return IMAGE_JPEG; + case "video/x-msvideo": + return VIDEO_X_MSVIDEO; + case "audio/wav": + return AUDIO_WAV; + case "image/avif": + return IMAGE_AVIF; + case "application/x-yaml": + return APPLICATION_X_YAML; + case "application/x-ndjson": + return APPLICATION_X_NDJSON; + case "image/gif": + return IMAGE_GIF; + case "image/bmp": + return IMAGE_BMP; + case "application/x-7z-compressed": + return APPLICATION_X7Z_COMPRESSED; + case "text/html": + return TEXT_HTML; + case "video/quicktime": + return VIDEO_QUICKTIME; + case "video/ogg": + return VIDEO_OGG; + case "image/webp": + return IMAGE_WEBP; + case "application/vnd.apache.parquet": + return APPLICATION_PARQUET; + case "application/gzip": + return APPLICATION_GZIP; + case "application/zip": + return APPLICATION_ZIP; + case "image/png": + return IMAGE_PNG; + case "video/mpeg": + return VIDEO_MPEG; + case "image/svg+xml": + return IMAGE_SVG_XML; + case "text/markdown": + return TEXT_MARKDOWN; + case "text/plain": + return TEXT_PLAIN; + case "application/pdf": + return APPLICATION_PDF; + case "audio/ogg": + return AUDIO_OGG; + case "application/json": + return APPLICATION_JSON; + case "application/vnd.openxmlformats-officedocument.presentationml.presentation": + return APPLICATION_OPENXML_PRESENTATION; + case "application/vnd.ms-excel": + return APPLICATION_MS_EXCEL; + case "image/heic": + return IMAGE_HEIC; + case "application/javascript": + return APPLICATION_JAVASCRIPT; + case "audio/oga": + return AUDIO_OGA; + case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": + return APPLICATION_OPENXML_WORD; + case "application/octet-stream": + return APPLICATION_OCTET_STREAM; + case "video/webm": + return VIDEO_WEBM; + case "text/csv": + return TEXT_CSV; + case "application/msword": + return APPLICATION_MSWORD; + case "text/x-typescript": + return TEXT_X_TYPESCRIPT; + default: + return new MediaContentType(Value.UNKNOWN, value); + } + } + + public enum Value { + IMAGE_PNG, + + IMAGE_JPEG, + + IMAGE_JPG, + + IMAGE_WEBP, + + IMAGE_GIF, + + IMAGE_SVG_XML, + + IMAGE_TIFF, + + IMAGE_BMP, + + IMAGE_AVIF, + + IMAGE_HEIC, + + AUDIO_MPEG, + + AUDIO_MP3, + + AUDIO_WAV, + + AUDIO_OGG, + + AUDIO_OGA, + + AUDIO_AAC, + + AUDIO_MP4, + + AUDIO_FLAC, + + AUDIO_OPUS, + + AUDIO_WEBM, + + VIDEO_MP4, + + VIDEO_WEBM, + + VIDEO_OGG, + + VIDEO_MPEG, + + VIDEO_QUICKTIME, + + VIDEO_X_MSVIDEO, + + VIDEO_X_MATROSKA, + + TEXT_PLAIN, + + TEXT_HTML, + + TEXT_CSS, + + TEXT_CSV, + + TEXT_MARKDOWN, + + TEXT_X_PYTHON, + + APPLICATION_JAVASCRIPT, + + TEXT_X_TYPESCRIPT, + + APPLICATION_X_YAML, + + APPLICATION_PDF, + + APPLICATION_MSWORD, + + APPLICATION_MS_EXCEL, + + APPLICATION_OPENXML_SPREADSHEET, + + APPLICATION_ZIP, + + APPLICATION_JSON, + + APPLICATION_XML, + + APPLICATION_OCTET_STREAM, + + APPLICATION_OPENXML_WORD, + + APPLICATION_OPENXML_PRESENTATION, + + APPLICATION_RTF, + + APPLICATION_X_NDJSON, + + APPLICATION_PARQUET, + + APPLICATION_GZIP, + + APPLICATION_X_TAR, + + APPLICATION_X7Z_COMPRESSED, + + UNKNOWN + } + + public interface Visitor { + T visitImagePng(); + + T visitImageJpeg(); + + T visitImageJpg(); + + T visitImageWebp(); + + T visitImageGif(); + + T visitImageSvgXml(); + + T visitImageTiff(); + + T visitImageBmp(); + + T visitImageAvif(); + + T visitImageHeic(); + + T visitAudioMpeg(); + + T visitAudioMp3(); + + T visitAudioWav(); + + T visitAudioOgg(); + + T visitAudioOga(); + + T visitAudioAac(); + + T visitAudioMp4(); + + T visitAudioFlac(); + + T visitAudioOpus(); + + T visitAudioWebm(); + + T visitVideoMp4(); + + T visitVideoWebm(); + + T visitVideoOgg(); + + T visitVideoMpeg(); + + T visitVideoQuicktime(); + + T visitVideoXMsvideo(); + + T visitVideoXMatroska(); + + T visitTextPlain(); + + T visitTextHtml(); + + T visitTextCss(); + + T visitTextCsv(); + + T visitTextMarkdown(); + + T visitTextXPython(); + + T visitApplicationJavascript(); + + T visitTextXTypescript(); + + T visitApplicationXYaml(); + + T visitApplicationPdf(); + + T visitApplicationMsword(); + + T visitApplicationMsExcel(); + + T visitApplicationOpenxmlSpreadsheet(); + + T visitApplicationZip(); + + T visitApplicationJson(); + + T visitApplicationXml(); + + T visitApplicationOctetStream(); + + T visitApplicationOpenxmlWord(); + + T visitApplicationOpenxmlPresentation(); + + T visitApplicationRtf(); + + T visitApplicationXNdjson(); + + T visitApplicationParquet(); + + T visitApplicationGzip(); + + T visitApplicationXTar(); + + T visitApplicationX7ZCompressed(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/media/types/PatchMediaBody.java b/src/main/java/com/langfuse/client/resources/media/types/PatchMediaBody.java index 0860d7a..96d3021 100644 --- a/src/main/java/com/langfuse/client/resources/media/types/PatchMediaBody.java +++ b/src/main/java/com/langfuse/client/resources/media/types/PatchMediaBody.java @@ -110,22 +110,38 @@ public static UploadedAtStage builder() { } public interface UploadedAtStage { + /** + *

        The date and time when the media record was uploaded

        + */ UploadHttpStatusStage uploadedAt(@NotNull OffsetDateTime uploadedAt); Builder from(PatchMediaBody other); } public interface UploadHttpStatusStage { + /** + *

        The HTTP status code of the upload

        + */ _FinalStage uploadHttpStatus(int uploadHttpStatus); } public interface _FinalStage { PatchMediaBody build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The HTTP error message of the upload

        + */ _FinalStage uploadHttpError(Optional uploadHttpError); _FinalStage uploadHttpError(String uploadHttpError); + /** + *

        The time in milliseconds it took to upload the media record

        + */ _FinalStage uploadTimeMs(Optional uploadTimeMs); _FinalStage uploadTimeMs(Integer uploadTimeMs); @@ -159,6 +175,7 @@ public Builder from(PatchMediaBody other) { } /** + *

        The date and time when the media record was uploaded

        *

        The date and time when the media record was uploaded

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -170,6 +187,7 @@ public UploadHttpStatusStage uploadedAt(@NotNull OffsetDateTime uploadedAt) { } /** + *

        The HTTP status code of the upload

        *

        The HTTP status code of the upload

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -190,6 +208,9 @@ public _FinalStage uploadTimeMs(Integer uploadTimeMs) { return this; } + /** + *

        The time in milliseconds it took to upload the media record

        + */ @java.lang.Override @JsonSetter( value = "uploadTimeMs", @@ -210,6 +231,9 @@ public _FinalStage uploadHttpError(String uploadHttpError) { return this; } + /** + *

        The HTTP error message of the upload

        + */ @java.lang.Override @JsonSetter( value = "uploadHttpError", @@ -224,5 +248,17 @@ public _FinalStage uploadHttpError(Optional uploadHttpError) { public PatchMediaBody build() { return new PatchMediaBody(uploadedAt, uploadHttpStatus, uploadHttpError, uploadTimeMs, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/metrics/AsyncMetricsClient.java b/src/main/java/com/langfuse/client/resources/metrics/AsyncMetricsClient.java new file mode 100644 index 0000000..865b5e4 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/metrics/AsyncMetricsClient.java @@ -0,0 +1,48 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.metrics; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.metrics.requests.GetMetricsRequest; +import com.langfuse.client.resources.metrics.types.MetricsResponse; + +public class AsyncMetricsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawMetricsClient rawClient; + + public AsyncMetricsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawMetricsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawMetricsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get metrics from the Langfuse project using a query object. + *

        Consider using the v2 metrics endpoint for better performance.

        + *

        For more details, see the Metrics API documentation.

        + */ + public CompletableFuture metrics(GetMetricsRequest request) { + return this.rawClient.metrics(request).thenApply(response -> response.body()); + } + + /** + * Get metrics from the Langfuse project using a query object. + *

        Consider using the v2 metrics endpoint for better performance.

        + *

        For more details, see the Metrics API documentation.

        + */ + public CompletableFuture metrics(GetMetricsRequest request, + RequestOptions requestOptions) { + return this.rawClient.metrics(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/metrics/AsyncRawMetricsClient.java b/src/main/java/com/langfuse/client/resources/metrics/AsyncRawMetricsClient.java new file mode 100644 index 0000000..dd55236 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/metrics/AsyncRawMetricsClient.java @@ -0,0 +1,122 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.metrics; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.metrics.requests.GetMetricsRequest; +import com.langfuse.client.resources.metrics.types.MetricsResponse; + +public class AsyncRawMetricsClient { + protected final ClientOptions clientOptions; + + public AsyncRawMetricsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get metrics from the Langfuse project using a query object. + *

        Consider using the v2 metrics endpoint for better performance.

        + *

        For more details, see the Metrics API documentation.

        + */ + public CompletableFuture> metrics( + GetMetricsRequest request) { + return metrics(request,null); + } + + /** + * Get metrics from the Langfuse project using a query object. + *

        Consider using the v2 metrics endpoint for better performance.

        + *

        For more details, see the Metrics API documentation.

        + */ + public CompletableFuture> metrics( + GetMetricsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("metrics");QueryStringMapper.addQueryParameter(httpUrl, "query", request.getQuery(), false); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MetricsResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/metrics/MetricsClient.java b/src/main/java/com/langfuse/client/resources/metrics/MetricsClient.java index f195ceb..1185730 100644 --- a/src/main/java/com/langfuse/client/resources/metrics/MetricsClient.java +++ b/src/main/java/com/langfuse/client/resources/metrics/MetricsClient.java @@ -4,35 +4,26 @@ package com.langfuse.client.resources.metrics; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.metrics.requests.GetMetricsRequest; import com.langfuse.client.resources.metrics.types.MetricsResponse; public class MetricsClient { protected final ClientOptions clientOptions; + private final RawMetricsClient rawClient; + public MetricsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawMetricsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawMetricsClient withRawResponse() { + return this.rawClient; } /** @@ -41,7 +32,7 @@ public MetricsClient(ClientOptions clientOptions) { *

        For more details, see the Metrics API documentation.

        */ public MetricsResponse metrics(GetMetricsRequest request) { - return metrics(request,null); + return this.rawClient.metrics(request).body(); } /** @@ -50,42 +41,6 @@ public MetricsResponse metrics(GetMetricsRequest request) { *

        For more details, see the Metrics API documentation.

        */ public MetricsResponse metrics(GetMetricsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("metrics");QueryStringMapper.addQueryParameter(httpUrl, "query", request.getQuery(), false); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MetricsResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.metrics(request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/metrics/RawMetricsClient.java b/src/main/java/com/langfuse/client/resources/metrics/RawMetricsClient.java new file mode 100644 index 0000000..17d5230 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/metrics/RawMetricsClient.java @@ -0,0 +1,98 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.metrics; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.metrics.requests.GetMetricsRequest; +import com.langfuse.client.resources.metrics.types.MetricsResponse; + +public class RawMetricsClient { + protected final ClientOptions clientOptions; + + public RawMetricsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get metrics from the Langfuse project using a query object. + *

        Consider using the v2 metrics endpoint for better performance.

        + *

        For more details, see the Metrics API documentation.

        + */ + public LangfuseClientHttpResponse metrics(GetMetricsRequest request) { + return metrics(request,null); + } + + /** + * Get metrics from the Langfuse project using a query object. + *

        Consider using the v2 metrics endpoint for better performance.

        + *

        For more details, see the Metrics API documentation.

        + */ + public LangfuseClientHttpResponse metrics(GetMetricsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("metrics");QueryStringMapper.addQueryParameter(httpUrl, "query", request.getQuery(), false); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MetricsResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/metrics/requests/GetMetricsRequest.java b/src/main/java/com/langfuse/client/resources/metrics/requests/GetMetricsRequest.java index 6a0423e..f00252c 100644 --- a/src/main/java/com/langfuse/client/resources/metrics/requests/GetMetricsRequest.java +++ b/src/main/java/com/langfuse/client/resources/metrics/requests/GetMetricsRequest.java @@ -110,6 +110,48 @@ public static QueryStage builder() { } public interface QueryStage { + /** + *

        JSON string containing the query parameters with the following structure:

        + *
        {
        +     *   "view": string,           // Required. One of "traces", "observations", "scores-numeric", "scores-categorical"
        +     *   "dimensions": [           // Optional. Default: []
        +     *     {
        +     *       "field": string       // Field to group by, e.g. "name", "userId", "sessionId"
        +     *     }
        +     *   ],
        +     *   "metrics": [              // Required. At least one metric must be provided
        +     *     {
        +     *       "measure": string,    // What to measure, e.g. "count", "latency", "value"
        +     *       "aggregation": string // How to aggregate, e.g. "count", "sum", "avg", "p95", "histogram"
        +     *     }
        +     *   ],
        +     *   "filters": [              // Optional. Default: []
        +     *     {
        +     *       "column": string,     // Column to filter on
        +     *       "operator": string,   // Operator, e.g. "=", ">", "<", "contains"
        +     *       "value": any,         // Value to compare against
        +     *       "type": string,       // Data type, e.g. "string", "number", "stringObject"
        +     *       "key": string         // Required only when filtering on metadata
        +     *     }
        +     *   ],
        +     *   "timeDimension": {        // Optional. Default: null. If provided, results will be grouped by time
        +     *     "granularity": string   // One of "minute", "hour", "day", "week", "month", "auto"
        +     *   },
        +     *   "fromTimestamp": string,  // Required. ISO datetime string for start of time range
        +     *   "toTimestamp": string,    // Required. ISO datetime string for end of time range
        +     *   "orderBy": [              // Optional. Default: null
        +     *     {
        +     *       "field": string,      // Field to order by
        +     *       "direction": string   // "asc" or "desc"
        +     *     }
        +     *   ],
        +     *   "config": {               // Optional. Query-specific configuration
        +     *     "bins": number,         // Optional. Number of bins for histogram (1-100), default: 10
        +     *     "row_limit": number     // Optional. Row limit for results (1-1000)
        +     *   }
        +     * }
        +     * 
        + */ _FinalStage query(@NotNull String query); Builder from(GetMetricsRequest other); @@ -117,6 +159,10 @@ public interface QueryStage { public interface _FinalStage { GetMetricsRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -138,6 +184,46 @@ public Builder from(GetMetricsRequest other) { } /** + *

        JSON string containing the query parameters with the following structure:

        + *
        {
        +     *   "view": string,           // Required. One of "traces", "observations", "scores-numeric", "scores-categorical"
        +     *   "dimensions": [           // Optional. Default: []
        +     *     {
        +     *       "field": string       // Field to group by, e.g. "name", "userId", "sessionId"
        +     *     }
        +     *   ],
        +     *   "metrics": [              // Required. At least one metric must be provided
        +     *     {
        +     *       "measure": string,    // What to measure, e.g. "count", "latency", "value"
        +     *       "aggregation": string // How to aggregate, e.g. "count", "sum", "avg", "p95", "histogram"
        +     *     }
        +     *   ],
        +     *   "filters": [              // Optional. Default: []
        +     *     {
        +     *       "column": string,     // Column to filter on
        +     *       "operator": string,   // Operator, e.g. "=", ">", "<", "contains"
        +     *       "value": any,         // Value to compare against
        +     *       "type": string,       // Data type, e.g. "string", "number", "stringObject"
        +     *       "key": string         // Required only when filtering on metadata
        +     *     }
        +     *   ],
        +     *   "timeDimension": {        // Optional. Default: null. If provided, results will be grouped by time
        +     *     "granularity": string   // One of "minute", "hour", "day", "week", "month", "auto"
        +     *   },
        +     *   "fromTimestamp": string,  // Required. ISO datetime string for start of time range
        +     *   "toTimestamp": string,    // Required. ISO datetime string for end of time range
        +     *   "orderBy": [              // Optional. Default: null
        +     *     {
        +     *       "field": string,      // Field to order by
        +     *       "direction": string   // "asc" or "desc"
        +     *     }
        +     *   ],
        +     *   "config": {               // Optional. Query-specific configuration
        +     *     "bins": number,         // Optional. Number of bins for histogram (1-100), default: 10
        +     *     "row_limit": number     // Optional. Row limit for results (1-1000)
        +     *   }
        +     * }
        +     * 
        *

        JSON string containing the query parameters with the following structure:

        *
        {
              *   "view": string,           // Required. One of "traces", "observations", "scores-numeric", "scores-categorical"
        @@ -191,5 +277,17 @@ public _FinalStage query(@NotNull String query) {
             public GetMetricsRequest build() {
               return new GetMetricsRequest(query, additionalProperties);
             }
        +
        +    @java.lang.Override
        +    public Builder additionalProperty(String key, Object value) {
        +      this.additionalProperties.put(key, value);
        +      return this;
        +    }
        +
        +    @java.lang.Override
        +    public Builder additionalProperties(Map additionalProperties) {
        +      this.additionalProperties.putAll(additionalProperties);
        +      return this;
        +    }
           }
         }
        diff --git a/src/main/java/com/langfuse/client/resources/metrics/types/MetricsResponse.java b/src/main/java/com/langfuse/client/resources/metrics/types/MetricsResponse.java
        index 2f3dacb..8276aa9 100644
        --- a/src/main/java/com/langfuse/client/resources/metrics/types/MetricsResponse.java
        +++ b/src/main/java/com/langfuse/client/resources/metrics/types/MetricsResponse.java
        @@ -92,13 +92,20 @@ public Builder from(MetricsResponse other) {
               return this;
             }
         
        +    /**
        +     * 

        The metrics data. Each item in the list contains the metric values and dimensions requested in the query. + * Format varies based on the query parameters. + * Histograms will return an array with [lower, upper, height] tuples.

        + */ @JsonSetter( value = "data", nulls = Nulls.SKIP ) public Builder data(List> data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -108,12 +115,24 @@ public Builder addData(Map data) { } public Builder addAllData(List> data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } public MetricsResponse build() { return new MetricsResponse(data, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/metricsv2/AsyncMetricsV2Client.java b/src/main/java/com/langfuse/client/resources/metricsv2/AsyncMetricsV2Client.java new file mode 100644 index 0000000..52c3803 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/metricsv2/AsyncMetricsV2Client.java @@ -0,0 +1,44 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.metricsv2; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.metricsv2.requests.GetMetricsV2Request; +import com.langfuse.client.resources.metricsv2.types.MetricsV2Response; + +public class AsyncMetricsV2Client { + protected final ClientOptions clientOptions; + + private final AsyncRawMetricsV2Client rawClient; + + public AsyncMetricsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawMetricsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawMetricsV2Client withRawResponse() { + return this.rawClient; + } + + /** + * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. + */ + public CompletableFuture metrics(GetMetricsV2Request request) { + return this.rawClient.metrics(request).thenApply(response -> response.body()); + } + + /** + * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. + */ + public CompletableFuture metrics(GetMetricsV2Request request, + RequestOptions requestOptions) { + return this.rawClient.metrics(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/metricsv2/AsyncRawMetricsV2Client.java b/src/main/java/com/langfuse/client/resources/metricsv2/AsyncRawMetricsV2Client.java new file mode 100644 index 0000000..910c7a4 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/metricsv2/AsyncRawMetricsV2Client.java @@ -0,0 +1,118 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.metricsv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.metricsv2.requests.GetMetricsV2Request; +import com.langfuse.client.resources.metricsv2.types.MetricsV2Response; + +public class AsyncRawMetricsV2Client { + protected final ClientOptions clientOptions; + + public AsyncRawMetricsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. + */ + public CompletableFuture> metrics( + GetMetricsV2Request request) { + return metrics(request,null); + } + + /** + * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. + */ + public CompletableFuture> metrics( + GetMetricsV2Request request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/metrics");QueryStringMapper.addQueryParameter(httpUrl, "query", request.getQuery(), false); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MetricsV2Response.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/metricsv2/MetricsV2Client.java b/src/main/java/com/langfuse/client/resources/metricsv2/MetricsV2Client.java index 03b29a4..1ba4329 100644 --- a/src/main/java/com/langfuse/client/resources/metricsv2/MetricsV2Client.java +++ b/src/main/java/com/langfuse/client/resources/metricsv2/MetricsV2Client.java @@ -4,84 +4,39 @@ package com.langfuse.client.resources.metricsv2; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.metricsv2.requests.GetMetricsV2Request; import com.langfuse.client.resources.metricsv2.types.MetricsV2Response; public class MetricsV2Client { protected final ClientOptions clientOptions; + private final RawMetricsV2Client rawClient; + public MetricsV2Client(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawMetricsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawMetricsV2Client withRawResponse() { + return this.rawClient; } /** * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. */ public MetricsV2Response metrics(GetMetricsV2Request request) { - return metrics(request,null); + return this.rawClient.metrics(request).body(); } /** * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. */ public MetricsV2Response metrics(GetMetricsV2Request request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("v2/metrics");QueryStringMapper.addQueryParameter(httpUrl, "query", request.getQuery(), false); - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MetricsV2Response.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.metrics(request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/metricsv2/RawMetricsV2Client.java b/src/main/java/com/langfuse/client/resources/metricsv2/RawMetricsV2Client.java new file mode 100644 index 0000000..c4c83ac --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/metricsv2/RawMetricsV2Client.java @@ -0,0 +1,94 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.metricsv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.metricsv2.requests.GetMetricsV2Request; +import com.langfuse.client.resources.metricsv2.types.MetricsV2Response; + +public class RawMetricsV2Client { + protected final ClientOptions clientOptions; + + public RawMetricsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. + */ + public LangfuseClientHttpResponse metrics(GetMetricsV2Request request) { + return metrics(request,null); + } + + /** + * Get metrics from the Langfuse project using a query object. V2 endpoint with optimized performance. + */ + public LangfuseClientHttpResponse metrics(GetMetricsV2Request request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/metrics");QueryStringMapper.addQueryParameter(httpUrl, "query", request.getQuery(), false); + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MetricsV2Response.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/metricsv2/requests/GetMetricsV2Request.java b/src/main/java/com/langfuse/client/resources/metricsv2/requests/GetMetricsV2Request.java index 3bf06c7..86dd5c4 100644 --- a/src/main/java/com/langfuse/client/resources/metricsv2/requests/GetMetricsV2Request.java +++ b/src/main/java/com/langfuse/client/resources/metricsv2/requests/GetMetricsV2Request.java @@ -118,6 +118,56 @@ public static QueryStage builder() { } public interface QueryStage { + /** + *

        JSON string containing the query parameters with the following structure:

        + *
        {
        +     *   "view": string,           // Required. One of "observations", "scores-numeric", "scores-categorical"
        +     *   "dimensions": [           // Optional. Default: []
        +     *     {
        +     *       "field": string       // Field to group by (see available dimensions above)
        +     *     }
        +     *   ],
        +     *   "metrics": [              // Required. At least one metric must be provided
        +     *     {
        +     *       "measure": string,    // What to measure (see available measures above)
        +     *       "aggregation": string // How to aggregate: "sum", "avg", "count", "max", "min", "p50", "p75", "p90", "p95", "p99", "histogram"
        +     *     }
        +     *   ],
        +     *   "filters": [              // Optional. Default: []
        +     *     {
        +     *       "column": string,     // Column to filter on (any dimension field)
        +     *       "operator": string,   // Operator based on type:
        +     *                             // - datetime: ">", "<", ">=", "<="
        +     *                             // - string: "=", "contains", "does not contain", "starts with", "ends with"
        +     *                             // - stringOptions: "any of", "none of"
        +     *                             // - arrayOptions: "any of", "none of", "all of"
        +     *                             // - number: "=", ">", "<", ">=", "<="
        +     *                             // - stringObject/numberObject: same as string/number with required "key"
        +     *                             // - boolean: "=", "<>"
        +     *                             // - null: "is null", "is not null"
        +     *       "value": any,         // Value to compare against
        +     *       "type": string,       // Data type: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "boolean", "null"
        +     *       "key": string         // Required only for stringObject/numberObject types (e.g., metadata filtering)
        +     *     }
        +     *   ],
        +     *   "timeDimension": {        // Optional. Default: null. If provided, results will be grouped by time
        +     *     "granularity": string   // One of "auto", "minute", "hour", "day", "week", "month"
        +     *   },
        +     *   "fromTimestamp": string,  // Required. ISO datetime string for start of time range
        +     *   "toTimestamp": string,    // Required. ISO datetime string for end of time range (must be after fromTimestamp)
        +     *   "orderBy": [              // Optional. Default: null
        +     *     {
        +     *       "field": string,      // Field to order by (dimension or metric alias)
        +     *       "direction": string   // "asc" or "desc"
        +     *     }
        +     *   ],
        +     *   "config": {               // Optional. Query-specific configuration
        +     *     "bins": number,         // Optional. Number of bins for histogram aggregation (1-100), default: 10
        +     *     "row_limit": number     // Optional. Maximum number of rows to return (1-1000), default: 100
        +     *   }
        +     * }
        +     * 
        + */ _FinalStage query(@NotNull String query); Builder from(GetMetricsV2Request other); @@ -125,6 +175,10 @@ public interface QueryStage { public interface _FinalStage { GetMetricsV2Request build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -146,6 +200,54 @@ public Builder from(GetMetricsV2Request other) { } /** + *

        JSON string containing the query parameters with the following structure:

        + *
        {
        +     *   "view": string,           // Required. One of "observations", "scores-numeric", "scores-categorical"
        +     *   "dimensions": [           // Optional. Default: []
        +     *     {
        +     *       "field": string       // Field to group by (see available dimensions above)
        +     *     }
        +     *   ],
        +     *   "metrics": [              // Required. At least one metric must be provided
        +     *     {
        +     *       "measure": string,    // What to measure (see available measures above)
        +     *       "aggregation": string // How to aggregate: "sum", "avg", "count", "max", "min", "p50", "p75", "p90", "p95", "p99", "histogram"
        +     *     }
        +     *   ],
        +     *   "filters": [              // Optional. Default: []
        +     *     {
        +     *       "column": string,     // Column to filter on (any dimension field)
        +     *       "operator": string,   // Operator based on type:
        +     *                             // - datetime: ">", "<", ">=", "<="
        +     *                             // - string: "=", "contains", "does not contain", "starts with", "ends with"
        +     *                             // - stringOptions: "any of", "none of"
        +     *                             // - arrayOptions: "any of", "none of", "all of"
        +     *                             // - number: "=", ">", "<", ">=", "<="
        +     *                             // - stringObject/numberObject: same as string/number with required "key"
        +     *                             // - boolean: "=", "<>"
        +     *                             // - null: "is null", "is not null"
        +     *       "value": any,         // Value to compare against
        +     *       "type": string,       // Data type: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "boolean", "null"
        +     *       "key": string         // Required only for stringObject/numberObject types (e.g., metadata filtering)
        +     *     }
        +     *   ],
        +     *   "timeDimension": {        // Optional. Default: null. If provided, results will be grouped by time
        +     *     "granularity": string   // One of "auto", "minute", "hour", "day", "week", "month"
        +     *   },
        +     *   "fromTimestamp": string,  // Required. ISO datetime string for start of time range
        +     *   "toTimestamp": string,    // Required. ISO datetime string for end of time range (must be after fromTimestamp)
        +     *   "orderBy": [              // Optional. Default: null
        +     *     {
        +     *       "field": string,      // Field to order by (dimension or metric alias)
        +     *       "direction": string   // "asc" or "desc"
        +     *     }
        +     *   ],
        +     *   "config": {               // Optional. Query-specific configuration
        +     *     "bins": number,         // Optional. Number of bins for histogram aggregation (1-100), default: 10
        +     *     "row_limit": number     // Optional. Maximum number of rows to return (1-1000), default: 100
        +     *   }
        +     * }
        +     * 
        *

        JSON string containing the query parameters with the following structure:

        *
        {
              *   "view": string,           // Required. One of "observations", "scores-numeric", "scores-categorical"
        @@ -207,5 +309,17 @@ public _FinalStage query(@NotNull String query) {
             public GetMetricsV2Request build() {
               return new GetMetricsV2Request(query, additionalProperties);
             }
        +
        +    @java.lang.Override
        +    public Builder additionalProperty(String key, Object value) {
        +      this.additionalProperties.put(key, value);
        +      return this;
        +    }
        +
        +    @java.lang.Override
        +    public Builder additionalProperties(Map additionalProperties) {
        +      this.additionalProperties.putAll(additionalProperties);
        +      return this;
        +    }
           }
         }
        diff --git a/src/main/java/com/langfuse/client/resources/metricsv2/types/MetricsV2Response.java b/src/main/java/com/langfuse/client/resources/metricsv2/types/MetricsV2Response.java
        index 1da4efa..3c95f10 100644
        --- a/src/main/java/com/langfuse/client/resources/metricsv2/types/MetricsV2Response.java
        +++ b/src/main/java/com/langfuse/client/resources/metricsv2/types/MetricsV2Response.java
        @@ -92,13 +92,20 @@ public Builder from(MetricsV2Response other) {
               return this;
             }
         
        +    /**
        +     * 

        The metrics data. Each item in the list contains the metric values and dimensions requested in the query. + * Format varies based on the query parameters. + * Histograms will return an array with [lower, upper, height] tuples.

        + */ @JsonSetter( value = "data", nulls = Nulls.SKIP ) public Builder data(List> data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -108,12 +115,24 @@ public Builder addData(Map data) { } public Builder addAllData(List> data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } public MetricsV2Response build() { return new MetricsV2Response(data, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/models/AsyncModelsClient.java b/src/main/java/com/langfuse/client/resources/models/AsyncModelsClient.java new file mode 100644 index 0000000..fd8ea97 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/models/AsyncModelsClient.java @@ -0,0 +1,105 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.models; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.Model; +import com.langfuse.client.resources.models.requests.GetModelsRequest; +import com.langfuse.client.resources.models.types.CreateModelRequest; +import com.langfuse.client.resources.models.types.PaginatedModels; + +public class AsyncModelsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawModelsClient rawClient; + + public AsyncModelsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawModelsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawModelsClient withRawResponse() { + return this.rawClient; + } + + /** + * Create a model + */ + public CompletableFuture create(CreateModelRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a model + */ + public CompletableFuture create(CreateModelRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all models + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * Get all models + */ + public CompletableFuture list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all models + */ + public CompletableFuture list(GetModelsRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * Get all models + */ + public CompletableFuture list(GetModelsRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a model + */ + public CompletableFuture get(String id) { + return this.rawClient.get(id).thenApply(response -> response.body()); + } + + /** + * Get a model + */ + public CompletableFuture get(String id, RequestOptions requestOptions) { + return this.rawClient.get(id, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public CompletableFuture delete(String id) { + return this.rawClient.delete(id).thenApply(response -> response.body()); + } + + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public CompletableFuture delete(String id, RequestOptions requestOptions) { + return this.rawClient.delete(id, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/models/AsyncRawModelsClient.java b/src/main/java/com/langfuse/client/resources/models/AsyncRawModelsClient.java new file mode 100644 index 0000000..cc5e74b --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/models/AsyncRawModelsClient.java @@ -0,0 +1,372 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.models; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Model; +import com.langfuse.client.resources.models.requests.GetModelsRequest; +import com.langfuse.client.resources.models.types.CreateModelRequest; +import com.langfuse.client.resources.models.types.PaginatedModels; + +public class AsyncRawModelsClient { + protected final ClientOptions clientOptions; + + public AsyncRawModelsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a model + */ + public CompletableFuture> create(CreateModelRequest request) { + return create(request,null); + } + + /** + * Create a model + */ + public CompletableFuture> create(CreateModelRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Model.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get all models + */ + public CompletableFuture> list() { + return list(GetModelsRequest.builder().build()); + } + + /** + * Get all models + */ + public CompletableFuture> list( + RequestOptions requestOptions) { + return list(GetModelsRequest.builder().build(),requestOptions); + } + + /** + * Get all models + */ + public CompletableFuture> list( + GetModelsRequest request) { + return list(request,null); + } + + /** + * Get all models + */ + public CompletableFuture> list( + GetModelsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedModels.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a model + */ + public CompletableFuture> get(String id) { + return get(id,null); + } + + /** + * Get a model + */ + public CompletableFuture> get(String id, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Model.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public CompletableFuture> delete(String id) { + return delete(id,null); + } + + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public CompletableFuture> delete(String id, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/models/ModelsClient.java b/src/main/java/com/langfuse/client/resources/models/ModelsClient.java index 5b0cad8..782dfdf 100644 --- a/src/main/java/com/langfuse/client/resources/models/ModelsClient.java +++ b/src/main/java/com/langfuse/client/resources/models/ModelsClient.java @@ -4,29 +4,9 @@ package com.langfuse.client.resources.models; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.Model; import com.langfuse.client.resources.models.requests.GetModelsRequest; import com.langfuse.client.resources.models.types.CreateModelRequest; @@ -35,230 +15,87 @@ public class ModelsClient { protected final ClientOptions clientOptions; + private final RawModelsClient rawClient; + public ModelsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawModelsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawModelsClient withRawResponse() { + return this.rawClient; } /** * Create a model */ public Model create(CreateModelRequest request) { - return create(request,null); + return this.rawClient.create(request).body(); } /** * Create a model */ public Model create(CreateModelRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("models") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Model.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * Get all models */ public PaginatedModels list() { - return list(GetModelsRequest.builder().build()); + return this.rawClient.list().body(); + } + + /** + * Get all models + */ + public PaginatedModels list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).body(); } /** * Get all models */ public PaginatedModels list(GetModelsRequest request) { - return list(request,null); + return this.rawClient.list(request).body(); } /** * Get all models */ public PaginatedModels list(GetModelsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("models");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedModels.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.list(request, requestOptions).body(); + } - /** - * Get a model - */ - public Model get(String id) { - return get(id,null); - } + /** + * Get a model + */ + public Model get(String id) { + return this.rawClient.get(id).body(); + } - /** - * Get a model - */ - public Model get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("models") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Model.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a model + */ + public Model get(String id, RequestOptions requestOptions) { + return this.rawClient.get(id, requestOptions).body(); + } - /** - * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. - */ - public void delete(String id) { - delete(id,null); - } + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public void delete(String id) { + this.rawClient.delete(id).body(); + } - /** - * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. - */ - public void delete(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("models") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public void delete(String id, RequestOptions requestOptions) { + this.rawClient.delete(id, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/models/RawModelsClient.java b/src/main/java/com/langfuse/client/resources/models/RawModelsClient.java new file mode 100644 index 0000000..07399c1 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/models/RawModelsClient.java @@ -0,0 +1,291 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.models; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import java.lang.Void; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Model; +import com.langfuse.client.resources.models.requests.GetModelsRequest; +import com.langfuse.client.resources.models.types.CreateModelRequest; +import com.langfuse.client.resources.models.types.PaginatedModels; + +public class RawModelsClient { + protected final ClientOptions clientOptions; + + public RawModelsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a model + */ + public LangfuseClientHttpResponse create(CreateModelRequest request) { + return create(request,null); + } + + /** + * Create a model + */ + public LangfuseClientHttpResponse create(CreateModelRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Model.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get all models + */ + public LangfuseClientHttpResponse list() { + return list(GetModelsRequest.builder().build()); + } + + /** + * Get all models + */ + public LangfuseClientHttpResponse list(RequestOptions requestOptions) { + return list(GetModelsRequest.builder().build(),requestOptions); + } + + /** + * Get all models + */ + public LangfuseClientHttpResponse list(GetModelsRequest request) { + return list(request,null); + } + + /** + * Get all models + */ + public LangfuseClientHttpResponse list(GetModelsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedModels.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a model + */ + public LangfuseClientHttpResponse get(String id) { + return get(id,null); + } + + /** + * Get a model + */ + public LangfuseClientHttpResponse get(String id, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Model.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public LangfuseClientHttpResponse delete(String id) { + return delete(id,null); + } + + /** + * Delete a model. Cannot delete models managed by Langfuse. You can create your own definition with the same modelName to override the definition though. + */ + public LangfuseClientHttpResponse delete(String id, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("models") + .addPathSegment(id);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/models/requests/GetModelsRequest.java b/src/main/java/com/langfuse/client/resources/models/requests/GetModelsRequest.java index 36a9256..aebc64a 100644 --- a/src/main/java/com/langfuse/client/resources/models/requests/GetModelsRequest.java +++ b/src/main/java/com/langfuse/client/resources/models/requests/GetModelsRequest.java @@ -104,6 +104,9 @@ public Builder from(GetModelsRequest other) { return this; } + /** + *

        page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder page(Integer page) { return this; } + /** + *

        limit of items per page

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder limit(Integer limit) { public GetModelsRequest build() { return new GetModelsRequest(page, limit, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/models/types/CreateModelRequest.java b/src/main/java/com/langfuse/client/resources/models/types/CreateModelRequest.java index f09014b..05afcc9 100644 --- a/src/main/java/com/langfuse/client/resources/models/types/CreateModelRequest.java +++ b/src/main/java/com/langfuse/client/resources/models/types/CreateModelRequest.java @@ -201,46 +201,100 @@ public static ModelNameStage builder() { } public interface ModelNameStage { + /** + *

        Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime

        + */ MatchPatternStage modelName(@NotNull String modelName); Builder from(CreateModelRequest other); } public interface MatchPatternStage { + /** + *

        Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use (?i)^modelname$

        + */ _FinalStage matchPattern(@NotNull String matchPattern); } public interface _FinalStage { CreateModelRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Apply only to generations which are newer than this ISO date.

        + */ _FinalStage startDate(Optional startDate); _FinalStage startDate(OffsetDateTime startDate); + /** + *

        Unit used by this model.

        + */ _FinalStage unit(Optional unit); _FinalStage unit(ModelUsageUnit unit); + /** + *

        Deprecated. Use 'pricingTiers' instead. Price (USD) per input unit. Creates a default tier if pricingTiers not provided.

        + */ _FinalStage inputPrice(Optional inputPrice); _FinalStage inputPrice(Double inputPrice); + /** + *

        Deprecated. Use 'pricingTiers' instead. Price (USD) per output unit. Creates a default tier if pricingTiers not provided.

        + */ _FinalStage outputPrice(Optional outputPrice); _FinalStage outputPrice(Double outputPrice); + /** + *

        Deprecated. Use 'pricingTiers' instead. Price (USD) per total units. Cannot be set if input or output price is set. Creates a default tier if pricingTiers not provided.

        + */ _FinalStage totalPrice(Optional totalPrice); _FinalStage totalPrice(Double totalPrice); + /** + *

        Optional. Array of pricing tiers for this model.

        + *

        Use pricing tiers for all models - both those with threshold-based pricing variations and those with simple flat pricing:

        + *
          + *
        • + *

          For models with standard flat pricing: Create a single default tier with your prices + * (e.g., one tier with isDefault=true, priority=0, conditions=[], and your standard prices)

          + *
        • + *
        • + *

          For models with threshold-based pricing: Create a default tier plus additional conditional tiers + * (e.g., default tier for standard usage + high-volume tier for usage above certain thresholds)

          + *
        • + *
        + *

        Requirements:

        + *
          + *
        • Cannot be provided with flat prices (inputPrice/outputPrice/totalPrice) - use one approach or the other
        • + *
        • Must include exactly one default tier with isDefault=true, priority=0, and conditions=[]
        • + *
        • All tier names and priorities must be unique within the model
        • + *
        • Each tier must define at least one price
        • + *
        + *

        If omitted, you must provide flat prices instead (inputPrice/outputPrice/totalPrice), + * which will automatically create a single default tier named "Standard".

        + */ _FinalStage pricingTiers(Optional> pricingTiers); _FinalStage pricingTiers(List pricingTiers); + /** + *

        Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.

        + */ _FinalStage tokenizerId(Optional tokenizerId); _FinalStage tokenizerId(String tokenizerId); + /** + *

        Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.

        + */ _FinalStage tokenizerConfig(Optional tokenizerConfig); _FinalStage tokenizerConfig(Object tokenizerConfig); @@ -292,6 +346,7 @@ public Builder from(CreateModelRequest other) { } /** + *

        Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime

        *

        Name of the model definition. If multiple with the same name exist, they are applied in the following order: (1) custom over built-in, (2) newest according to startTime where model.startTime<observation.startTime

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -303,6 +358,7 @@ public MatchPatternStage modelName(@NotNull String modelName) { } /** + *

        Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use (?i)^modelname$

        *

        Regex pattern which matches this model definition to generation.model. Useful in case of fine-tuned models. If you want to exact match, use (?i)^modelname$

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -323,6 +379,9 @@ public _FinalStage tokenizerConfig(Object tokenizerConfig) { return this; } + /** + *

        Optional. Configuration for the selected tokenizer. Needs to be JSON. See docs for more details.

        + */ @java.lang.Override @JsonSetter( value = "tokenizerConfig", @@ -343,6 +402,9 @@ public _FinalStage tokenizerId(String tokenizerId) { return this; } + /** + *

        Optional. Tokenizer to be applied to observations which match to this model. See docs for more details.

        + */ @java.lang.Override @JsonSetter( value = "tokenizerId", @@ -383,6 +445,29 @@ public _FinalStage pricingTiers(List pricingTiers) { return this; } + /** + *

        Optional. Array of pricing tiers for this model.

        + *

        Use pricing tiers for all models - both those with threshold-based pricing variations and those with simple flat pricing:

        + *
          + *
        • + *

          For models with standard flat pricing: Create a single default tier with your prices + * (e.g., one tier with isDefault=true, priority=0, conditions=[], and your standard prices)

          + *
        • + *
        • + *

          For models with threshold-based pricing: Create a default tier plus additional conditional tiers + * (e.g., default tier for standard usage + high-volume tier for usage above certain thresholds)

          + *
        • + *
        + *

        Requirements:

        + *
          + *
        • Cannot be provided with flat prices (inputPrice/outputPrice/totalPrice) - use one approach or the other
        • + *
        • Must include exactly one default tier with isDefault=true, priority=0, and conditions=[]
        • + *
        • All tier names and priorities must be unique within the model
        • + *
        • Each tier must define at least one price
        • + *
        + *

        If omitted, you must provide flat prices instead (inputPrice/outputPrice/totalPrice), + * which will automatically create a single default tier named "Standard".

        + */ @java.lang.Override @JsonSetter( value = "pricingTiers", @@ -403,6 +488,9 @@ public _FinalStage totalPrice(Double totalPrice) { return this; } + /** + *

        Deprecated. Use 'pricingTiers' instead. Price (USD) per total units. Cannot be set if input or output price is set. Creates a default tier if pricingTiers not provided.

        + */ @java.lang.Override @JsonSetter( value = "totalPrice", @@ -423,6 +511,9 @@ public _FinalStage outputPrice(Double outputPrice) { return this; } + /** + *

        Deprecated. Use 'pricingTiers' instead. Price (USD) per output unit. Creates a default tier if pricingTiers not provided.

        + */ @java.lang.Override @JsonSetter( value = "outputPrice", @@ -443,6 +534,9 @@ public _FinalStage inputPrice(Double inputPrice) { return this; } + /** + *

        Deprecated. Use 'pricingTiers' instead. Price (USD) per input unit. Creates a default tier if pricingTiers not provided.

        + */ @java.lang.Override @JsonSetter( value = "inputPrice", @@ -463,6 +557,9 @@ public _FinalStage unit(ModelUsageUnit unit) { return this; } + /** + *

        Unit used by this model.

        + */ @java.lang.Override @JsonSetter( value = "unit", @@ -483,6 +580,9 @@ public _FinalStage startDate(OffsetDateTime startDate) { return this; } + /** + *

        Apply only to generations which are newer than this ISO date.

        + */ @java.lang.Override @JsonSetter( value = "startDate", @@ -497,5 +597,17 @@ public _FinalStage startDate(Optional startDate) { public CreateModelRequest build() { return new CreateModelRequest(modelName, matchPattern, startDate, unit, inputPrice, outputPrice, totalPrice, pricingTiers, tokenizerId, tokenizerConfig, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/models/types/PaginatedModels.java b/src/main/java/com/langfuse/client/resources/models/types/PaginatedModels.java index 9ddac87..40c2959 100644 --- a/src/main/java/com/langfuse/client/resources/models/types/PaginatedModels.java +++ b/src/main/java/com/langfuse/client/resources/models/types/PaginatedModels.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedModels build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(Model data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(Model data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public PaginatedModels build() { return new PaginatedModels(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/observations/AsyncObservationsClient.java b/src/main/java/com/langfuse/client/resources/observations/AsyncObservationsClient.java new file mode 100644 index 0000000..730ddc7 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/observations/AsyncObservationsClient.java @@ -0,0 +1,79 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.observations; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.ObservationsView; +import com.langfuse.client.resources.observations.requests.GetObservationsRequest; +import com.langfuse.client.resources.observations.types.ObservationsViews; + +public class AsyncObservationsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawObservationsClient rawClient; + + public AsyncObservationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawObservationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawObservationsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get a observation + */ + public CompletableFuture get(String observationId) { + return this.rawClient.get(observationId).thenApply(response -> response.body()); + } + + /** + * Get a observation + */ + public CompletableFuture get(String observationId, + RequestOptions requestOptions) { + return this.rawClient.get(observationId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture getMany() { + return this.rawClient.getMany().thenApply(response -> response.body()); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture getMany(RequestOptions requestOptions) { + return this.rawClient.getMany(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture getMany(GetObservationsRequest request) { + return this.rawClient.getMany(request).thenApply(response -> response.body()); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture getMany(GetObservationsRequest request, + RequestOptions requestOptions) { + return this.rawClient.getMany(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/observations/AsyncRawObservationsClient.java b/src/main/java/com/langfuse/client/resources/observations/AsyncRawObservationsClient.java new file mode 100644 index 0000000..83ff355 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/observations/AsyncRawObservationsClient.java @@ -0,0 +1,250 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.observations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.ObservationsView; +import com.langfuse.client.resources.observations.requests.GetObservationsRequest; +import com.langfuse.client.resources.observations.types.ObservationsViews; + +public class AsyncRawObservationsClient { + protected final ClientOptions clientOptions; + + public AsyncRawObservationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a observation + */ + public CompletableFuture> get(String observationId) { + return get(observationId,null); + } + + /** + * Get a observation + */ + public CompletableFuture> get(String observationId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("observations") + .addPathSegment(observationId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ObservationsView.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture> getMany() { + return getMany(GetObservationsRequest.builder().build()); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture> getMany( + RequestOptions requestOptions) { + return getMany(GetObservationsRequest.builder().build(),requestOptions); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture> getMany( + GetObservationsRequest request) { + return getMany(request,null); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public CompletableFuture> getMany( + GetObservationsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("observations");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType().get(), false); + } + if (request.getTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); + } + if (request.getLevel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "level", request.getLevel().get(), false); + } + if (request.getParentObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "parentObservationId", request.getParentObservationId().get(), false); + } + if (request.getFromStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromStartTime", request.getFromStartTime().get(), false); + } + if (request.getToStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toStartTime", request.getToStartTime().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ObservationsViews.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/observations/ObservationsClient.java b/src/main/java/com/langfuse/client/resources/observations/ObservationsClient.java index dd22514..c9ef464 100644 --- a/src/main/java/com/langfuse/client/resources/observations/ObservationsClient.java +++ b/src/main/java/com/langfuse/client/resources/observations/ObservationsClient.java @@ -4,27 +4,9 @@ package com.langfuse.client.resources.observations; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.ObservationsView; import com.langfuse.client.resources.observations.requests.GetObservationsRequest; import com.langfuse.client.resources.observations.types.ObservationsViews; @@ -32,60 +14,32 @@ public class ObservationsClient { protected final ClientOptions clientOptions; + private final RawObservationsClient rawClient; + public ObservationsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawObservationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawObservationsClient withRawResponse() { + return this.rawClient; } /** * Get a observation */ public ObservationsView get(String observationId) { - return get(observationId,null); + return this.rawClient.get(observationId).body(); } /** * Get a observation */ public ObservationsView get(String observationId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("observations") - .addPathSegment(observationId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ObservationsView.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.get(observationId, requestOptions).body(); } /** @@ -93,7 +47,15 @@ public ObservationsView get(String observationId, RequestOptions requestOptions) *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        */ public ObservationsViews getMany() { - return getMany(GetObservationsRequest.builder().build()); + return this.rawClient.getMany().body(); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public ObservationsViews getMany(RequestOptions requestOptions) { + return this.rawClient.getMany(requestOptions).body(); } /** @@ -101,7 +63,7 @@ public ObservationsViews getMany() { *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        */ public ObservationsViews getMany(GetObservationsRequest request) { - return getMany(request,null); + return this.rawClient.getMany(request).body(); } /** @@ -109,80 +71,6 @@ public ObservationsViews getMany(GetObservationsRequest request) { *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        */ public ObservationsViews getMany(GetObservationsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("observations");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - if (request.getName().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); - } - if (request.getUserId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); - } - if (request.getType().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType().get(), false); - } - if (request.getTraceId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); - } - if (request.getLevel().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "level", request.getLevel().get().toString(), false); - } - if (request.getParentObservationId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "parentObservationId", request.getParentObservationId().get(), false); - } - if (request.getEnvironment().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), false); - } - if (request.getFromStartTime().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fromStartTime", request.getFromStartTime().get().toString(), false); - } - if (request.getToStartTime().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "toStartTime", request.getToStartTime().get().toString(), false); - } - if (request.getVersion().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); - } - if (request.getFilter().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ObservationsViews.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.getMany(request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/observations/RawObservationsClient.java b/src/main/java/com/langfuse/client/resources/observations/RawObservationsClient.java new file mode 100644 index 0000000..be5c0bc --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/observations/RawObservationsClient.java @@ -0,0 +1,207 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.observations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.ObservationsView; +import com.langfuse.client.resources.observations.requests.GetObservationsRequest; +import com.langfuse.client.resources.observations.types.ObservationsViews; + +public class RawObservationsClient { + protected final ClientOptions clientOptions; + + public RawObservationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a observation + */ + public LangfuseClientHttpResponse get(String observationId) { + return get(observationId,null); + } + + /** + * Get a observation + */ + public LangfuseClientHttpResponse get(String observationId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("observations") + .addPathSegment(observationId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ObservationsView.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public LangfuseClientHttpResponse getMany() { + return getMany(GetObservationsRequest.builder().build()); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public LangfuseClientHttpResponse getMany(RequestOptions requestOptions) { + return getMany(GetObservationsRequest.builder().build(),requestOptions); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public LangfuseClientHttpResponse getMany(GetObservationsRequest request) { + return getMany(request,null); + } + + /** + * Get a list of observations. + *

        Consider using the v2 observations endpoint for cursor-based pagination and field selection.

        + */ + public LangfuseClientHttpResponse getMany(GetObservationsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("observations");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType().get(), false); + } + if (request.getTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); + } + if (request.getLevel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "level", request.getLevel().get(), false); + } + if (request.getParentObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "parentObservationId", request.getParentObservationId().get(), false); + } + if (request.getFromStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromStartTime", request.getFromStartTime().get(), false); + } + if (request.getToStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toStartTime", request.getToStartTime().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ObservationsViews.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/observations/requests/GetObservationsRequest.java b/src/main/java/com/langfuse/client/resources/observations/requests/GetObservationsRequest.java index 65c5b9e..5775e9d 100644 --- a/src/main/java/com/langfuse/client/resources/observations/requests/GetObservationsRequest.java +++ b/src/main/java/com/langfuse/client/resources/observations/requests/GetObservationsRequest.java @@ -17,7 +17,9 @@ import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -28,6 +30,8 @@ builder = GetObservationsRequest.Builder.class ) public final class GetObservationsRequest { + private final Optional> environment; + private final Optional page; private final Optional limit; @@ -44,8 +48,6 @@ public final class GetObservationsRequest { private final Optional parentObservationId; - private final Optional environment; - private final Optional fromStartTime; private final Optional toStartTime; @@ -56,12 +58,13 @@ public final class GetObservationsRequest { private final Map additionalProperties; - private GetObservationsRequest(Optional page, Optional limit, - Optional name, Optional userId, Optional type, - Optional traceId, Optional level, - Optional parentObservationId, Optional environment, - Optional fromStartTime, Optional toStartTime, - Optional version, Optional filter, Map additionalProperties) { + private GetObservationsRequest(Optional> environment, Optional page, + Optional limit, Optional name, Optional userId, + Optional type, Optional traceId, Optional level, + Optional parentObservationId, Optional fromStartTime, + Optional toStartTime, Optional version, Optional filter, + Map additionalProperties) { + this.environment = environment; this.page = page; this.limit = limit; this.name = name; @@ -70,7 +73,6 @@ private GetObservationsRequest(Optional page, Optional limit, this.traceId = traceId; this.level = level; this.parentObservationId = parentObservationId; - this.environment = environment; this.fromStartTime = fromStartTime; this.toStartTime = toStartTime; this.version = version; @@ -78,6 +80,14 @@ private GetObservationsRequest(Optional page, Optional limit, this.additionalProperties = additionalProperties; } + /** + * @return Optional filter for observations where the environment is one of the provided values. + */ + @JsonProperty("environment") + public Optional> getEnvironment() { + return environment; + } + /** * @return Page number, starts at 1. */ @@ -127,14 +137,6 @@ public Optional getParentObservationId() { return parentObservationId; } - /** - * @return Optional filter for observations where the environment is one of the provided values. - */ - @JsonProperty("environment") - public Optional getEnvironment() { - return environment; - } - /** * @return Retrieve only observations with a start_time on or after this datetime (ISO 8601). */ @@ -179,12 +181,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(GetObservationsRequest other) { - return page.equals(other.page) && limit.equals(other.limit) && name.equals(other.name) && userId.equals(other.userId) && type.equals(other.type) && traceId.equals(other.traceId) && level.equals(other.level) && parentObservationId.equals(other.parentObservationId) && environment.equals(other.environment) && fromStartTime.equals(other.fromStartTime) && toStartTime.equals(other.toStartTime) && version.equals(other.version) && filter.equals(other.filter); + return environment.equals(other.environment) && page.equals(other.page) && limit.equals(other.limit) && name.equals(other.name) && userId.equals(other.userId) && type.equals(other.type) && traceId.equals(other.traceId) && level.equals(other.level) && parentObservationId.equals(other.parentObservationId) && fromStartTime.equals(other.fromStartTime) && toStartTime.equals(other.toStartTime) && version.equals(other.version) && filter.equals(other.filter); } @java.lang.Override public int hashCode() { - return Objects.hash(this.page, this.limit, this.name, this.userId, this.type, this.traceId, this.level, this.parentObservationId, this.environment, this.fromStartTime, this.toStartTime, this.version, this.filter); + return Objects.hash(this.environment, this.page, this.limit, this.name, this.userId, this.type, this.traceId, this.level, this.parentObservationId, this.fromStartTime, this.toStartTime, this.version, this.filter); } @java.lang.Override @@ -200,6 +202,8 @@ public static Builder builder() { ignoreUnknown = true ) public static final class Builder { + private Optional> environment = Optional.empty(); + private Optional page = Optional.empty(); private Optional limit = Optional.empty(); @@ -216,8 +220,6 @@ public static final class Builder { private Optional parentObservationId = Optional.empty(); - private Optional environment = Optional.empty(); - private Optional fromStartTime = Optional.empty(); private Optional toStartTime = Optional.empty(); @@ -233,6 +235,7 @@ private Builder() { } public Builder from(GetObservationsRequest other) { + environment(other.getEnvironment()); page(other.getPage()); limit(other.getLimit()); name(other.getName()); @@ -241,7 +244,6 @@ public Builder from(GetObservationsRequest other) { traceId(other.getTraceId()); level(other.getLevel()); parentObservationId(other.getParentObservationId()); - environment(other.getEnvironment()); fromStartTime(other.getFromStartTime()); toStartTime(other.getToStartTime()); version(other.getVersion()); @@ -249,6 +251,31 @@ public Builder from(GetObservationsRequest other) { return this; } + /** + *

        Optional filter for observations where the environment is one of the provided values.

        + */ + @JsonSetter( + value = "environment", + nulls = Nulls.SKIP + ) + public Builder environment(Optional> environment) { + this.environment = environment; + return this; + } + + public Builder environment(List environment) { + this.environment = Optional.ofNullable(environment); + return this; + } + + public Builder environment(String environment) { + this.environment = Optional.of(Collections.singletonList(environment)); + return this; + } + + /** + *

        Page number, starts at 1.

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -263,6 +290,9 @@ public Builder page(Integer page) { return this; } + /** + *

        Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -333,6 +363,9 @@ public Builder traceId(String traceId) { return this; } + /** + *

        Optional filter for observations with a specific level (e.g. "DEBUG", "DEFAULT", "WARNING", "ERROR").

        + */ @JsonSetter( value = "level", nulls = Nulls.SKIP @@ -361,20 +394,9 @@ public Builder parentObservationId(String parentObservationId) { return this; } - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public Builder environment(Optional environment) { - this.environment = environment; - return this; - } - - public Builder environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - + /** + *

        Retrieve only observations with a start_time on or after this datetime (ISO 8601).

        + */ @JsonSetter( value = "fromStartTime", nulls = Nulls.SKIP @@ -389,6 +411,9 @@ public Builder fromStartTime(OffsetDateTime fromStartTime) { return this; } + /** + *

        Retrieve only observations with a start_time before this datetime (ISO 8601).

        + */ @JsonSetter( value = "toStartTime", nulls = Nulls.SKIP @@ -403,6 +428,9 @@ public Builder toStartTime(OffsetDateTime toStartTime) { return this; } + /** + *

        Optional filter to only include observations with a certain version.

        + */ @JsonSetter( value = "version", nulls = Nulls.SKIP @@ -432,7 +460,17 @@ public Builder filter(String filter) { } public GetObservationsRequest build() { - return new GetObservationsRequest(page, limit, name, userId, type, traceId, level, parentObservationId, environment, fromStartTime, toStartTime, version, filter, additionalProperties); + return new GetObservationsRequest(environment, page, limit, name, userId, type, traceId, level, parentObservationId, fromStartTime, toStartTime, version, filter, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/observations/types/Observations.java b/src/main/java/com/langfuse/client/resources/observations/types/Observations.java index dbb7b8c..fb12855 100644 --- a/src/main/java/com/langfuse/client/resources/observations/types/Observations.java +++ b/src/main/java/com/langfuse/client/resources/observations/types/Observations.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { Observations build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(Observation data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(Observation data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public Observations build() { return new Observations(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/observations/types/ObservationsViews.java b/src/main/java/com/langfuse/client/resources/observations/types/ObservationsViews.java index 21c8e39..19f0edc 100644 --- a/src/main/java/com/langfuse/client/resources/observations/types/ObservationsViews.java +++ b/src/main/java/com/langfuse/client/resources/observations/types/ObservationsViews.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { ObservationsViews build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(ObservationsView data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(ObservationsView data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public ObservationsViews build() { return new ObservationsViews(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/observationsv2/AsyncObservationsV2Client.java b/src/main/java/com/langfuse/client/resources/observationsv2/AsyncObservationsV2Client.java new file mode 100644 index 0000000..15588c9 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/observationsv2/AsyncObservationsV2Client.java @@ -0,0 +1,58 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.observationsv2; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.observationsv2.requests.GetObservationsV2Request; +import com.langfuse.client.resources.observationsv2.types.ObservationsV2Response; + +public class AsyncObservationsV2Client { + protected final ClientOptions clientOptions; + + private final AsyncRawObservationsV2Client rawClient; + + public AsyncObservationsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawObservationsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawObservationsV2Client withRawResponse() { + return this.rawClient; + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture getMany() { + return this.rawClient.getMany().thenApply(response -> response.body()); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture getMany(RequestOptions requestOptions) { + return this.rawClient.getMany(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture getMany(GetObservationsV2Request request) { + return this.rawClient.getMany(request).thenApply(response -> response.body()); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture getMany(GetObservationsV2Request request, + RequestOptions requestOptions) { + return this.rawClient.getMany(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/observationsv2/AsyncRawObservationsV2Client.java b/src/main/java/com/langfuse/client/resources/observationsv2/AsyncRawObservationsV2Client.java new file mode 100644 index 0000000..47fdcb2 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/observationsv2/AsyncRawObservationsV2Client.java @@ -0,0 +1,180 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.observationsv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.observationsv2.requests.GetObservationsV2Request; +import com.langfuse.client.resources.observationsv2.types.ObservationsV2Response; + +public class AsyncRawObservationsV2Client { + protected final ClientOptions clientOptions; + + public AsyncRawObservationsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture> getMany() { + return getMany(GetObservationsV2Request.builder().build()); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture> getMany( + RequestOptions requestOptions) { + return getMany(GetObservationsV2Request.builder().build(),requestOptions); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture> getMany( + GetObservationsV2Request request) { + return getMany(request,null); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public CompletableFuture> getMany( + GetObservationsV2Request request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/observations");if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); + } + if (request.getExpandMetadata().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "expandMetadata", request.getExpandMetadata().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getCursor().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "cursor", request.getCursor().get(), false); + } + if (request.getParseIoAsJson().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "parseIoAsJson", request.getParseIoAsJson().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType().get(), false); + } + if (request.getTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); + } + if (request.getLevel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "level", request.getLevel().get(), false); + } + if (request.getParentObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "parentObservationId", request.getParentObservationId().get(), false); + } + if (request.getFromStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromStartTime", request.getFromStartTime().get(), false); + } + if (request.getToStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toStartTime", request.getToStartTime().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ObservationsV2Response.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/observationsv2/ObservationsV2Client.java b/src/main/java/com/langfuse/client/resources/observationsv2/ObservationsV2Client.java index c0d2b81..454556b 100644 --- a/src/main/java/com/langfuse/client/resources/observationsv2/ObservationsV2Client.java +++ b/src/main/java/com/langfuse/client/resources/observationsv2/ObservationsV2Client.java @@ -4,49 +4,47 @@ package com.langfuse.client.resources.observationsv2; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.observationsv2.requests.GetObservationsV2Request; import com.langfuse.client.resources.observationsv2.types.ObservationsV2Response; public class ObservationsV2Client { protected final ClientOptions clientOptions; + private final RawObservationsV2Client rawClient; + public ObservationsV2Client(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawObservationsV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawObservationsV2Client withRawResponse() { + return this.rawClient; } /** * Get a list of observations with cursor-based pagination and flexible field selection. */ public ObservationsV2Response getMany() { - return getMany(GetObservationsV2Request.builder().build()); + return this.rawClient.getMany().body(); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public ObservationsV2Response getMany(RequestOptions requestOptions) { + return this.rawClient.getMany(requestOptions).body(); } /** * Get a list of observations with cursor-based pagination and flexible field selection. */ public ObservationsV2Response getMany(GetObservationsV2Request request) { - return getMany(request,null); + return this.rawClient.getMany(request).body(); } /** @@ -54,86 +52,6 @@ public ObservationsV2Response getMany(GetObservationsV2Request request) { */ public ObservationsV2Response getMany(GetObservationsV2Request request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("v2/observations");if (request.getFields().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - if (request.getCursor().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "cursor", request.getCursor().get(), false); - } - if (request.getParseIoAsJson().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "parseIoAsJson", request.getParseIoAsJson().get().toString(), false); - } - if (request.getName().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); - } - if (request.getUserId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); - } - if (request.getType().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType().get(), false); - } - if (request.getTraceId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); - } - if (request.getLevel().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "level", request.getLevel().get().toString(), false); - } - if (request.getParentObservationId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "parentObservationId", request.getParentObservationId().get(), false); - } - if (request.getEnvironment().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), false); - } - if (request.getFromStartTime().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fromStartTime", request.getFromStartTime().get().toString(), false); - } - if (request.getToStartTime().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "toStartTime", request.getToStartTime().get().toString(), false); - } - if (request.getVersion().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); - } - if (request.getFilter().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ObservationsV2Response.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.getMany(request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/observationsv2/RawObservationsV2Client.java b/src/main/java/com/langfuse/client/resources/observationsv2/RawObservationsV2Client.java new file mode 100644 index 0000000..b13dc0d --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/observationsv2/RawObservationsV2Client.java @@ -0,0 +1,156 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.observationsv2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.observationsv2.requests.GetObservationsV2Request; +import com.langfuse.client.resources.observationsv2.types.ObservationsV2Response; + +public class RawObservationsV2Client { + protected final ClientOptions clientOptions; + + public RawObservationsV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public LangfuseClientHttpResponse getMany() { + return getMany(GetObservationsV2Request.builder().build()); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public LangfuseClientHttpResponse getMany(RequestOptions requestOptions) { + return getMany(GetObservationsV2Request.builder().build(),requestOptions); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public LangfuseClientHttpResponse getMany( + GetObservationsV2Request request) { + return getMany(request,null); + } + + /** + * Get a list of observations with cursor-based pagination and flexible field selection. + */ + public LangfuseClientHttpResponse getMany( + GetObservationsV2Request request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("v2/observations");if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); + } + if (request.getExpandMetadata().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "expandMetadata", request.getExpandMetadata().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getCursor().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "cursor", request.getCursor().get(), false); + } + if (request.getParseIoAsJson().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "parseIoAsJson", request.getParseIoAsJson().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType().get(), false); + } + if (request.getTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); + } + if (request.getLevel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "level", request.getLevel().get(), false); + } + if (request.getParentObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "parentObservationId", request.getParentObservationId().get(), false); + } + if (request.getFromStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromStartTime", request.getFromStartTime().get(), false); + } + if (request.getToStartTime().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toStartTime", request.getToStartTime().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ObservationsV2Response.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/observationsv2/requests/GetObservationsV2Request.java b/src/main/java/com/langfuse/client/resources/observationsv2/requests/GetObservationsV2Request.java index e890c60..bbf9896 100644 --- a/src/main/java/com/langfuse/client/resources/observationsv2/requests/GetObservationsV2Request.java +++ b/src/main/java/com/langfuse/client/resources/observationsv2/requests/GetObservationsV2Request.java @@ -18,7 +18,9 @@ import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -29,8 +31,12 @@ builder = GetObservationsV2Request.Builder.class ) public final class GetObservationsV2Request { + private final Optional> environment; + private final Optional fields; + private final Optional expandMetadata; + private final Optional limit; private final Optional cursor; @@ -49,8 +55,6 @@ public final class GetObservationsV2Request { private final Optional parentObservationId; - private final Optional environment; - private final Optional fromStartTime; private final Optional toStartTime; @@ -61,14 +65,16 @@ public final class GetObservationsV2Request { private final Map additionalProperties; - private GetObservationsV2Request(Optional fields, Optional limit, - Optional cursor, Optional parseIoAsJson, Optional name, - Optional userId, Optional type, Optional traceId, - Optional level, Optional parentObservationId, - Optional environment, Optional fromStartTime, + private GetObservationsV2Request(Optional> environment, Optional fields, + Optional expandMetadata, Optional limit, Optional cursor, + Optional parseIoAsJson, Optional name, Optional userId, + Optional type, Optional traceId, Optional level, + Optional parentObservationId, Optional fromStartTime, Optional toStartTime, Optional version, Optional filter, Map additionalProperties) { + this.environment = environment; this.fields = fields; + this.expandMetadata = expandMetadata; this.limit = limit; this.cursor = cursor; this.parseIoAsJson = parseIoAsJson; @@ -78,7 +84,6 @@ private GetObservationsV2Request(Optional fields, Optional limi this.traceId = traceId; this.level = level; this.parentObservationId = parentObservationId; - this.environment = environment; this.fromStartTime = fromStartTime; this.toStartTime = toStartTime; this.version = version; @@ -86,6 +91,14 @@ private GetObservationsV2Request(Optional fields, Optional limi this.additionalProperties = additionalProperties; } + /** + * @return Optional filter for observations where the environment is one of the provided values. + */ + @JsonProperty("environment") + public Optional> getEnvironment() { + return environment; + } + /** * @return Comma-separated list of field groups to include in the response. * Available groups: core, basic, time, io, metadata, model, usage, prompt, metrics. @@ -97,6 +110,17 @@ public Optional getFields() { return fields; } + /** + * @return Comma-separated list of metadata keys to return non-truncated. + * By default, metadata values over 200 characters are truncated. + * Use this parameter to retrieve full values for specific keys. + * Example: "key1,key2" + */ + @JsonProperty("expandMetadata") + public Optional getExpandMetadata() { + return expandMetadata; + } + /** * @return Number of items to return per page. Maximum 1000, default 50. */ @@ -114,8 +138,9 @@ public Optional getCursor() { } /** - * @return Set to true to parse input/output fields as JSON, or false to return raw strings. - * Defaults to false if not provided. + * @return Deprecated. Setting this to true will return a 400 error. + * Input/output fields are always returned as raw strings. + * Remove this parameter or set it to false. */ @JsonProperty("parseIoAsJson") public Optional getParseIoAsJson() { @@ -158,14 +183,6 @@ public Optional getParentObservationId() { return parentObservationId; } - /** - * @return Optional filter for observations where the environment is one of the provided values. - */ - @JsonProperty("environment") - public Optional getEnvironment() { - return environment; - } - /** * @return Retrieve only observations with a start_time on or after this datetime (ISO 8601). */ @@ -210,12 +227,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(GetObservationsV2Request other) { - return fields.equals(other.fields) && limit.equals(other.limit) && cursor.equals(other.cursor) && parseIoAsJson.equals(other.parseIoAsJson) && name.equals(other.name) && userId.equals(other.userId) && type.equals(other.type) && traceId.equals(other.traceId) && level.equals(other.level) && parentObservationId.equals(other.parentObservationId) && environment.equals(other.environment) && fromStartTime.equals(other.fromStartTime) && toStartTime.equals(other.toStartTime) && version.equals(other.version) && filter.equals(other.filter); + return environment.equals(other.environment) && fields.equals(other.fields) && expandMetadata.equals(other.expandMetadata) && limit.equals(other.limit) && cursor.equals(other.cursor) && parseIoAsJson.equals(other.parseIoAsJson) && name.equals(other.name) && userId.equals(other.userId) && type.equals(other.type) && traceId.equals(other.traceId) && level.equals(other.level) && parentObservationId.equals(other.parentObservationId) && fromStartTime.equals(other.fromStartTime) && toStartTime.equals(other.toStartTime) && version.equals(other.version) && filter.equals(other.filter); } @java.lang.Override public int hashCode() { - return Objects.hash(this.fields, this.limit, this.cursor, this.parseIoAsJson, this.name, this.userId, this.type, this.traceId, this.level, this.parentObservationId, this.environment, this.fromStartTime, this.toStartTime, this.version, this.filter); + return Objects.hash(this.environment, this.fields, this.expandMetadata, this.limit, this.cursor, this.parseIoAsJson, this.name, this.userId, this.type, this.traceId, this.level, this.parentObservationId, this.fromStartTime, this.toStartTime, this.version, this.filter); } @java.lang.Override @@ -231,8 +248,12 @@ public static Builder builder() { ignoreUnknown = true ) public static final class Builder { + private Optional> environment = Optional.empty(); + private Optional fields = Optional.empty(); + private Optional expandMetadata = Optional.empty(); + private Optional limit = Optional.empty(); private Optional cursor = Optional.empty(); @@ -251,8 +272,6 @@ public static final class Builder { private Optional parentObservationId = Optional.empty(); - private Optional environment = Optional.empty(); - private Optional fromStartTime = Optional.empty(); private Optional toStartTime = Optional.empty(); @@ -268,7 +287,9 @@ private Builder() { } public Builder from(GetObservationsV2Request other) { + environment(other.getEnvironment()); fields(other.getFields()); + expandMetadata(other.getExpandMetadata()); limit(other.getLimit()); cursor(other.getCursor()); parseIoAsJson(other.getParseIoAsJson()); @@ -278,7 +299,6 @@ public Builder from(GetObservationsV2Request other) { traceId(other.getTraceId()); level(other.getLevel()); parentObservationId(other.getParentObservationId()); - environment(other.getEnvironment()); fromStartTime(other.getFromStartTime()); toStartTime(other.getToStartTime()); version(other.getVersion()); @@ -286,6 +306,34 @@ public Builder from(GetObservationsV2Request other) { return this; } + /** + *

        Optional filter for observations where the environment is one of the provided values.

        + */ + @JsonSetter( + value = "environment", + nulls = Nulls.SKIP + ) + public Builder environment(Optional> environment) { + this.environment = environment; + return this; + } + + public Builder environment(List environment) { + this.environment = Optional.ofNullable(environment); + return this; + } + + public Builder environment(String environment) { + this.environment = Optional.of(Collections.singletonList(environment)); + return this; + } + + /** + *

        Comma-separated list of field groups to include in the response. + * Available groups: core, basic, time, io, metadata, model, usage, prompt, metrics. + * If not specified, core and basic field groups are returned. + * Example: "basic,usage,model"

        + */ @JsonSetter( value = "fields", nulls = Nulls.SKIP @@ -300,6 +348,29 @@ public Builder fields(String fields) { return this; } + /** + *

        Comma-separated list of metadata keys to return non-truncated. + * By default, metadata values over 200 characters are truncated. + * Use this parameter to retrieve full values for specific keys. + * Example: "key1,key2"

        + */ + @JsonSetter( + value = "expandMetadata", + nulls = Nulls.SKIP + ) + public Builder expandMetadata(Optional expandMetadata) { + this.expandMetadata = expandMetadata; + return this; + } + + public Builder expandMetadata(String expandMetadata) { + this.expandMetadata = Optional.ofNullable(expandMetadata); + return this; + } + + /** + *

        Number of items to return per page. Maximum 1000, default 50.

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -314,6 +385,9 @@ public Builder limit(Integer limit) { return this; } + /** + *

        Base64-encoded cursor for pagination. Use the cursor from the previous response to get the next page.

        + */ @JsonSetter( value = "cursor", nulls = Nulls.SKIP @@ -328,6 +402,11 @@ public Builder cursor(String cursor) { return this; } + /** + *

        Deprecated. Setting this to true will return a 400 error. + * Input/output fields are always returned as raw strings. + * Remove this parameter or set it to false.

        + */ @JsonSetter( value = "parseIoAsJson", nulls = Nulls.SKIP @@ -370,6 +449,9 @@ public Builder userId(String userId) { return this; } + /** + *

        Filter by observation type (e.g., "GENERATION", "SPAN", "EVENT", "AGENT", "TOOL", "CHAIN", "RETRIEVER", "EVALUATOR", "EMBEDDING", "GUARDRAIL")

        + */ @JsonSetter( value = "type", nulls = Nulls.SKIP @@ -398,6 +480,9 @@ public Builder traceId(String traceId) { return this; } + /** + *

        Optional filter for observations with a specific level (e.g. "DEBUG", "DEFAULT", "WARNING", "ERROR").

        + */ @JsonSetter( value = "level", nulls = Nulls.SKIP @@ -426,20 +511,9 @@ public Builder parentObservationId(String parentObservationId) { return this; } - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public Builder environment(Optional environment) { - this.environment = environment; - return this; - } - - public Builder environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - + /** + *

        Retrieve only observations with a start_time on or after this datetime (ISO 8601).

        + */ @JsonSetter( value = "fromStartTime", nulls = Nulls.SKIP @@ -454,6 +528,9 @@ public Builder fromStartTime(OffsetDateTime fromStartTime) { return this; } + /** + *

        Retrieve only observations with a start_time before this datetime (ISO 8601).

        + */ @JsonSetter( value = "toStartTime", nulls = Nulls.SKIP @@ -468,6 +545,9 @@ public Builder toStartTime(OffsetDateTime toStartTime) { return this; } + /** + *

        Optional filter to only include observations with a certain version.

        + */ @JsonSetter( value = "version", nulls = Nulls.SKIP @@ -482,6 +562,9 @@ public Builder version(String version) { return this; } + /** + * JSON string containing an array of filter conditions. When provided, this takes precedence over query parameter filters (userId, name, type, level, environment, fromStartTime, ...). + */ @JsonSetter( value = "filter", nulls = Nulls.SKIP @@ -497,7 +580,17 @@ public Builder filter(String filter) { } public GetObservationsV2Request build() { - return new GetObservationsV2Request(fields, limit, cursor, parseIoAsJson, name, userId, type, traceId, level, parentObservationId, environment, fromStartTime, toStartTime, version, filter, additionalProperties); + return new GetObservationsV2Request(environment, fields, expandMetadata, limit, cursor, parseIoAsJson, name, userId, type, traceId, level, parentObservationId, fromStartTime, toStartTime, version, filter, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Meta.java b/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Meta.java index 988c323..a02c3b3 100644 --- a/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Meta.java +++ b/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Meta.java @@ -88,6 +88,9 @@ public Builder from(ObservationsV2Meta other) { return this; } + /** + *

        Base64-encoded cursor to use for retrieving the next page. If not present, there are no more results.

        + */ @JsonSetter( value = "cursor", nulls = Nulls.SKIP @@ -105,5 +108,15 @@ public Builder cursor(String cursor) { public ObservationsV2Meta build() { return new ObservationsV2Meta(cursor, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Response.java b/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Response.java index 24d25a0..d334158 100644 --- a/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Response.java +++ b/src/main/java/com/langfuse/client/resources/observationsv2/types/ObservationsV2Response.java @@ -91,6 +91,13 @@ public interface MetaStage { public interface _FinalStage { ObservationsV2Response build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Array of observation objects. Fields included depend on the fields parameter in the request.

        + */ _FinalStage data(List> data); _FinalStage addData(Map data); @@ -132,7 +139,9 @@ public _FinalStage meta(@NotNull ObservationsV2Meta meta) { */ @java.lang.Override public _FinalStage addAllData(List> data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -146,6 +155,9 @@ public _FinalStage addData(Map data) { return this; } + /** + *

        Array of observation objects. Fields included depend on the fields parameter in the request.

        + */ @java.lang.Override @JsonSetter( value = "data", @@ -153,7 +165,9 @@ public _FinalStage addData(Map data) { ) public _FinalStage data(List> data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -161,5 +175,17 @@ public _FinalStage data(List> data) { public ObservationsV2Response build() { return new ObservationsV2Response(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/AsyncOpentelemetryClient.java b/src/main/java/com/langfuse/client/resources/opentelemetry/AsyncOpentelemetryClient.java new file mode 100644 index 0000000..eda427f --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/AsyncOpentelemetryClient.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.opentelemetry; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.opentelemetry.requests.OtelTraceRequest; +import com.langfuse.client.resources.opentelemetry.types.OtelTraceResponse; + +public class AsyncOpentelemetryClient { + protected final ClientOptions clientOptions; + + private final AsyncRawOpentelemetryClient rawClient; + + public AsyncOpentelemetryClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawOpentelemetryClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawOpentelemetryClient withRawResponse() { + return this.rawClient; + } + + /** + * OpenTelemetry Traces Ingestion Endpoint + *

        This endpoint implements the OTLP/HTTP specification for trace ingestion, providing native OpenTelemetry integration for Langfuse Observability.

        + *

        Supported Formats:

        + *
          + *
        • Binary Protobuf: Content-Type: application/x-protobuf
        • + *
        • JSON Protobuf: Content-Type: application/json
        • + *
        • Supports gzip compression via Content-Encoding: gzip header
        • + *
        + *

        Specification Compliance:

        + * + *

        Documentation:

        + *
          + *
        • Integration guide: https://langfuse.com/integrations/native/opentelemetry
        • + *
        • Data model: https://langfuse.com/docs/observability/data-model
        • + *
        + */ + public CompletableFuture exportTraces(OtelTraceRequest request) { + return this.rawClient.exportTraces(request).thenApply(response -> response.body()); + } + + /** + * OpenTelemetry Traces Ingestion Endpoint + *

        This endpoint implements the OTLP/HTTP specification for trace ingestion, providing native OpenTelemetry integration for Langfuse Observability.

        + *

        Supported Formats:

        + *
          + *
        • Binary Protobuf: Content-Type: application/x-protobuf
        • + *
        • JSON Protobuf: Content-Type: application/json
        • + *
        • Supports gzip compression via Content-Encoding: gzip header
        • + *
        + *

        Specification Compliance:

        + * + *

        Documentation:

        + *
          + *
        • Integration guide: https://langfuse.com/integrations/native/opentelemetry
        • + *
        • Data model: https://langfuse.com/docs/observability/data-model
        • + *
        + */ + public CompletableFuture exportTraces(OtelTraceRequest request, + RequestOptions requestOptions) { + return this.rawClient.exportTraces(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/AsyncRawOpentelemetryClient.java b/src/main/java/com/langfuse/client/resources/opentelemetry/AsyncRawOpentelemetryClient.java new file mode 100644 index 0000000..daa0cf8 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/AsyncRawOpentelemetryClient.java @@ -0,0 +1,160 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.opentelemetry; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.opentelemetry.requests.OtelTraceRequest; +import com.langfuse.client.resources.opentelemetry.types.OtelTraceResponse; + +public class AsyncRawOpentelemetryClient { + protected final ClientOptions clientOptions; + + public AsyncRawOpentelemetryClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * OpenTelemetry Traces Ingestion Endpoint + *

        This endpoint implements the OTLP/HTTP specification for trace ingestion, providing native OpenTelemetry integration for Langfuse Observability.

        + *

        Supported Formats:

        + *
          + *
        • Binary Protobuf: Content-Type: application/x-protobuf
        • + *
        • JSON Protobuf: Content-Type: application/json
        • + *
        • Supports gzip compression via Content-Encoding: gzip header
        • + *
        + *

        Specification Compliance:

        + * + *

        Documentation:

        + *
          + *
        • Integration guide: https://langfuse.com/integrations/native/opentelemetry
        • + *
        • Data model: https://langfuse.com/docs/observability/data-model
        • + *
        + */ + public CompletableFuture> exportTraces( + OtelTraceRequest request) { + return exportTraces(request,null); + } + + /** + * OpenTelemetry Traces Ingestion Endpoint + *

        This endpoint implements the OTLP/HTTP specification for trace ingestion, providing native OpenTelemetry integration for Langfuse Observability.

        + *

        Supported Formats:

        + *
          + *
        • Binary Protobuf: Content-Type: application/x-protobuf
        • + *
        • JSON Protobuf: Content-Type: application/json
        • + *
        • Supports gzip compression via Content-Encoding: gzip header
        • + *
        + *

        Specification Compliance:

        + * + *

        Documentation:

        + *
          + *
        • Integration guide: https://langfuse.com/integrations/native/opentelemetry
        • + *
        • Data model: https://langfuse.com/docs/observability/data-model
        • + *
        + */ + public CompletableFuture> exportTraces( + OtelTraceRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("otel/v1/traces");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OtelTraceResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/OpentelemetryClient.java b/src/main/java/com/langfuse/client/resources/opentelemetry/OpentelemetryClient.java index f3fa6e2..779de5b 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/OpentelemetryClient.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/OpentelemetryClient.java @@ -4,36 +4,26 @@ package com.langfuse.client.resources.opentelemetry; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; -import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.opentelemetry.requests.OtelTraceRequest; import com.langfuse.client.resources.opentelemetry.types.OtelTraceResponse; public class OpentelemetryClient { protected final ClientOptions clientOptions; + private final RawOpentelemetryClient rawClient; + public OpentelemetryClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawOpentelemetryClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawOpentelemetryClient withRawResponse() { + return this.rawClient; } /** @@ -57,7 +47,7 @@ public OpentelemetryClient(ClientOptions clientOptions) { * */ public OtelTraceResponse exportTraces(OtelTraceRequest request) { - return exportTraces(request,null); + return this.rawClient.exportTraces(request).body(); } /** @@ -81,50 +71,6 @@ public OtelTraceResponse exportTraces(OtelTraceRequest request) { * */ public OtelTraceResponse exportTraces(OtelTraceRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("otel/v1/traces") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), OtelTraceResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.exportTraces(request, requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/RawOpentelemetryClient.java b/src/main/java/com/langfuse/client/resources/opentelemetry/RawOpentelemetryClient.java new file mode 100644 index 0000000..8ccabe5 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/RawOpentelemetryClient.java @@ -0,0 +1,136 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.opentelemetry; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.opentelemetry.requests.OtelTraceRequest; +import com.langfuse.client.resources.opentelemetry.types.OtelTraceResponse; + +public class RawOpentelemetryClient { + protected final ClientOptions clientOptions; + + public RawOpentelemetryClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * OpenTelemetry Traces Ingestion Endpoint + *

        This endpoint implements the OTLP/HTTP specification for trace ingestion, providing native OpenTelemetry integration for Langfuse Observability.

        + *

        Supported Formats:

        + *
          + *
        • Binary Protobuf: Content-Type: application/x-protobuf
        • + *
        • JSON Protobuf: Content-Type: application/json
        • + *
        • Supports gzip compression via Content-Encoding: gzip header
        • + *
        + *

        Specification Compliance:

        + * + *

        Documentation:

        + *
          + *
        • Integration guide: https://langfuse.com/integrations/native/opentelemetry
        • + *
        • Data model: https://langfuse.com/docs/observability/data-model
        • + *
        + */ + public LangfuseClientHttpResponse exportTraces(OtelTraceRequest request) { + return exportTraces(request,null); + } + + /** + * OpenTelemetry Traces Ingestion Endpoint + *

        This endpoint implements the OTLP/HTTP specification for trace ingestion, providing native OpenTelemetry integration for Langfuse Observability.

        + *

        Supported Formats:

        + *
          + *
        • Binary Protobuf: Content-Type: application/x-protobuf
        • + *
        • JSON Protobuf: Content-Type: application/json
        • + *
        • Supports gzip compression via Content-Encoding: gzip header
        • + *
        + *

        Specification Compliance:

        + * + *

        Documentation:

        + *
          + *
        • Integration guide: https://langfuse.com/integrations/native/opentelemetry
        • + *
        • Data model: https://langfuse.com/docs/observability/data-model
        • + *
        + */ + public LangfuseClientHttpResponse exportTraces(OtelTraceRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("otel/v1/traces");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OtelTraceResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/requests/OtelTraceRequest.java b/src/main/java/com/langfuse/client/resources/opentelemetry/requests/OtelTraceRequest.java index dd58e66..c0b6d0f 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/requests/OtelTraceRequest.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/requests/OtelTraceRequest.java @@ -91,13 +91,18 @@ public Builder from(OtelTraceRequest other) { return this; } + /** + *

        Array of resource spans containing trace data as defined in the OTLP specification

        + */ @JsonSetter( value = "resourceSpans", nulls = Nulls.SKIP ) public Builder resourceSpans(List resourceSpans) { this.resourceSpans.clear(); - this.resourceSpans.addAll(resourceSpans); + if (resourceSpans != null) { + this.resourceSpans.addAll(resourceSpans); + } return this; } @@ -107,12 +112,24 @@ public Builder addResourceSpans(OtelResourceSpan resourceSpans) { } public Builder addAllResourceSpans(List resourceSpans) { - this.resourceSpans.addAll(resourceSpans); + if (resourceSpans != null) { + this.resourceSpans.addAll(resourceSpans); + } return this; } public OtelTraceRequest build() { return new OtelTraceRequest(resourceSpans, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttribute.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttribute.java index 4ae6e38..7722946 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttribute.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttribute.java @@ -103,6 +103,9 @@ public Builder from(OtelAttribute other) { return this; } + /** + *

        Attribute key (e.g., "service.name", "langfuse.observation.type")

        + */ @JsonSetter( value = "key", nulls = Nulls.SKIP @@ -117,6 +120,9 @@ public Builder key(String key) { return this; } + /** + *

        Attribute value

        + */ @JsonSetter( value = "value", nulls = Nulls.SKIP @@ -134,5 +140,15 @@ public Builder value(OtelAttributeValue value) { public OtelAttribute build() { return new OtelAttribute(key, value, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttributeValue.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttributeValue.java index ebe5d5e..47c75aa 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttributeValue.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelAttributeValue.java @@ -135,6 +135,9 @@ public Builder from(OtelAttributeValue other) { return this; } + /** + *

        String value

        + */ @JsonSetter( value = "stringValue", nulls = Nulls.SKIP @@ -149,6 +152,9 @@ public Builder stringValue(String stringValue) { return this; } + /** + *

        Integer value

        + */ @JsonSetter( value = "intValue", nulls = Nulls.SKIP @@ -163,6 +169,9 @@ public Builder intValue(Integer intValue) { return this; } + /** + *

        Double value

        + */ @JsonSetter( value = "doubleValue", nulls = Nulls.SKIP @@ -177,6 +186,9 @@ public Builder doubleValue(Double doubleValue) { return this; } + /** + *

        Boolean value

        + */ @JsonSetter( value = "boolValue", nulls = Nulls.SKIP @@ -194,5 +206,15 @@ public Builder boolValue(Boolean boolValue) { public OtelAttributeValue build() { return new OtelAttributeValue(stringValue, intValue, doubleValue, boolValue, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResource.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResource.java index a91048a..235db54 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResource.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResource.java @@ -90,6 +90,9 @@ public Builder from(OtelResource other) { return this; } + /** + *

        Resource attributes like service.name, service.version, etc.

        + */ @JsonSetter( value = "attributes", nulls = Nulls.SKIP @@ -107,5 +110,15 @@ public Builder attributes(List attributes) { public OtelResource build() { return new OtelResource(attributes, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResourceSpan.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResourceSpan.java index 5a57544..008a383 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResourceSpan.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelResourceSpan.java @@ -104,6 +104,9 @@ public Builder from(OtelResourceSpan other) { return this; } + /** + *

        Resource information

        + */ @JsonSetter( value = "resource", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder resource(OtelResource resource) { return this; } + /** + *

        Array of scope spans

        + */ @JsonSetter( value = "scopeSpans", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder scopeSpans(List scopeSpans) { public OtelResourceSpan build() { return new OtelResourceSpan(resource, scopeSpans, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScope.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScope.java index 5f9d0b9..2f060da 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScope.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScope.java @@ -118,6 +118,9 @@ public Builder from(OtelScope other) { return this; } + /** + *

        Instrumentation scope name

        + */ @JsonSetter( value = "name", nulls = Nulls.SKIP @@ -132,6 +135,9 @@ public Builder name(String name) { return this; } + /** + *

        Instrumentation scope version

        + */ @JsonSetter( value = "version", nulls = Nulls.SKIP @@ -146,6 +152,9 @@ public Builder version(String version) { return this; } + /** + *

        Additional scope attributes

        + */ @JsonSetter( value = "attributes", nulls = Nulls.SKIP @@ -163,5 +172,15 @@ public Builder attributes(List attributes) { public OtelScope build() { return new OtelScope(name, version, attributes, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScopeSpan.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScopeSpan.java index 25f8f91..462c16b 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScopeSpan.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelScopeSpan.java @@ -104,6 +104,9 @@ public Builder from(OtelScopeSpan other) { return this; } + /** + *

        Instrumentation scope information

        + */ @JsonSetter( value = "scope", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder scope(OtelScope scope) { return this; } + /** + *

        Array of spans

        + */ @JsonSetter( value = "spans", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder spans(List spans) { public OtelScopeSpan build() { return new OtelScopeSpan(scope, spans, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelSpan.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelSpan.java index e0e7d5e..74ca715 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelSpan.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelSpan.java @@ -205,6 +205,9 @@ public Builder from(OtelSpan other) { return this; } + /** + *

        Trace ID (16 bytes, hex-encoded string in JSON or Buffer in binary)

        + */ @JsonSetter( value = "traceId", nulls = Nulls.SKIP @@ -219,6 +222,9 @@ public Builder traceId(Object traceId) { return this; } + /** + *

        Span ID (8 bytes, hex-encoded string in JSON or Buffer in binary)

        + */ @JsonSetter( value = "spanId", nulls = Nulls.SKIP @@ -233,6 +239,9 @@ public Builder spanId(Object spanId) { return this; } + /** + *

        Parent span ID if this is a child span

        + */ @JsonSetter( value = "parentSpanId", nulls = Nulls.SKIP @@ -247,6 +256,9 @@ public Builder parentSpanId(Object parentSpanId) { return this; } + /** + *

        Span name describing the operation

        + */ @JsonSetter( value = "name", nulls = Nulls.SKIP @@ -261,6 +273,9 @@ public Builder name(String name) { return this; } + /** + *

        Span kind (1=INTERNAL, 2=SERVER, 3=CLIENT, 4=PRODUCER, 5=CONSUMER)

        + */ @JsonSetter( value = "kind", nulls = Nulls.SKIP @@ -275,6 +290,9 @@ public Builder kind(Integer kind) { return this; } + /** + *

        Start time in nanoseconds since Unix epoch

        + */ @JsonSetter( value = "startTimeUnixNano", nulls = Nulls.SKIP @@ -289,6 +307,9 @@ public Builder startTimeUnixNano(Object startTimeUnixNano) { return this; } + /** + *

        End time in nanoseconds since Unix epoch

        + */ @JsonSetter( value = "endTimeUnixNano", nulls = Nulls.SKIP @@ -303,6 +324,9 @@ public Builder endTimeUnixNano(Object endTimeUnixNano) { return this; } + /** + *

        Span attributes including Langfuse-specific attributes (langfuse.observation.*)

        + */ @JsonSetter( value = "attributes", nulls = Nulls.SKIP @@ -317,6 +341,9 @@ public Builder attributes(List attributes) { return this; } + /** + *

        Span status object

        + */ @JsonSetter( value = "status", nulls = Nulls.SKIP @@ -334,5 +361,15 @@ public Builder status(Object status) { public OtelSpan build() { return new OtelSpan(traceId, spanId, parentSpanId, name, kind, startTimeUnixNano, endTimeUnixNano, attributes, status, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelTraceResponse.java b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelTraceResponse.java index 3e81e13..6ade84c 100644 --- a/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelTraceResponse.java +++ b/src/main/java/com/langfuse/client/resources/opentelemetry/types/OtelTraceResponse.java @@ -63,5 +63,15 @@ public Builder from(OtelTraceResponse other) { public OtelTraceResponse build() { return new OtelTraceResponse(additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/AsyncOrganizationsClient.java b/src/main/java/com/langfuse/client/resources/organizations/AsyncOrganizationsClient.java new file mode 100644 index 0000000..c56f34e --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/organizations/AsyncOrganizationsClient.java @@ -0,0 +1,159 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.organizations; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.organizations.types.DeleteMembershipRequest; +import com.langfuse.client.resources.organizations.types.MembershipDeletionResponse; +import com.langfuse.client.resources.organizations.types.MembershipRequest; +import com.langfuse.client.resources.organizations.types.MembershipResponse; +import com.langfuse.client.resources.organizations.types.MembershipsResponse; +import com.langfuse.client.resources.organizations.types.OrganizationApiKeysResponse; +import com.langfuse.client.resources.organizations.types.OrganizationProjectsResponse; + +public class AsyncOrganizationsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawOrganizationsClient rawClient; + + public AsyncOrganizationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawOrganizationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawOrganizationsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get all memberships for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture getOrganizationMemberships() { + return this.rawClient.getOrganizationMemberships().thenApply(response -> response.body()); + } + + /** + * Get all memberships for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture getOrganizationMemberships( + RequestOptions requestOptions) { + return this.rawClient.getOrganizationMemberships(requestOptions).thenApply(response -> response.body()); + } + + /** + * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture updateOrganizationMembership( + MembershipRequest request) { + return this.rawClient.updateOrganizationMembership(request).thenApply(response -> response.body()); + } + + /** + * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture updateOrganizationMembership( + MembershipRequest request, RequestOptions requestOptions) { + return this.rawClient.updateOrganizationMembership(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a membership from the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture deleteOrganizationMembership( + DeleteMembershipRequest request) { + return this.rawClient.deleteOrganizationMembership(request).thenApply(response -> response.body()); + } + + /** + * Delete a membership from the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture deleteOrganizationMembership( + DeleteMembershipRequest request, RequestOptions requestOptions) { + return this.rawClient.deleteOrganizationMembership(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all memberships for a specific project (requires organization-scoped API key) + */ + public CompletableFuture getProjectMemberships(String projectId) { + return this.rawClient.getProjectMemberships(projectId).thenApply(response -> response.body()); + } + + /** + * Get all memberships for a specific project (requires organization-scoped API key) + */ + public CompletableFuture getProjectMemberships(String projectId, + RequestOptions requestOptions) { + return this.rawClient.getProjectMemberships(projectId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. + */ + public CompletableFuture updateProjectMembership(String projectId, + MembershipRequest request) { + return this.rawClient.updateProjectMembership(projectId, request).thenApply(response -> response.body()); + } + + /** + * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. + */ + public CompletableFuture updateProjectMembership(String projectId, + MembershipRequest request, RequestOptions requestOptions) { + return this.rawClient.updateProjectMembership(projectId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a membership from a specific project (requires organization-scoped API key). The user must be a member of the organization. + */ + public CompletableFuture deleteProjectMembership(String projectId, + DeleteMembershipRequest request) { + return this.rawClient.deleteProjectMembership(projectId, request).thenApply(response -> response.body()); + } + + /** + * Delete a membership from a specific project (requires organization-scoped API key). The user must be a member of the organization. + */ + public CompletableFuture deleteProjectMembership(String projectId, + DeleteMembershipRequest request, RequestOptions requestOptions) { + return this.rawClient.deleteProjectMembership(projectId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all projects for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture getOrganizationProjects() { + return this.rawClient.getOrganizationProjects().thenApply(response -> response.body()); + } + + /** + * Get all projects for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture getOrganizationProjects( + RequestOptions requestOptions) { + return this.rawClient.getOrganizationProjects(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all API keys for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture getOrganizationApiKeys() { + return this.rawClient.getOrganizationApiKeys().thenApply(response -> response.body()); + } + + /** + * Get all API keys for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture getOrganizationApiKeys( + RequestOptions requestOptions) { + return this.rawClient.getOrganizationApiKeys(requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/organizations/AsyncRawOrganizationsClient.java b/src/main/java/com/langfuse/client/resources/organizations/AsyncRawOrganizationsClient.java new file mode 100644 index 0000000..11bb792 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/organizations/AsyncRawOrganizationsClient.java @@ -0,0 +1,679 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.organizations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.organizations.types.DeleteMembershipRequest; +import com.langfuse.client.resources.organizations.types.MembershipDeletionResponse; +import com.langfuse.client.resources.organizations.types.MembershipRequest; +import com.langfuse.client.resources.organizations.types.MembershipResponse; +import com.langfuse.client.resources.organizations.types.MembershipsResponse; +import com.langfuse.client.resources.organizations.types.OrganizationApiKeysResponse; +import com.langfuse.client.resources.organizations.types.OrganizationProjectsResponse; + +public class AsyncRawOrganizationsClient { + protected final ClientOptions clientOptions; + + public AsyncRawOrganizationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all memberships for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> getOrganizationMemberships( + ) { + return getOrganizationMemberships(null); + } + + /** + * Get all memberships for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> getOrganizationMemberships( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipsResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> updateOrganizationMembership( + MembershipRequest request) { + return updateOrganizationMembership(request,null); + } + + /** + * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> updateOrganizationMembership( + MembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a membership from the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> deleteOrganizationMembership( + DeleteMembershipRequest request) { + return deleteOrganizationMembership(request,null); + } + + /** + * Delete a membership from the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> deleteOrganizationMembership( + DeleteMembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipDeletionResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get all memberships for a specific project (requires organization-scoped API key) + */ + public CompletableFuture> getProjectMemberships( + String projectId) { + return getProjectMemberships(projectId,null); + } + + /** + * Get all memberships for a specific project (requires organization-scoped API key) + */ + public CompletableFuture> getProjectMemberships( + String projectId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipsResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. + */ + public CompletableFuture> updateProjectMembership( + String projectId, MembershipRequest request) { + return updateProjectMembership(projectId,request,null); + } + + /** + * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. + */ + public CompletableFuture> updateProjectMembership( + String projectId, MembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a membership from a specific project (requires organization-scoped API key). The user must be a member of the organization. + */ + public CompletableFuture> deleteProjectMembership( + String projectId, DeleteMembershipRequest request) { + return deleteProjectMembership(projectId,request,null); + } + + /** + * Delete a membership from a specific project (requires organization-scoped API key). The user must be a member of the organization. + */ + public CompletableFuture> deleteProjectMembership( + String projectId, DeleteMembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipDeletionResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get all projects for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> getOrganizationProjects( + ) { + return getOrganizationProjects(null); + } + + /** + * Get all projects for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> getOrganizationProjects( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/projects");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OrganizationProjectsResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get all API keys for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> getOrganizationApiKeys( + ) { + return getOrganizationApiKeys(null); + } + + /** + * Get all API keys for the organization associated with the API key (requires organization-scoped API key) + */ + public CompletableFuture> getOrganizationApiKeys( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/apiKeys");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OrganizationApiKeysResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/organizations/OrganizationsClient.java b/src/main/java/com/langfuse/client/resources/organizations/OrganizationsClient.java index 5698ff3..a3f5207 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/OrganizationsClient.java +++ b/src/main/java/com/langfuse/client/resources/organizations/OrganizationsClient.java @@ -4,28 +4,9 @@ package com.langfuse.client.resources.organizations; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.organizations.types.DeleteMembershipRequest; import com.langfuse.client.resources.organizations.types.MembershipDeletionResponse; import com.langfuse.client.resources.organizations.types.MembershipRequest; @@ -37,66 +18,39 @@ public class OrganizationsClient { protected final ClientOptions clientOptions; + private final RawOrganizationsClient rawClient; + public OrganizationsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawOrganizationsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawOrganizationsClient withRawResponse() { + return this.rawClient; } /** * Get all memberships for the organization associated with the API key (requires organization-scoped API key) */ public MembershipsResponse getOrganizationMemberships() { - return getOrganizationMemberships(null); + return this.rawClient.getOrganizationMemberships().body(); } /** * Get all memberships for the organization associated with the API key (requires organization-scoped API key) */ public MembershipsResponse getOrganizationMemberships(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("organizations/memberships") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MembershipsResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getOrganizationMemberships(requestOptions).body(); } /** * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) */ public MembershipResponse updateOrganizationMembership(MembershipRequest request) { - return updateOrganizationMembership(request,null); + return this.rawClient.updateOrganizationMembership(request).body(); } /** @@ -104,58 +58,14 @@ public MembershipResponse updateOrganizationMembership(MembershipRequest request */ public MembershipResponse updateOrganizationMembership(MembershipRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("organizations/memberships") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MembershipResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.updateOrganizationMembership(request, requestOptions).body(); } /** * Delete a membership from the organization associated with the API key (requires organization-scoped API key) */ public MembershipDeletionResponse deleteOrganizationMembership(DeleteMembershipRequest request) { - return deleteOrganizationMembership(request,null); + return this.rawClient.deleteOrganizationMembership(request).body(); } /** @@ -163,58 +73,14 @@ public MembershipDeletionResponse deleteOrganizationMembership(DeleteMembershipR */ public MembershipDeletionResponse deleteOrganizationMembership(DeleteMembershipRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("organizations/memberships") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MembershipDeletionResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.deleteOrganizationMembership(request, requestOptions).body(); } /** * Get all memberships for a specific project (requires organization-scoped API key) */ public MembershipsResponse getProjectMemberships(String projectId) { - return getProjectMemberships(projectId,null); + return this.rawClient.getProjectMemberships(projectId).body(); } /** @@ -222,53 +88,14 @@ public MembershipsResponse getProjectMemberships(String projectId) { */ public MembershipsResponse getProjectMemberships(String projectId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .addPathSegments("memberships") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MembershipsResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getProjectMemberships(projectId, requestOptions).body(); } /** * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. */ public MembershipResponse updateProjectMembership(String projectId, MembershipRequest request) { - return updateProjectMembership(projectId,request,null); + return this.rawClient.updateProjectMembership(projectId, request).body(); } /** @@ -276,53 +103,7 @@ public MembershipResponse updateProjectMembership(String projectId, MembershipRe */ public MembershipResponse updateProjectMembership(String projectId, MembershipRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .addPathSegments("memberships") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MembershipResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.updateProjectMembership(projectId, request, requestOptions).body(); } /** @@ -330,7 +111,7 @@ public MembershipResponse updateProjectMembership(String projectId, MembershipRe */ public MembershipDeletionResponse deleteProjectMembership(String projectId, DeleteMembershipRequest request) { - return deleteProjectMembership(projectId,request,null); + return this.rawClient.deleteProjectMembership(projectId, request).body(); } /** @@ -338,154 +119,34 @@ public MembershipDeletionResponse deleteProjectMembership(String projectId, */ public MembershipDeletionResponse deleteProjectMembership(String projectId, DeleteMembershipRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .addPathSegments("memberships") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), MembershipDeletionResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.deleteProjectMembership(projectId, request, requestOptions).body(); } /** * Get all projects for the organization associated with the API key (requires organization-scoped API key) */ public OrganizationProjectsResponse getOrganizationProjects() { - return getOrganizationProjects(null); + return this.rawClient.getOrganizationProjects().body(); } /** * Get all projects for the organization associated with the API key (requires organization-scoped API key) */ public OrganizationProjectsResponse getOrganizationProjects(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("organizations/projects") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), OrganizationProjectsResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getOrganizationProjects(requestOptions).body(); } /** * Get all API keys for the organization associated with the API key (requires organization-scoped API key) */ public OrganizationApiKeysResponse getOrganizationApiKeys() { - return getOrganizationApiKeys(null); + return this.rawClient.getOrganizationApiKeys().body(); } /** * Get all API keys for the organization associated with the API key (requires organization-scoped API key) */ public OrganizationApiKeysResponse getOrganizationApiKeys(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("organizations/apiKeys") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), OrganizationApiKeysResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getOrganizationApiKeys(requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/RawOrganizationsClient.java b/src/main/java/com/langfuse/client/resources/organizations/RawOrganizationsClient.java new file mode 100644 index 0000000..7b53e3f --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/organizations/RawOrganizationsClient.java @@ -0,0 +1,529 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.organizations; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.organizations.types.DeleteMembershipRequest; +import com.langfuse.client.resources.organizations.types.MembershipDeletionResponse; +import com.langfuse.client.resources.organizations.types.MembershipRequest; +import com.langfuse.client.resources.organizations.types.MembershipResponse; +import com.langfuse.client.resources.organizations.types.MembershipsResponse; +import com.langfuse.client.resources.organizations.types.OrganizationApiKeysResponse; +import com.langfuse.client.resources.organizations.types.OrganizationProjectsResponse; + +public class RawOrganizationsClient { + protected final ClientOptions clientOptions; + + public RawOrganizationsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get all memberships for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getOrganizationMemberships() { + return getOrganizationMemberships(null); + } + + /** + * Get all memberships for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getOrganizationMemberships( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipsResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse updateOrganizationMembership( + MembershipRequest request) { + return updateOrganizationMembership(request,null); + } + + /** + * Create or update a membership for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse updateOrganizationMembership( + MembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a membership from the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse deleteOrganizationMembership( + DeleteMembershipRequest request) { + return deleteOrganizationMembership(request,null); + } + + /** + * Delete a membership from the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse deleteOrganizationMembership( + DeleteMembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipDeletionResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get all memberships for a specific project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getProjectMemberships( + String projectId) { + return getProjectMemberships(projectId,null); + } + + /** + * Get all memberships for a specific project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getProjectMemberships( + String projectId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipsResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. + */ + public LangfuseClientHttpResponse updateProjectMembership( + String projectId, MembershipRequest request) { + return updateProjectMembership(projectId,request,null); + } + + /** + * Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization. + */ + public LangfuseClientHttpResponse updateProjectMembership( + String projectId, MembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a membership from a specific project (requires organization-scoped API key). The user must be a member of the organization. + */ + public LangfuseClientHttpResponse deleteProjectMembership( + String projectId, DeleteMembershipRequest request) { + return deleteProjectMembership(projectId,request,null); + } + + /** + * Delete a membership from a specific project (requires organization-scoped API key). The user must be a member of the organization. + */ + public LangfuseClientHttpResponse deleteProjectMembership( + String projectId, DeleteMembershipRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("memberships");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, MembershipDeletionResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get all projects for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getOrganizationProjects( + ) { + return getOrganizationProjects(null); + } + + /** + * Get all projects for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getOrganizationProjects( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/projects");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OrganizationProjectsResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get all API keys for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getOrganizationApiKeys( + ) { + return getOrganizationApiKeys(null); + } + + /** + * Get all API keys for the organization associated with the API key (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getOrganizationApiKeys( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("organizations/apiKeys");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OrganizationApiKeysResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/DeleteMembershipRequest.java b/src/main/java/com/langfuse/client/resources/organizations/types/DeleteMembershipRequest.java index 6c78e2d..a48b96c 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/DeleteMembershipRequest.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/DeleteMembershipRequest.java @@ -75,6 +75,10 @@ public interface UserIdStage { public interface _FinalStage { DeleteMembershipRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -106,5 +110,17 @@ public _FinalStage userId(@NotNull String userId) { public DeleteMembershipRequest build() { return new DeleteMembershipRequest(userId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipDeletionResponse.java b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipDeletionResponse.java index ee84d49..ec91246 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipDeletionResponse.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipDeletionResponse.java @@ -88,6 +88,10 @@ public interface UserIdStage { public interface _FinalStage { MembershipDeletionResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -129,5 +133,17 @@ public _FinalStage userId(@NotNull String userId) { public MembershipDeletionResponse build() { return new MembershipDeletionResponse(message, userId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRequest.java b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRequest.java index e7f113f..9be5a7c 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRequest.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRequest.java @@ -88,6 +88,10 @@ public interface RoleStage { public interface _FinalStage { MembershipRequest build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -129,5 +133,17 @@ public _FinalStage role(@NotNull MembershipRole role) { public MembershipRequest build() { return new MembershipRequest(userId, role, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipResponse.java b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipResponse.java index 6270b99..214d0de 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipResponse.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipResponse.java @@ -112,6 +112,10 @@ public interface NameStage { public interface _FinalStage { MembershipResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -173,5 +177,17 @@ public _FinalStage name(@NotNull String name) { public MembershipResponse build() { return new MembershipResponse(userId, role, email, name, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRole.java b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRole.java index 53f2c79..93c4b58 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRole.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipRole.java @@ -4,27 +4,105 @@ package com.langfuse.client.resources.organizations.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum MembershipRole { - OWNER("OWNER"), +public final class MembershipRole { + public static final MembershipRole OWNER = new MembershipRole(Value.OWNER, "OWNER"); - ADMIN("ADMIN"), + public static final MembershipRole MEMBER = new MembershipRole(Value.MEMBER, "MEMBER"); - MEMBER("MEMBER"), + public static final MembershipRole ADMIN = new MembershipRole(Value.ADMIN, "ADMIN"); - VIEWER("VIEWER"); + public static final MembershipRole VIEWER = new MembershipRole(Value.VIEWER, "VIEWER"); - private final String value; + private final Value value; - MembershipRole(String value) { + private final String string; + + MembershipRole(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof MembershipRole && this.string.equals(((MembershipRole) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case OWNER: + return visitor.visitOwner(); + case MEMBER: + return visitor.visitMember(); + case ADMIN: + return visitor.visitAdmin(); + case VIEWER: + return visitor.visitViewer(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static MembershipRole valueOf(String value) { + switch (value) { + case "OWNER": + return OWNER; + case "MEMBER": + return MEMBER; + case "ADMIN": + return ADMIN; + case "VIEWER": + return VIEWER; + default: + return new MembershipRole(Value.UNKNOWN, value); + } + } + + public enum Value { + OWNER, + + ADMIN, + + MEMBER, + + VIEWER, + + UNKNOWN + } + + public interface Visitor { + T visitOwner(); + + T visitAdmin(); + + T visitMember(); + + T visitViewer(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipsResponse.java b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipsResponse.java index e8c8bee..6ef0284 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/MembershipsResponse.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/MembershipsResponse.java @@ -93,7 +93,9 @@ public Builder from(MembershipsResponse other) { ) public Builder memberships(List memberships) { this.memberships.clear(); - this.memberships.addAll(memberships); + if (memberships != null) { + this.memberships.addAll(memberships); + } return this; } @@ -103,12 +105,24 @@ public Builder addMemberships(MembershipResponse memberships) { } public Builder addAllMemberships(List memberships) { - this.memberships.addAll(memberships); + if (memberships != null) { + this.memberships.addAll(memberships); + } return this; } public MembershipsResponse build() { return new MembershipsResponse(memberships, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKey.java b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKey.java index 0c1a5c2..a6f55e8 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKey.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKey.java @@ -142,6 +142,10 @@ public interface DisplaySecretKeyStage { public interface _FinalStage { OrganizationApiKey build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage expiresAt(Optional expiresAt); _FinalStage expiresAt(OffsetDateTime expiresAt); @@ -271,5 +275,17 @@ public _FinalStage expiresAt(Optional expiresAt) { public OrganizationApiKey build() { return new OrganizationApiKey(id, createdAt, expiresAt, lastUsedAt, note, publicKey, displaySecretKey, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKeysResponse.java b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKeysResponse.java index 7ab5313..4a813a2 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKeysResponse.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationApiKeysResponse.java @@ -93,7 +93,9 @@ public Builder from(OrganizationApiKeysResponse other) { ) public Builder apiKeys(List apiKeys) { this.apiKeys.clear(); - this.apiKeys.addAll(apiKeys); + if (apiKeys != null) { + this.apiKeys.addAll(apiKeys); + } return this; } @@ -103,12 +105,24 @@ public Builder addApiKeys(OrganizationApiKey apiKeys) { } public Builder addAllApiKeys(List apiKeys) { - this.apiKeys.addAll(apiKeys); + if (apiKeys != null) { + this.apiKeys.addAll(apiKeys); + } return this; } public OrganizationApiKeysResponse build() { return new OrganizationApiKeysResponse(apiKeys, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProject.java b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProject.java index 1f4e181..b68c262 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProject.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProject.java @@ -125,6 +125,10 @@ public interface UpdatedAtStage { public interface _FinalStage { OrganizationProject build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage metadata(Optional> metadata); _FinalStage metadata(Map metadata); @@ -208,5 +212,17 @@ public _FinalStage metadata(Optional> metadata) { public OrganizationProject build() { return new OrganizationProject(id, name, metadata, createdAt, updatedAt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProjectsResponse.java b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProjectsResponse.java index 9ac5585..bc3434d 100644 --- a/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProjectsResponse.java +++ b/src/main/java/com/langfuse/client/resources/organizations/types/OrganizationProjectsResponse.java @@ -93,7 +93,9 @@ public Builder from(OrganizationProjectsResponse other) { ) public Builder projects(List projects) { this.projects.clear(); - this.projects.addAll(projects); + if (projects != null) { + this.projects.addAll(projects); + } return this; } @@ -103,12 +105,24 @@ public Builder addProjects(OrganizationProject projects) { } public Builder addAllProjects(List projects) { - this.projects.addAll(projects); + if (projects != null) { + this.projects.addAll(projects); + } return this; } public OrganizationProjectsResponse build() { return new OrganizationProjectsResponse(projects, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/AsyncProjectsClient.java b/src/main/java/com/langfuse/client/resources/projects/AsyncProjectsClient.java new file mode 100644 index 0000000..f39b86b --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/projects/AsyncProjectsClient.java @@ -0,0 +1,156 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.projects; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.projects.requests.CreateApiKeyRequest; +import com.langfuse.client.resources.projects.requests.CreateProjectRequest; +import com.langfuse.client.resources.projects.requests.UpdateProjectRequest; +import com.langfuse.client.resources.projects.types.ApiKeyDeletionResponse; +import com.langfuse.client.resources.projects.types.ApiKeyList; +import com.langfuse.client.resources.projects.types.ApiKeyResponse; +import com.langfuse.client.resources.projects.types.Project; +import com.langfuse.client.resources.projects.types.ProjectDeletionResponse; +import com.langfuse.client.resources.projects.types.Projects; + +public class AsyncProjectsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawProjectsClient rawClient; + + public AsyncProjectsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawProjectsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawProjectsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. + */ + public CompletableFuture get() { + return this.rawClient.get().thenApply(response -> response.body()); + } + + /** + * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. + */ + public CompletableFuture get(RequestOptions requestOptions) { + return this.rawClient.get(requestOptions).thenApply(response -> response.body()); + } + + /** + * Create a new project (requires organization-scoped API key) + */ + public CompletableFuture create(CreateProjectRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a new project (requires organization-scoped API key) + */ + public CompletableFuture create(CreateProjectRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Update a project by ID (requires organization-scoped API key). + */ + public CompletableFuture update(String projectId, UpdateProjectRequest request) { + return this.rawClient.update(projectId, request).thenApply(response -> response.body()); + } + + /** + * Update a project by ID (requires organization-scoped API key). + */ + public CompletableFuture update(String projectId, UpdateProjectRequest request, + RequestOptions requestOptions) { + return this.rawClient.update(projectId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. + */ + public CompletableFuture delete(String projectId) { + return this.rawClient.delete(projectId).thenApply(response -> response.body()); + } + + /** + * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. + */ + public CompletableFuture delete(String projectId, + RequestOptions requestOptions) { + return this.rawClient.delete(projectId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all API keys for a project (requires organization-scoped API key) + */ + public CompletableFuture getApiKeys(String projectId) { + return this.rawClient.getApiKeys(projectId).thenApply(response -> response.body()); + } + + /** + * Get all API keys for a project (requires organization-scoped API key) + */ + public CompletableFuture getApiKeys(String projectId, RequestOptions requestOptions) { + return this.rawClient.getApiKeys(projectId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture createApiKey(String projectId) { + return this.rawClient.createApiKey(projectId).thenApply(response -> response.body()); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture createApiKey(String projectId, + RequestOptions requestOptions) { + return this.rawClient.createApiKey(projectId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture createApiKey(String projectId, + CreateApiKeyRequest request) { + return this.rawClient.createApiKey(projectId, request).thenApply(response -> response.body()); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture createApiKey(String projectId, + CreateApiKeyRequest request, RequestOptions requestOptions) { + return this.rawClient.createApiKey(projectId, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete an API key for a project (requires organization-scoped API key) + */ + public CompletableFuture deleteApiKey(String projectId, String apiKeyId) { + return this.rawClient.deleteApiKey(projectId, apiKeyId).thenApply(response -> response.body()); + } + + /** + * Delete an API key for a project (requires organization-scoped API key) + */ + public CompletableFuture deleteApiKey(String projectId, String apiKeyId, + RequestOptions requestOptions) { + return this.rawClient.deleteApiKey(projectId, apiKeyId, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/projects/AsyncRawProjectsClient.java b/src/main/java/com/langfuse/client/resources/projects/AsyncRawProjectsClient.java new file mode 100644 index 0000000..8740c4c --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/projects/AsyncRawProjectsClient.java @@ -0,0 +1,617 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.projects; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.projects.requests.CreateApiKeyRequest; +import com.langfuse.client.resources.projects.requests.CreateProjectRequest; +import com.langfuse.client.resources.projects.requests.UpdateProjectRequest; +import com.langfuse.client.resources.projects.types.ApiKeyDeletionResponse; +import com.langfuse.client.resources.projects.types.ApiKeyList; +import com.langfuse.client.resources.projects.types.ApiKeyResponse; +import com.langfuse.client.resources.projects.types.Project; +import com.langfuse.client.resources.projects.types.ProjectDeletionResponse; +import com.langfuse.client.resources.projects.types.Projects; + +public class AsyncRawProjectsClient { + protected final ClientOptions clientOptions; + + public AsyncRawProjectsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. + */ + public CompletableFuture> get() { + return get(null); + } + + /** + * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. + */ + public CompletableFuture> get( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Projects.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create a new project (requires organization-scoped API key) + */ + public CompletableFuture> create( + CreateProjectRequest request) { + return create(request,null); + } + + /** + * Create a new project (requires organization-scoped API key) + */ + public CompletableFuture> create( + CreateProjectRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Project.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Update a project by ID (requires organization-scoped API key). + */ + public CompletableFuture> update(String projectId, + UpdateProjectRequest request) { + return update(projectId,request,null); + } + + /** + * Update a project by ID (requires organization-scoped API key). + */ + public CompletableFuture> update(String projectId, + UpdateProjectRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Project.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. + */ + public CompletableFuture> delete( + String projectId) { + return delete(projectId,null); + } + + /** + * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. + */ + public CompletableFuture> delete( + String projectId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ProjectDeletionResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get all API keys for a project (requires organization-scoped API key) + */ + public CompletableFuture> getApiKeys( + String projectId) { + return getApiKeys(projectId,null); + } + + /** + * Get all API keys for a project (requires organization-scoped API key) + */ + public CompletableFuture> getApiKeys( + String projectId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("apiKeys");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ApiKeyList.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture> createApiKey( + String projectId) { + return createApiKey(projectId,CreateApiKeyRequest.builder().build()); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture> createApiKey( + String projectId, RequestOptions requestOptions) { + return createApiKey(projectId,CreateApiKeyRequest.builder().build(),requestOptions); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture> createApiKey( + String projectId, CreateApiKeyRequest request) { + return createApiKey(projectId,request,null); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public CompletableFuture> createApiKey( + String projectId, CreateApiKeyRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("apiKeys");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ApiKeyResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete an API key for a project (requires organization-scoped API key) + */ + public CompletableFuture> deleteApiKey( + String projectId, String apiKeyId) { + return deleteApiKey(projectId,apiKeyId,null); + } + + /** + * Delete an API key for a project (requires organization-scoped API key) + */ + public CompletableFuture> deleteApiKey( + String projectId, String apiKeyId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("apiKeys") + .addPathSegment(apiKeyId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ApiKeyDeletionResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/projects/ProjectsClient.java b/src/main/java/com/langfuse/client/resources/projects/ProjectsClient.java index f96cbe7..694abe2 100644 --- a/src/main/java/com/langfuse/client/resources/projects/ProjectsClient.java +++ b/src/main/java/com/langfuse/client/resources/projects/ProjectsClient.java @@ -4,28 +4,9 @@ package com.langfuse.client.resources.projects; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.projects.requests.CreateApiKeyRequest; import com.langfuse.client.resources.projects.requests.CreateProjectRequest; import com.langfuse.client.resources.projects.requests.UpdateProjectRequest; @@ -39,124 +20,53 @@ public class ProjectsClient { protected final ClientOptions clientOptions; + private final RawProjectsClient rawClient; + public ProjectsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawProjectsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawProjectsClient withRawResponse() { + return this.rawClient; } /** * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. */ public Projects get() { - return get(null); + return this.rawClient.get().body(); } /** * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. */ public Projects get(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Projects.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.get(requestOptions).body(); } /** * Create a new project (requires organization-scoped API key) */ public Project create(CreateProjectRequest request) { - return create(request,null); + return this.rawClient.create(request).body(); } /** * Create a new project (requires organization-scoped API key) */ public Project create(CreateProjectRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Project.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * Update a project by ID (requires organization-scoped API key). */ public Project update(String projectId, UpdateProjectRequest request) { - return update(projectId,request,null); + return this.rawClient.update(projectId, request).body(); } /** @@ -164,171 +74,56 @@ public Project update(String projectId, UpdateProjectRequest request) { */ public Project update(String projectId, UpdateProjectRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PUT", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Project.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.update(projectId, request, requestOptions).body(); } /** * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. */ public ProjectDeletionResponse delete(String projectId) { - return delete(projectId,null); + return this.rawClient.delete(projectId).body(); } /** * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. */ public ProjectDeletionResponse delete(String projectId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ProjectDeletionResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.delete(projectId, requestOptions).body(); } /** * Get all API keys for a project (requires organization-scoped API key) */ public ApiKeyList getApiKeys(String projectId) { - return getApiKeys(projectId,null); + return this.rawClient.getApiKeys(projectId).body(); } /** * Get all API keys for a project (requires organization-scoped API key) */ public ApiKeyList getApiKeys(String projectId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .addPathSegments("apiKeys") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ApiKeyList.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getApiKeys(projectId, requestOptions).body(); } /** * Create a new API key for a project (requires organization-scoped API key) */ public ApiKeyResponse createApiKey(String projectId) { - return createApiKey(projectId,CreateApiKeyRequest.builder().build()); + return this.rawClient.createApiKey(projectId).body(); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public ApiKeyResponse createApiKey(String projectId, RequestOptions requestOptions) { + return this.rawClient.createApiKey(projectId, requestOptions).body(); } /** * Create a new API key for a project (requires organization-scoped API key) */ public ApiKeyResponse createApiKey(String projectId, CreateApiKeyRequest request) { - return createApiKey(projectId,request,null); + return this.rawClient.createApiKey(projectId, request).body(); } /** @@ -336,60 +131,14 @@ public ApiKeyResponse createApiKey(String projectId, CreateApiKeyRequest request */ public ApiKeyResponse createApiKey(String projectId, CreateApiKeyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .addPathSegments("apiKeys") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ApiKeyResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.createApiKey(projectId, request, requestOptions).body(); } /** * Delete an API key for a project (requires organization-scoped API key) */ public ApiKeyDeletionResponse deleteApiKey(String projectId, String apiKeyId) { - return deleteApiKey(projectId,apiKeyId,null); + return this.rawClient.deleteApiKey(projectId, apiKeyId).body(); } /** @@ -397,46 +146,6 @@ public ApiKeyDeletionResponse deleteApiKey(String projectId, String apiKeyId) { */ public ApiKeyDeletionResponse deleteApiKey(String projectId, String apiKeyId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("projects") - .addPathSegment(projectId) - .addPathSegments("apiKeys") - .addPathSegment(apiKeyId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ApiKeyDeletionResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.deleteApiKey(projectId, apiKeyId, requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/projects/RawProjectsClient.java b/src/main/java/com/langfuse/client/resources/projects/RawProjectsClient.java new file mode 100644 index 0000000..b81d4d2 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/projects/RawProjectsClient.java @@ -0,0 +1,481 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.projects; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.projects.requests.CreateApiKeyRequest; +import com.langfuse.client.resources.projects.requests.CreateProjectRequest; +import com.langfuse.client.resources.projects.requests.UpdateProjectRequest; +import com.langfuse.client.resources.projects.types.ApiKeyDeletionResponse; +import com.langfuse.client.resources.projects.types.ApiKeyList; +import com.langfuse.client.resources.projects.types.ApiKeyResponse; +import com.langfuse.client.resources.projects.types.Project; +import com.langfuse.client.resources.projects.types.ProjectDeletionResponse; +import com.langfuse.client.resources.projects.types.Projects; + +public class RawProjectsClient { + protected final ClientOptions clientOptions; + + public RawProjectsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. + */ + public LangfuseClientHttpResponse get() { + return get(null); + } + + /** + * Get Project associated with API key (requires project-scoped API key). You can use GET /api/public/organizations/projects to get all projects with an organization-scoped key. + */ + public LangfuseClientHttpResponse get(RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Projects.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create a new project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse create(CreateProjectRequest request) { + return create(request,null); + } + + /** + * Create a new project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse create(CreateProjectRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Project.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Update a project by ID (requires organization-scoped API key). + */ + public LangfuseClientHttpResponse update(String projectId, + UpdateProjectRequest request) { + return update(projectId,request,null); + } + + /** + * Update a project by ID (requires organization-scoped API key). + */ + public LangfuseClientHttpResponse update(String projectId, + UpdateProjectRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Project.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. + */ + public LangfuseClientHttpResponse delete(String projectId) { + return delete(projectId,null); + } + + /** + * Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. + */ + public LangfuseClientHttpResponse delete(String projectId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ProjectDeletionResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get all API keys for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getApiKeys(String projectId) { + return getApiKeys(projectId,null); + } + + /** + * Get all API keys for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getApiKeys(String projectId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("apiKeys");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ApiKeyList.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse createApiKey(String projectId) { + return createApiKey(projectId,CreateApiKeyRequest.builder().build()); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse createApiKey(String projectId, + RequestOptions requestOptions) { + return createApiKey(projectId,CreateApiKeyRequest.builder().build(),requestOptions); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse createApiKey(String projectId, + CreateApiKeyRequest request) { + return createApiKey(projectId,request,null); + } + + /** + * Create a new API key for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse createApiKey(String projectId, + CreateApiKeyRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("apiKeys");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ApiKeyResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete an API key for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse deleteApiKey( + String projectId, String apiKeyId) { + return deleteApiKey(projectId,apiKeyId,null); + } + + /** + * Delete an API key for a project (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse deleteApiKey( + String projectId, String apiKeyId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("projects") + .addPathSegment(projectId) + .addPathSegments("apiKeys") + .addPathSegment(apiKeyId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ApiKeyDeletionResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/projects/requests/CreateApiKeyRequest.java b/src/main/java/com/langfuse/client/resources/projects/requests/CreateApiKeyRequest.java index ddc3e85..89ce1e6 100644 --- a/src/main/java/com/langfuse/client/resources/projects/requests/CreateApiKeyRequest.java +++ b/src/main/java/com/langfuse/client/resources/projects/requests/CreateApiKeyRequest.java @@ -117,6 +117,9 @@ public Builder from(CreateApiKeyRequest other) { return this; } + /** + *

        Optional note for the API key

        + */ @JsonSetter( value = "note", nulls = Nulls.SKIP @@ -131,6 +134,9 @@ public Builder note(String note) { return this; } + /** + *

        Optional predefined public key. Must start with 'pk-lf-'. If provided, secretKey must also be provided.

        + */ @JsonSetter( value = "publicKey", nulls = Nulls.SKIP @@ -145,6 +151,9 @@ public Builder publicKey(String publicKey) { return this; } + /** + *

        Optional predefined secret key. Must start with 'sk-lf-'. If provided, publicKey must also be provided.

        + */ @JsonSetter( value = "secretKey", nulls = Nulls.SKIP @@ -162,5 +171,15 @@ public Builder secretKey(String secretKey) { public CreateApiKeyRequest build() { return new CreateApiKeyRequest(note, publicKey, secretKey, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/requests/CreateProjectRequest.java b/src/main/java/com/langfuse/client/resources/projects/requests/CreateProjectRequest.java index 0c8da05..e80c9c3 100644 --- a/src/main/java/com/langfuse/client/resources/projects/requests/CreateProjectRequest.java +++ b/src/main/java/com/langfuse/client/resources/projects/requests/CreateProjectRequest.java @@ -99,12 +99,22 @@ public interface NameStage { } public interface RetentionStage { + /** + *

        Number of days to retain data. Must be 0 or at least 3 days. Requires data-retention entitlement for non-zero values. Optional.

        + */ _FinalStage retention(int retention); } public interface _FinalStage { CreateProjectRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional metadata for the project

        + */ _FinalStage metadata(Optional> metadata); _FinalStage metadata(Map metadata); @@ -142,6 +152,7 @@ public RetentionStage name(@NotNull String name) { } /** + *

        Number of days to retain data. Must be 0 or at least 3 days. Requires data-retention entitlement for non-zero values. Optional.

        *

        Number of days to retain data. Must be 0 or at least 3 days. Requires data-retention entitlement for non-zero values. Optional.

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -162,6 +173,9 @@ public _FinalStage metadata(Map metadata) { return this; } + /** + *

        Optional metadata for the project

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -176,5 +190,17 @@ public _FinalStage metadata(Optional> metadata) { public CreateProjectRequest build() { return new CreateProjectRequest(name, metadata, retention, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/requests/UpdateProjectRequest.java b/src/main/java/com/langfuse/client/resources/projects/requests/UpdateProjectRequest.java index 48514a8..99d40d9 100644 --- a/src/main/java/com/langfuse/client/resources/projects/requests/UpdateProjectRequest.java +++ b/src/main/java/com/langfuse/client/resources/projects/requests/UpdateProjectRequest.java @@ -13,6 +13,7 @@ import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.langfuse.client.core.ObjectMappers; +import java.lang.Integer; import java.lang.Object; import java.lang.String; import java.util.HashMap; @@ -30,12 +31,12 @@ public final class UpdateProjectRequest { private final Optional> metadata; - private final int retention; + private final Optional retention; private final Map additionalProperties; - private UpdateProjectRequest(String name, Optional> metadata, int retention, - Map additionalProperties) { + private UpdateProjectRequest(String name, Optional> metadata, + Optional retention, Map additionalProperties) { this.name = name; this.metadata = metadata; this.retention = retention; @@ -56,10 +57,13 @@ public Optional> getMetadata() { } /** - * @return Number of days to retain data. Must be 0 or at least 3 days. Requires data-retention entitlement for non-zero values. Optional. + * @return Number of days to retain data. + * Must be 0 or at least 3 days. + * Requires data-retention entitlement for non-zero values. + * Optional. Will retain existing retention setting if omitted. */ @JsonProperty("retention") - public int getRetention() { + public Optional getRetention() { return retention; } @@ -75,7 +79,7 @@ public Map getAdditionalProperties() { } private boolean equalTo(UpdateProjectRequest other) { - return name.equals(other.name) && metadata.equals(other.metadata) && retention == other.retention; + return name.equals(other.name) && metadata.equals(other.metadata) && retention.equals(other.retention); } @java.lang.Override @@ -93,30 +97,43 @@ public static NameStage builder() { } public interface NameStage { - RetentionStage name(@NotNull String name); + _FinalStage name(@NotNull String name); Builder from(UpdateProjectRequest other); } - public interface RetentionStage { - _FinalStage retention(int retention); - } - public interface _FinalStage { UpdateProjectRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Optional metadata for the project

        + */ _FinalStage metadata(Optional> metadata); _FinalStage metadata(Map metadata); + + /** + *

        Number of days to retain data. + * Must be 0 or at least 3 days. + * Requires data-retention entitlement for non-zero values. + * Optional. Will retain existing retention setting if omitted.

        + */ + _FinalStage retention(Optional retention); + + _FinalStage retention(Integer retention); } @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements NameStage, RetentionStage, _FinalStage { + public static final class Builder implements NameStage, _FinalStage { private String name; - private int retention; + private Optional retention = Optional.empty(); private Optional> metadata = Optional.empty(); @@ -136,18 +153,36 @@ public Builder from(UpdateProjectRequest other) { @java.lang.Override @JsonSetter("name") - public RetentionStage name(@NotNull String name) { + public _FinalStage name(@NotNull String name) { this.name = Objects.requireNonNull(name, "name must not be null"); return this; } /** - *

        Number of days to retain data. Must be 0 or at least 3 days. Requires data-retention entitlement for non-zero values. Optional.

        + *

        Number of days to retain data. + * Must be 0 or at least 3 days. + * Requires data-retention entitlement for non-zero values. + * Optional. Will retain existing retention setting if omitted.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - @JsonSetter("retention") - public _FinalStage retention(int retention) { + public _FinalStage retention(Integer retention) { + this.retention = Optional.ofNullable(retention); + return this; + } + + /** + *

        Number of days to retain data. + * Must be 0 or at least 3 days. + * Requires data-retention entitlement for non-zero values. + * Optional. Will retain existing retention setting if omitted.

        + */ + @java.lang.Override + @JsonSetter( + value = "retention", + nulls = Nulls.SKIP + ) + public _FinalStage retention(Optional retention) { this.retention = retention; return this; } @@ -162,6 +197,9 @@ public _FinalStage metadata(Map metadata) { return this; } + /** + *

        Optional metadata for the project

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -176,5 +214,17 @@ public _FinalStage metadata(Optional> metadata) { public UpdateProjectRequest build() { return new UpdateProjectRequest(name, metadata, retention, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyDeletionResponse.java b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyDeletionResponse.java index ead19fe..3f8201c 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyDeletionResponse.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyDeletionResponse.java @@ -74,6 +74,10 @@ public interface SuccessStage { public interface _FinalStage { ApiKeyDeletionResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -105,5 +109,17 @@ public _FinalStage success(boolean success) { public ApiKeyDeletionResponse build() { return new ApiKeyDeletionResponse(success, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyList.java b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyList.java index 9812db6..d7b9880 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyList.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyList.java @@ -92,7 +92,9 @@ public Builder from(ApiKeyList other) { ) public Builder apiKeys(List apiKeys) { this.apiKeys.clear(); - this.apiKeys.addAll(apiKeys); + if (apiKeys != null) { + this.apiKeys.addAll(apiKeys); + } return this; } @@ -102,12 +104,24 @@ public Builder addApiKeys(ApiKeySummary apiKeys) { } public Builder addAllApiKeys(List apiKeys) { - this.apiKeys.addAll(apiKeys); + if (apiKeys != null) { + this.apiKeys.addAll(apiKeys); + } return this; } public ApiKeyList build() { return new ApiKeyList(apiKeys, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyResponse.java b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyResponse.java index 574576a..31e55c5 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyResponse.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeyResponse.java @@ -136,6 +136,10 @@ public interface DisplaySecretKeyStage { public interface _FinalStage { ApiKeyResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage note(Optional note); _FinalStage note(String note); @@ -229,5 +233,17 @@ public _FinalStage note(Optional note) { public ApiKeyResponse build() { return new ApiKeyResponse(id, createdAt, publicKey, secretKey, displaySecretKey, note, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeySummary.java b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeySummary.java index 22f9c30..c8a77da 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/ApiKeySummary.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/ApiKeySummary.java @@ -141,6 +141,10 @@ public interface DisplaySecretKeyStage { public interface _FinalStage { ApiKeySummary build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage expiresAt(Optional expiresAt); _FinalStage expiresAt(OffsetDateTime expiresAt); @@ -270,5 +274,17 @@ public _FinalStage expiresAt(Optional expiresAt) { public ApiKeySummary build() { return new ApiKeySummary(id, createdAt, expiresAt, lastUsedAt, note, publicKey, displaySecretKey, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/Organization.java b/src/main/java/com/langfuse/client/resources/projects/types/Organization.java index eed61e1..8967d00 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/Organization.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/Organization.java @@ -82,17 +82,27 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        The unique identifier of the organization

        + */ NameStage id(@NotNull String id); Builder from(Organization other); } public interface NameStage { + /** + *

        The name of the organization

        + */ _FinalStage name(@NotNull String name); } public interface _FinalStage { Organization build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -117,6 +127,7 @@ public Builder from(Organization other) { } /** + *

        The unique identifier of the organization

        *

        The unique identifier of the organization

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -128,6 +139,7 @@ public NameStage id(@NotNull String id) { } /** + *

        The name of the organization

        *

        The name of the organization

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -142,5 +154,17 @@ public _FinalStage name(@NotNull String name) { public Organization build() { return new Organization(id, name, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/Project.java b/src/main/java/com/langfuse/client/resources/projects/types/Project.java index 4da8735..7183bf1 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/Project.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/Project.java @@ -124,18 +124,31 @@ public interface NameStage { } public interface OrganizationStage { + /** + *

        The organization this project belongs to

        + */ _FinalStage organization(@NotNull Organization organization); } public interface _FinalStage { Project build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Metadata for the project

        + */ _FinalStage metadata(Map metadata); _FinalStage putAllMetadata(Map metadata); _FinalStage metadata(String key, Object value); + /** + *

        Number of days to retain data. Null or 0 means no retention. Omitted if no retention is configured.

        + */ _FinalStage retentionDays(Optional retentionDays); _FinalStage retentionDays(Integer retentionDays); @@ -186,6 +199,7 @@ public OrganizationStage name(@NotNull String name) { } /** + *

        The organization this project belongs to

        *

        The organization this project belongs to

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -206,6 +220,9 @@ public _FinalStage retentionDays(Integer retentionDays) { return this; } + /** + *

        Number of days to retain data. Null or 0 means no retention. Omitted if no retention is configured.

        + */ @java.lang.Override @JsonSetter( value = "retentionDays", @@ -232,10 +249,15 @@ public _FinalStage metadata(String key, Object value) { */ @java.lang.Override public _FinalStage putAllMetadata(Map metadata) { - this.metadata.putAll(metadata); + if (metadata != null) { + this.metadata.putAll(metadata); + } return this; } + /** + *

        Metadata for the project

        + */ @java.lang.Override @JsonSetter( value = "metadata", @@ -243,7 +265,9 @@ public _FinalStage putAllMetadata(Map metadata) { ) public _FinalStage metadata(Map metadata) { this.metadata.clear(); - this.metadata.putAll(metadata); + if (metadata != null) { + this.metadata.putAll(metadata); + } return this; } @@ -251,5 +275,17 @@ public _FinalStage metadata(Map metadata) { public Project build() { return new Project(id, name, organization, metadata, retentionDays, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/ProjectDeletionResponse.java b/src/main/java/com/langfuse/client/resources/projects/types/ProjectDeletionResponse.java index d0ffece..6cc7262 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/ProjectDeletionResponse.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/ProjectDeletionResponse.java @@ -88,6 +88,10 @@ public interface MessageStage { public interface _FinalStage { ProjectDeletionResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -129,5 +133,17 @@ public _FinalStage message(@NotNull String message) { public ProjectDeletionResponse build() { return new ProjectDeletionResponse(success, message, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/projects/types/Projects.java b/src/main/java/com/langfuse/client/resources/projects/types/Projects.java index 39f9d78..67303e7 100644 --- a/src/main/java/com/langfuse/client/resources/projects/types/Projects.java +++ b/src/main/java/com/langfuse/client/resources/projects/types/Projects.java @@ -92,7 +92,9 @@ public Builder from(Projects other) { ) public Builder data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -102,12 +104,24 @@ public Builder addData(Project data) { } public Builder addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } public Projects build() { return new Projects(data, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/AsyncPromptsClient.java b/src/main/java/com/langfuse/client/resources/prompts/AsyncPromptsClient.java new file mode 100644 index 0000000..af9a6e2 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/prompts/AsyncPromptsClient.java @@ -0,0 +1,137 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.prompts; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.prompts.requests.DeletePromptRequest; +import com.langfuse.client.resources.prompts.requests.GetPromptRequest; +import com.langfuse.client.resources.prompts.requests.ListPromptsMetaRequest; +import com.langfuse.client.resources.prompts.types.CreatePromptRequest; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.prompts.types.PromptMetaListResponse; + +public class AsyncPromptsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawPromptsClient rawClient; + + public AsyncPromptsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawPromptsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawPromptsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get a prompt + */ + public CompletableFuture get(String promptName) { + return this.rawClient.get(promptName).thenApply(response -> response.body()); + } + + /** + * Get a prompt + */ + public CompletableFuture get(String promptName, RequestOptions requestOptions) { + return this.rawClient.get(promptName, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a prompt + */ + public CompletableFuture get(String promptName, GetPromptRequest request) { + return this.rawClient.get(promptName, request).thenApply(response -> response.body()); + } + + /** + * Get a prompt + */ + public CompletableFuture get(String promptName, GetPromptRequest request, + RequestOptions requestOptions) { + return this.rawClient.get(promptName, request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture list(ListPromptsMetaRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture list(ListPromptsMetaRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create a new version for the prompt with the given name + */ + public CompletableFuture create(CreatePromptRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a new version for the prompt with the given name + */ + public CompletableFuture create(CreatePromptRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture delete(String promptName) { + return this.rawClient.delete(promptName).thenApply(response -> response.body()); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture delete(String promptName, RequestOptions requestOptions) { + return this.rawClient.delete(promptName, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture delete(String promptName, DeletePromptRequest request) { + return this.rawClient.delete(promptName, request).thenApply(response -> response.body()); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture delete(String promptName, DeletePromptRequest request, + RequestOptions requestOptions) { + return this.rawClient.delete(promptName, request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/prompts/AsyncRawPromptsClient.java b/src/main/java/com/langfuse/client/resources/prompts/AsyncRawPromptsClient.java new file mode 100644 index 0000000..2ad6145 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/prompts/AsyncRawPromptsClient.java @@ -0,0 +1,434 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.prompts; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.prompts.requests.DeletePromptRequest; +import com.langfuse.client.resources.prompts.requests.GetPromptRequest; +import com.langfuse.client.resources.prompts.requests.ListPromptsMetaRequest; +import com.langfuse.client.resources.prompts.types.CreatePromptRequest; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.prompts.types.PromptMetaListResponse; + +public class AsyncRawPromptsClient { + protected final ClientOptions clientOptions; + + public AsyncRawPromptsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a prompt + */ + public CompletableFuture> get(String promptName) { + return get(promptName,GetPromptRequest.builder().build()); + } + + /** + * Get a prompt + */ + public CompletableFuture> get(String promptName, + RequestOptions requestOptions) { + return get(promptName,GetPromptRequest.builder().build(),requestOptions); + } + + /** + * Get a prompt + */ + public CompletableFuture> get(String promptName, + GetPromptRequest request) { + return get(promptName,request,null); + } + + /** + * Get a prompt + */ + public CompletableFuture> get(String promptName, + GetPromptRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts") + .addPathSegment(promptName);if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getLabel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Prompt.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture> list() { + return list(ListPromptsMetaRequest.builder().build()); + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture> list( + RequestOptions requestOptions) { + return list(ListPromptsMetaRequest.builder().build(),requestOptions); + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture> list( + ListPromptsMetaRequest request) { + return list(request,null); + } + + /** + * Get a list of prompt names with versions and labels + */ + public CompletableFuture> list( + ListPromptsMetaRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts");if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getLabel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); + } + if (request.getTag().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "tag", request.getTag().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getFromUpdatedAt().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromUpdatedAt", request.getFromUpdatedAt().get(), false); + } + if (request.getToUpdatedAt().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toUpdatedAt", request.getToUpdatedAt().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PromptMetaListResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create a new version for the prompt with the given name + */ + public CompletableFuture> create( + CreatePromptRequest request) { + return create(request,null); + } + + /** + * Create a new version for the prompt with the given name + */ + public CompletableFuture> create( + CreatePromptRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Prompt.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture> delete(String promptName) { + return delete(promptName,DeletePromptRequest.builder().build()); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture> delete(String promptName, + RequestOptions requestOptions) { + return delete(promptName,DeletePromptRequest.builder().build(),requestOptions); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture> delete(String promptName, + DeletePromptRequest request) { + return delete(promptName,request,null); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public CompletableFuture> delete(String promptName, + DeletePromptRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts") + .addPathSegment(promptName);if (request.getLabel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/prompts/PromptsClient.java b/src/main/java/com/langfuse/client/resources/prompts/PromptsClient.java index b695cc6..809a69a 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/PromptsClient.java +++ b/src/main/java/com/langfuse/client/resources/prompts/PromptsClient.java @@ -4,29 +4,9 @@ package com.langfuse.client.resources.prompts; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.prompts.requests.DeletePromptRequest; import com.langfuse.client.resources.prompts.requests.GetPromptRequest; import com.langfuse.client.resources.prompts.requests.ListPromptsMetaRequest; @@ -37,269 +17,117 @@ public class PromptsClient { protected final ClientOptions clientOptions; + private final RawPromptsClient rawClient; + public PromptsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawPromptsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawPromptsClient withRawResponse() { + return this.rawClient; } /** * Get a prompt */ public Prompt get(String promptName) { - return get(promptName,GetPromptRequest.builder().build()); + return this.rawClient.get(promptName).body(); + } + + /** + * Get a prompt + */ + public Prompt get(String promptName, RequestOptions requestOptions) { + return this.rawClient.get(promptName, requestOptions).body(); } /** * Get a prompt */ public Prompt get(String promptName, GetPromptRequest request) { - return get(promptName,request,null); + return this.rawClient.get(promptName, request).body(); } /** * Get a prompt */ public Prompt get(String promptName, GetPromptRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/v2") - .addPathSegments("prompts") - .addPathSegment(promptName);if (request.getVersion().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get().toString(), false); - } - if (request.getLabel().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Prompt.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.get(promptName, request, requestOptions).body(); + } - /** - * Get a list of prompt names with versions and labels - */ - public PromptMetaListResponse list() { - return list(ListPromptsMetaRequest.builder().build()); - } + /** + * Get a list of prompt names with versions and labels + */ + public PromptMetaListResponse list() { + return this.rawClient.list().body(); + } - /** - * Get a list of prompt names with versions and labels - */ - public PromptMetaListResponse list(ListPromptsMetaRequest request) { - return list(request,null); - } + /** + * Get a list of prompt names with versions and labels + */ + public PromptMetaListResponse list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).body(); + } - /** - * Get a list of prompt names with versions and labels - */ - public PromptMetaListResponse list(ListPromptsMetaRequest request, - RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/v2") - .addPathSegments("prompts");if (request.getName().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); - } - if (request.getLabel().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); - } - if (request.getTag().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "tag", request.getTag().get(), false); - } - if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - if (request.getFromUpdatedAt().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fromUpdatedAt", request.getFromUpdatedAt().get().toString(), false); - } - if (request.getToUpdatedAt().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "toUpdatedAt", request.getToUpdatedAt().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PromptMetaListResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a list of prompt names with versions and labels + */ + public PromptMetaListResponse list(ListPromptsMetaRequest request) { + return this.rawClient.list(request).body(); + } - /** - * Create a new version for the prompt with the given name - */ - public Prompt create(CreatePromptRequest request) { - return create(request,null); - } + /** + * Get a list of prompt names with versions and labels + */ + public PromptMetaListResponse list(ListPromptsMetaRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).body(); + } - /** - * Create a new version for the prompt with the given name - */ - public Prompt create(CreatePromptRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/v2") - .addPathSegments("prompts") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Prompt.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Create a new version for the prompt with the given name + */ + public Prompt create(CreatePromptRequest request) { + return this.rawClient.create(request).body(); + } - /** - * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. - */ - public void delete(String promptName) { - delete(promptName,DeletePromptRequest.builder().build()); - } + /** + * Create a new version for the prompt with the given name + */ + public Prompt create(CreatePromptRequest request, RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).body(); + } - /** - * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. - */ - public void delete(String promptName, DeletePromptRequest request) { - delete(promptName,request,null); - } + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public void delete(String promptName) { + this.rawClient.delete(promptName).body(); + } - /** - * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. - */ - public void delete(String promptName, DeletePromptRequest request, - RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/v2") - .addPathSegments("prompts") - .addPathSegment(promptName);if (request.getLabel().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); - } - if (request.getVersion().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } - } + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public void delete(String promptName, RequestOptions requestOptions) { + this.rawClient.delete(promptName, requestOptions).body(); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public void delete(String promptName, DeletePromptRequest request) { + this.rawClient.delete(promptName, request).body(); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public void delete(String promptName, DeletePromptRequest request, + RequestOptions requestOptions) { + this.rawClient.delete(promptName, request, requestOptions).body(); + } +} diff --git a/src/main/java/com/langfuse/client/resources/prompts/RawPromptsClient.java b/src/main/java/com/langfuse/client/resources/prompts/RawPromptsClient.java new file mode 100644 index 0000000..0366217 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/prompts/RawPromptsClient.java @@ -0,0 +1,352 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.prompts; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import java.lang.Void; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.prompts.requests.DeletePromptRequest; +import com.langfuse.client.resources.prompts.requests.GetPromptRequest; +import com.langfuse.client.resources.prompts.requests.ListPromptsMetaRequest; +import com.langfuse.client.resources.prompts.types.CreatePromptRequest; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.prompts.types.PromptMetaListResponse; + +public class RawPromptsClient { + protected final ClientOptions clientOptions; + + public RawPromptsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a prompt + */ + public LangfuseClientHttpResponse get(String promptName) { + return get(promptName,GetPromptRequest.builder().build()); + } + + /** + * Get a prompt + */ + public LangfuseClientHttpResponse get(String promptName, RequestOptions requestOptions) { + return get(promptName,GetPromptRequest.builder().build(),requestOptions); + } + + /** + * Get a prompt + */ + public LangfuseClientHttpResponse get(String promptName, GetPromptRequest request) { + return get(promptName,request,null); + } + + /** + * Get a prompt + */ + public LangfuseClientHttpResponse get(String promptName, GetPromptRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts") + .addPathSegment(promptName);if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getLabel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Prompt.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a list of prompt names with versions and labels + */ + public LangfuseClientHttpResponse list() { + return list(ListPromptsMetaRequest.builder().build()); + } + + /** + * Get a list of prompt names with versions and labels + */ + public LangfuseClientHttpResponse list(RequestOptions requestOptions) { + return list(ListPromptsMetaRequest.builder().build(),requestOptions); + } + + /** + * Get a list of prompt names with versions and labels + */ + public LangfuseClientHttpResponse list(ListPromptsMetaRequest request) { + return list(request,null); + } + + /** + * Get a list of prompt names with versions and labels + */ + public LangfuseClientHttpResponse list(ListPromptsMetaRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts");if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getLabel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); + } + if (request.getTag().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "tag", request.getTag().get(), false); + } + if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getFromUpdatedAt().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromUpdatedAt", request.getFromUpdatedAt().get(), false); + } + if (request.getToUpdatedAt().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toUpdatedAt", request.getToUpdatedAt().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PromptMetaListResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create a new version for the prompt with the given name + */ + public LangfuseClientHttpResponse create(CreatePromptRequest request) { + return create(request,null); + } + + /** + * Create a new version for the prompt with the given name + */ + public LangfuseClientHttpResponse create(CreatePromptRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Prompt.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public LangfuseClientHttpResponse delete(String promptName) { + return delete(promptName,DeletePromptRequest.builder().build()); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public LangfuseClientHttpResponse delete(String promptName, + RequestOptions requestOptions) { + return delete(promptName,DeletePromptRequest.builder().build(),requestOptions); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public LangfuseClientHttpResponse delete(String promptName, + DeletePromptRequest request) { + return delete(promptName,request,null); + } + + /** + * Delete prompt versions. If neither version nor label is specified, all versions of the prompt are deleted. + */ + public LangfuseClientHttpResponse delete(String promptName, + DeletePromptRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts") + .addPathSegment(promptName);if (request.getLabel().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "label", request.getLabel().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/prompts/requests/DeletePromptRequest.java b/src/main/java/com/langfuse/client/resources/prompts/requests/DeletePromptRequest.java index a6f1f60..dc4abe0 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/requests/DeletePromptRequest.java +++ b/src/main/java/com/langfuse/client/resources/prompts/requests/DeletePromptRequest.java @@ -104,6 +104,9 @@ public Builder from(DeletePromptRequest other) { return this; } + /** + *

        Optional label to filter deletion. If specified, deletes all prompt versions that have this label.

        + */ @JsonSetter( value = "label", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder label(String label) { return this; } + /** + *

        Optional version to filter deletion. If specified, deletes only this specific version of the prompt.

        + */ @JsonSetter( value = "version", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder version(Integer version) { public DeletePromptRequest build() { return new DeletePromptRequest(label, version, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/requests/GetPromptRequest.java b/src/main/java/com/langfuse/client/resources/prompts/requests/GetPromptRequest.java index 46d7bb0..2e2a118 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/requests/GetPromptRequest.java +++ b/src/main/java/com/langfuse/client/resources/prompts/requests/GetPromptRequest.java @@ -104,6 +104,9 @@ public Builder from(GetPromptRequest other) { return this; } + /** + *

        Version of the prompt to be retrieved.

        + */ @JsonSetter( value = "version", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder version(Integer version) { return this; } + /** + *

        Label of the prompt to be retrieved. Defaults to "production" if no label or version is set.

        + */ @JsonSetter( value = "label", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder label(String label) { public GetPromptRequest build() { return new GetPromptRequest(version, label, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/requests/ListPromptsMetaRequest.java b/src/main/java/com/langfuse/client/resources/prompts/requests/ListPromptsMetaRequest.java index e42b5b7..f96eb56 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/requests/ListPromptsMetaRequest.java +++ b/src/main/java/com/langfuse/client/resources/prompts/requests/ListPromptsMetaRequest.java @@ -210,6 +210,9 @@ public Builder tag(String tag) { return this; } + /** + *

        page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -224,6 +227,9 @@ public Builder page(Integer page) { return this; } + /** + *

        limit of items per page

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -238,6 +244,9 @@ public Builder limit(Integer limit) { return this; } + /** + *

        Optional filter to only include prompt versions created/updated on or after a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "fromUpdatedAt", nulls = Nulls.SKIP @@ -252,6 +261,9 @@ public Builder fromUpdatedAt(OffsetDateTime fromUpdatedAt) { return this; } + /** + *

        Optional filter to only include prompt versions created/updated before a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "toUpdatedAt", nulls = Nulls.SKIP @@ -269,5 +281,15 @@ public Builder toUpdatedAt(OffsetDateTime toUpdatedAt) { public ListPromptsMetaRequest build() { return new ListPromptsMetaRequest(name, label, tag, page, limit, fromUpdatedAt, toUpdatedAt, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/BasePrompt.java b/src/main/java/com/langfuse/client/resources/prompts/types/BasePrompt.java index 1961c41..1299225 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/BasePrompt.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/BasePrompt.java @@ -157,22 +157,38 @@ public interface ConfigStage { public interface _FinalStage { BasePrompt build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        List of deployment labels of this prompt version.

        + */ _FinalStage labels(List labels); _FinalStage addLabels(String labels); _FinalStage addAllLabels(List labels); + /** + *

        List of tags. Used to filter via UI and API. The same across versions of a prompt.

        + */ _FinalStage tags(List tags); _FinalStage addTags(String tags); _FinalStage addAllTags(List tags); + /** + *

        Commit message for this prompt version.

        + */ _FinalStage commitMessage(Optional commitMessage); _FinalStage commitMessage(String commitMessage); + /** + *

        The dependency resolution graph for the current prompt. Null if prompt has no dependencies.

        + */ _FinalStage resolutionGraph(Optional> resolutionGraph); _FinalStage resolutionGraph(Map resolutionGraph); @@ -245,6 +261,9 @@ public _FinalStage resolutionGraph(Map resolutionGraph) { return this; } + /** + *

        The dependency resolution graph for the current prompt. Null if prompt has no dependencies.

        + */ @java.lang.Override @JsonSetter( value = "resolutionGraph", @@ -265,6 +284,9 @@ public _FinalStage commitMessage(String commitMessage) { return this; } + /** + *

        Commit message for this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "commitMessage", @@ -281,7 +303,9 @@ public _FinalStage commitMessage(Optional commitMessage) { */ @java.lang.Override public _FinalStage addAllTags(List tags) { - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -295,6 +319,9 @@ public _FinalStage addTags(String tags) { return this; } + /** + *

        List of tags. Used to filter via UI and API. The same across versions of a prompt.

        + */ @java.lang.Override @JsonSetter( value = "tags", @@ -302,7 +329,9 @@ public _FinalStage addTags(String tags) { ) public _FinalStage tags(List tags) { this.tags.clear(); - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -312,7 +341,9 @@ public _FinalStage tags(List tags) { */ @java.lang.Override public _FinalStage addAllLabels(List labels) { - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @@ -326,6 +357,9 @@ public _FinalStage addLabels(String labels) { return this; } + /** + *

        List of deployment labels of this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "labels", @@ -333,7 +367,9 @@ public _FinalStage addLabels(String labels) { ) public _FinalStage labels(List labels) { this.labels.clear(); - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @@ -341,5 +377,17 @@ public _FinalStage labels(List labels) { public BasePrompt build() { return new BasePrompt(name, version, config, labels, tags, commitMessage, resolutionGraph, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessage.java b/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessage.java index 6d7b4c7..050eaa7 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessage.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessage.java @@ -10,6 +10,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; @@ -17,6 +18,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.Optional; import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) @@ -28,11 +30,15 @@ public final class ChatMessage { private final String content; + private final Optional type; + private final Map additionalProperties; - private ChatMessage(String role, String content, Map additionalProperties) { + private ChatMessage(String role, String content, Optional type, + Map additionalProperties) { this.role = role; this.content = content; + this.type = type; this.additionalProperties = additionalProperties; } @@ -46,6 +52,11 @@ public String getContent() { return content; } + @JsonProperty("type") + public Optional getType() { + return type; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -58,12 +69,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(ChatMessage other) { - return role.equals(other.role) && content.equals(other.content); + return role.equals(other.role) && content.equals(other.content) && type.equals(other.type); } @java.lang.Override public int hashCode() { - return Objects.hash(this.role, this.content); + return Objects.hash(this.role, this.content, this.type); } @java.lang.Override @@ -87,6 +98,14 @@ public interface ContentStage { public interface _FinalStage { ChatMessage build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + _FinalStage type(Optional type); + + _FinalStage type(ChatMessageType type); } @JsonIgnoreProperties( @@ -97,6 +116,8 @@ public static final class Builder implements RoleStage, ContentStage, _FinalStag private String content; + private Optional type = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -107,6 +128,7 @@ private Builder() { public Builder from(ChatMessage other) { role(other.getRole()); content(other.getContent()); + type(other.getType()); return this; } @@ -124,9 +146,37 @@ public _FinalStage content(@NotNull String content) { return this; } + @java.lang.Override + public _FinalStage type(ChatMessageType type) { + this.type = Optional.ofNullable(type); + return this; + } + + @java.lang.Override + @JsonSetter( + value = "type", + nulls = Nulls.SKIP + ) + public _FinalStage type(Optional type) { + this.type = type; + return this; + } + @java.lang.Override public ChatMessage build() { - return new ChatMessage(role, content, additionalProperties); + return new ChatMessage(role, content, type, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessageType.java b/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessageType.java new file mode 100644 index 0000000..3c138e4 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessageType.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.prompts.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; +import java.lang.String; + +public final class ChatMessageType { + public static final ChatMessageType CHATMESSAGE = new ChatMessageType(Value.CHATMESSAGE, "chatmessage"); + + private final Value value; + + private final String string; + + ChatMessageType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatMessageType && this.string.equals(((ChatMessageType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case CHATMESSAGE: + return visitor.visitChatmessage(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static ChatMessageType valueOf(String value) { + switch (value) { + case "chatmessage": + return CHATMESSAGE; + default: + return new ChatMessageType(Value.UNKNOWN, value); + } + } + + public enum Value { + CHATMESSAGE, + + UNKNOWN + } + + public interface Visitor { + T visitChatmessage(); + + T visitUnknown(String unknownType); + } +} diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessageWithPlaceholders.java b/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessageWithPlaceholders.java index 38d29ce..769f683 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessageWithPlaceholders.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/ChatMessageWithPlaceholders.java @@ -4,224 +4,113 @@ package com.langfuse.client.resources.prompts.types; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.langfuse.client.core.ObjectMappers; +import java.io.IOException; +import java.lang.IllegalStateException; import java.lang.Object; +import java.lang.RuntimeException; import java.lang.String; +import java.lang.SuppressWarnings; +import java.util.Map; import java.util.Objects; -import java.util.Optional; +@JsonDeserialize( + using = ChatMessageWithPlaceholders.Deserializer.class +) public final class ChatMessageWithPlaceholders { - private final Value value; + private final Object value; - @JsonCreator( - mode = JsonCreator.Mode.DELEGATING - ) - private ChatMessageWithPlaceholders(Value value) { - this.value = value; - } - - public T visit(Visitor visitor) { - return value.visit(visitor); - } - - public static ChatMessageWithPlaceholders chatmessage(ChatMessage value) { - return new ChatMessageWithPlaceholders(new ChatmessageValue(value)); - } - - public static ChatMessageWithPlaceholders placeholder(PlaceholderMessage value) { - return new ChatMessageWithPlaceholders(new PlaceholderValue(value)); - } + private final int type; - public boolean isChatmessage() { - return value instanceof ChatmessageValue; - } - - public boolean isPlaceholder() { - return value instanceof PlaceholderValue; + private ChatMessageWithPlaceholders(Object value, int type) { + this.value = value; + this.type = type; } - public boolean _isUnknown() { - return value instanceof _UnknownValue; + @JsonValue + public Object get() { + return this.value; } - public Optional getChatmessage() { - if (isChatmessage()) { - return Optional.of(((ChatmessageValue) value).value); + @SuppressWarnings("unchecked") + public T visit(Visitor visitor) { + if(this.type == 0) { + return visitor.visit((ChatMessage) this.value); + } else if(this.type == 1) { + return visitor.visit((PlaceholderMessage) this.value); } - return Optional.empty(); + throw new IllegalStateException("Failed to visit value. This should never happen."); } - public Optional getPlaceholder() { - if (isPlaceholder()) { - return Optional.of(((PlaceholderValue) value).value); - } - return Optional.empty(); + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ChatMessageWithPlaceholders && equalTo((ChatMessageWithPlaceholders) other); } - public Optional _getUnknown() { - if (_isUnknown()) { - return Optional.of(((_UnknownValue) value).value); - } - return Optional.empty(); + private boolean equalTo(ChatMessageWithPlaceholders other) { + return value.equals(other.value); } - @JsonValue - private Value getValue() { - return this.value; + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value); } - public interface Visitor { - T visitChatmessage(ChatMessage chatmessage); - - T visitPlaceholder(PlaceholderMessage placeholder); - - T _visitUnknown(Object unknownType); + @java.lang.Override + public String toString() { + return this.value.toString(); } - @JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - visible = true, - defaultImpl = _UnknownValue.class - ) - @JsonSubTypes({ - @JsonSubTypes.Type(ChatmessageValue.class), - @JsonSubTypes.Type(PlaceholderValue.class) - }) - @JsonIgnoreProperties( - ignoreUnknown = true - ) - private interface Value { - T visit(Visitor visitor); + public static ChatMessageWithPlaceholders of(ChatMessage value) { + return new ChatMessageWithPlaceholders(value, 0); } - @JsonTypeName("chatmessage") - @JsonIgnoreProperties("type") - private static final class ChatmessageValue implements Value { - @JsonUnwrapped - private ChatMessage value; - - @JsonCreator( - mode = JsonCreator.Mode.PROPERTIES - ) - private ChatmessageValue() { - } - - private ChatmessageValue(ChatMessage value) { - this.value = value; - } - - @java.lang.Override - public T visit(Visitor visitor) { - return visitor.visitChatmessage(value); - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof ChatmessageValue && equalTo((ChatmessageValue) other); - } - - private boolean equalTo(ChatmessageValue other) { - return value.equals(other.value); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.value); - } - - @java.lang.Override - public String toString() { - return "ChatMessageWithPlaceholders{" + "value: " + value + "}"; - } + public static ChatMessageWithPlaceholders of(PlaceholderMessage value) { + return new ChatMessageWithPlaceholders(value, 1); } - @JsonTypeName("placeholder") - @JsonIgnoreProperties("type") - private static final class PlaceholderValue implements Value { - @JsonUnwrapped - private PlaceholderMessage value; - - @JsonCreator( - mode = JsonCreator.Mode.PROPERTIES - ) - private PlaceholderValue() { - } - - private PlaceholderValue(PlaceholderMessage value) { - this.value = value; - } - - @java.lang.Override - public T visit(Visitor visitor) { - return visitor.visitPlaceholder(value); - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof PlaceholderValue && equalTo((PlaceholderValue) other); - } - - private boolean equalTo(PlaceholderValue other) { - return value.equals(other.value); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.value); - } + public interface Visitor { + T visit(ChatMessage value); - @java.lang.Override - public String toString() { - return "ChatMessageWithPlaceholders{" + "value: " + value + "}"; - } + T visit(PlaceholderMessage value); } - @JsonIgnoreProperties("type") - private static final class _UnknownValue implements Value { - private String type; - - @JsonValue - private Object value; - - @JsonCreator( - mode = JsonCreator.Mode.PROPERTIES - ) - private _UnknownValue(@JsonProperty("value") Object value) { - } - - @java.lang.Override - public T visit(Visitor visitor) { - return visitor._visitUnknown(value); - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof _UnknownValue && equalTo((_UnknownValue) other); - } - - private boolean equalTo(_UnknownValue other) { - return type.equals(other.type) && value.equals(other.value); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.type, this.value); + static final class Deserializer extends StdDeserializer { + Deserializer() { + super(ChatMessageWithPlaceholders.class); } @java.lang.Override - public String toString() { - return "ChatMessageWithPlaceholders{" + "type: " + type + ", value: " + value + "}"; + public ChatMessageWithPlaceholders deserialize(JsonParser p, DeserializationContext context) + throws IOException { + Object value = p.readValueAs(Object.class); + // Use "type" discriminator when present — placeholder messages carry + // "type": "placeholder" while regular chat messages typically have no type field. + if (value instanceof Map) { + Map map = (Map) value; + if ("placeholder".equals(map.get("type"))) { + try { + return of(ObjectMappers.JSON_MAPPER.convertValue(value, PlaceholderMessage.class)); + } catch(RuntimeException e) { + } + } + } + try { + return of(ObjectMappers.JSON_MAPPER.convertValue(value, ChatMessage.class)); + } catch(RuntimeException e) { + } + try { + return of(ObjectMappers.JSON_MAPPER.convertValue(value, PlaceholderMessage.class)); + } catch(RuntimeException e) { + } + throw new JsonParseException(p, "Failed to deserialize"); } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/ChatPrompt.java b/src/main/java/com/langfuse/client/resources/prompts/types/ChatPrompt.java index f24e28f..9c52b2e 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/ChatPrompt.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/ChatPrompt.java @@ -166,22 +166,38 @@ public interface ConfigStage { public interface _FinalStage { ChatPrompt build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        List of deployment labels of this prompt version.

        + */ _FinalStage labels(List labels); _FinalStage addLabels(String labels); _FinalStage addAllLabels(List labels); + /** + *

        List of tags. Used to filter via UI and API. The same across versions of a prompt.

        + */ _FinalStage tags(List tags); _FinalStage addTags(String tags); _FinalStage addAllTags(List tags); + /** + *

        Commit message for this prompt version.

        + */ _FinalStage commitMessage(Optional commitMessage); _FinalStage commitMessage(String commitMessage); + /** + *

        The dependency resolution graph for the current prompt. Null if prompt has no dependencies.

        + */ _FinalStage resolutionGraph(Optional> resolutionGraph); _FinalStage resolutionGraph(Map resolutionGraph); @@ -255,7 +271,9 @@ public _FinalStage config(Object config) { @java.lang.Override public _FinalStage addAllPrompt(List prompt) { - this.prompt.addAll(prompt); + if (prompt != null) { + this.prompt.addAll(prompt); + } return this; } @@ -272,7 +290,9 @@ public _FinalStage addPrompt(ChatMessageWithPlaceholders prompt) { ) public _FinalStage prompt(List prompt) { this.prompt.clear(); - this.prompt.addAll(prompt); + if (prompt != null) { + this.prompt.addAll(prompt); + } return this; } @@ -286,6 +306,9 @@ public _FinalStage resolutionGraph(Map resolutionGraph) { return this; } + /** + *

        The dependency resolution graph for the current prompt. Null if prompt has no dependencies.

        + */ @java.lang.Override @JsonSetter( value = "resolutionGraph", @@ -306,6 +329,9 @@ public _FinalStage commitMessage(String commitMessage) { return this; } + /** + *

        Commit message for this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "commitMessage", @@ -322,7 +348,9 @@ public _FinalStage commitMessage(Optional commitMessage) { */ @java.lang.Override public _FinalStage addAllTags(List tags) { - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -336,6 +364,9 @@ public _FinalStage addTags(String tags) { return this; } + /** + *

        List of tags. Used to filter via UI and API. The same across versions of a prompt.

        + */ @java.lang.Override @JsonSetter( value = "tags", @@ -343,7 +374,9 @@ public _FinalStage addTags(String tags) { ) public _FinalStage tags(List tags) { this.tags.clear(); - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -353,7 +386,9 @@ public _FinalStage tags(List tags) { */ @java.lang.Override public _FinalStage addAllLabels(List labels) { - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @@ -367,6 +402,9 @@ public _FinalStage addLabels(String labels) { return this; } + /** + *

        List of deployment labels of this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "labels", @@ -374,7 +412,9 @@ public _FinalStage addLabels(String labels) { ) public _FinalStage labels(List labels) { this.labels.clear(); - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @@ -382,5 +422,17 @@ public _FinalStage labels(List labels) { public ChatPrompt build() { return new ChatPrompt(name, version, config, labels, tags, commitMessage, resolutionGraph, prompt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/CreateChatPromptRequest.java b/src/main/java/com/langfuse/client/resources/prompts/types/CreateChatPromptRequest.java index 535559f..4e4ff5d 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/CreateChatPromptRequest.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/CreateChatPromptRequest.java @@ -34,6 +34,8 @@ public final class CreateChatPromptRequest { private final Optional config; + private final CreateChatPromptType type; + private final Optional> labels; private final Optional> tags; @@ -43,11 +45,13 @@ public final class CreateChatPromptRequest { private final Map additionalProperties; private CreateChatPromptRequest(String name, List prompt, - Optional config, Optional> labels, Optional> tags, - Optional commitMessage, Map additionalProperties) { + Optional config, CreateChatPromptType type, Optional> labels, + Optional> tags, Optional commitMessage, + Map additionalProperties) { this.name = name; this.prompt = prompt; this.config = config; + this.type = type; this.labels = labels; this.tags = tags; this.commitMessage = commitMessage; @@ -69,6 +73,11 @@ public Optional getConfig() { return config; } + @JsonProperty("type") + public CreateChatPromptType getType() { + return type; + } + /** * @return List of deployment labels of this prompt version. */ @@ -105,12 +114,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(CreateChatPromptRequest other) { - return name.equals(other.name) && prompt.equals(other.prompt) && config.equals(other.config) && labels.equals(other.labels) && tags.equals(other.tags) && commitMessage.equals(other.commitMessage); + return name.equals(other.name) && prompt.equals(other.prompt) && config.equals(other.config) && type.equals(other.type) && labels.equals(other.labels) && tags.equals(other.tags) && commitMessage.equals(other.commitMessage); } @java.lang.Override public int hashCode() { - return Objects.hash(this.name, this.prompt, this.config, this.labels, this.tags, this.commitMessage); + return Objects.hash(this.name, this.prompt, this.config, this.type, this.labels, this.tags, this.commitMessage); } @java.lang.Override @@ -123,14 +132,22 @@ public static NameStage builder() { } public interface NameStage { - _FinalStage name(@NotNull String name); + TypeStage name(@NotNull String name); Builder from(CreateChatPromptRequest other); } + public interface TypeStage { + _FinalStage type(@NotNull CreateChatPromptType type); + } + public interface _FinalStage { CreateChatPromptRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage prompt(List prompt); _FinalStage addPrompt(ChatMessageWithPlaceholders prompt); @@ -141,14 +158,23 @@ public interface _FinalStage { _FinalStage config(Object config); + /** + *

        List of deployment labels of this prompt version.

        + */ _FinalStage labels(Optional> labels); _FinalStage labels(List labels); + /** + *

        List of tags to apply to all versions of this prompt.

        + */ _FinalStage tags(Optional> tags); _FinalStage tags(List tags); + /** + *

        Commit message for this prompt version.

        + */ _FinalStage commitMessage(Optional commitMessage); _FinalStage commitMessage(String commitMessage); @@ -157,9 +183,11 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements NameStage, _FinalStage { + public static final class Builder implements NameStage, TypeStage, _FinalStage { private String name; + private CreateChatPromptType type; + private Optional commitMessage = Optional.empty(); private Optional> tags = Optional.empty(); @@ -181,6 +209,7 @@ public Builder from(CreateChatPromptRequest other) { name(other.getName()); prompt(other.getPrompt()); config(other.getConfig()); + type(other.getType()); labels(other.getLabels()); tags(other.getTags()); commitMessage(other.getCommitMessage()); @@ -189,11 +218,18 @@ public Builder from(CreateChatPromptRequest other) { @java.lang.Override @JsonSetter("name") - public _FinalStage name(@NotNull String name) { + public TypeStage name(@NotNull String name) { this.name = Objects.requireNonNull(name, "name must not be null"); return this; } + @java.lang.Override + @JsonSetter("type") + public _FinalStage type(@NotNull CreateChatPromptType type) { + this.type = Objects.requireNonNull(type, "type must not be null"); + return this; + } + /** *

        Commit message for this prompt version.

        * @return Reference to {@code this} so that method calls can be chained together. @@ -204,6 +240,9 @@ public _FinalStage commitMessage(String commitMessage) { return this; } + /** + *

        Commit message for this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "commitMessage", @@ -224,6 +263,9 @@ public _FinalStage tags(List tags) { return this; } + /** + *

        List of tags to apply to all versions of this prompt.

        + */ @java.lang.Override @JsonSetter( value = "tags", @@ -244,6 +286,9 @@ public _FinalStage labels(List labels) { return this; } + /** + *

        List of deployment labels of this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "labels", @@ -272,7 +317,9 @@ public _FinalStage config(Optional config) { @java.lang.Override public _FinalStage addAllPrompt(List prompt) { - this.prompt.addAll(prompt); + if (prompt != null) { + this.prompt.addAll(prompt); + } return this; } @@ -289,13 +336,27 @@ public _FinalStage addPrompt(ChatMessageWithPlaceholders prompt) { ) public _FinalStage prompt(List prompt) { this.prompt.clear(); - this.prompt.addAll(prompt); + if (prompt != null) { + this.prompt.addAll(prompt); + } return this; } @java.lang.Override public CreateChatPromptRequest build() { - return new CreateChatPromptRequest(name, prompt, config, labels, tags, commitMessage, additionalProperties); + return new CreateChatPromptRequest(name, prompt, config, type, labels, tags, commitMessage, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/CreateChatPromptType.java b/src/main/java/com/langfuse/client/resources/prompts/types/CreateChatPromptType.java new file mode 100644 index 0000000..b1f4ef5 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/prompts/types/CreateChatPromptType.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.prompts.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; +import java.lang.String; + +public final class CreateChatPromptType { + public static final CreateChatPromptType CHAT = new CreateChatPromptType(Value.CHAT, "chat"); + + private final Value value; + + private final String string; + + CreateChatPromptType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof CreateChatPromptType && this.string.equals(((CreateChatPromptType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case CHAT: + return visitor.visitChat(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static CreateChatPromptType valueOf(String value) { + switch (value) { + case "chat": + return CHAT; + default: + return new CreateChatPromptType(Value.UNKNOWN, value); + } + } + + public enum Value { + CHAT, + + UNKNOWN + } + + public interface Visitor { + T visitChat(); + + T visitUnknown(String unknownType); + } +} diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/CreatePromptRequest.java b/src/main/java/com/langfuse/client/resources/prompts/types/CreatePromptRequest.java index d67bec4..627fe17 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/CreatePromptRequest.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/CreatePromptRequest.java @@ -4,224 +4,101 @@ package com.langfuse.client.resources.prompts.types; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.langfuse.client.core.ObjectMappers; +import java.io.IOException; +import java.lang.IllegalStateException; import java.lang.Object; +import java.lang.RuntimeException; import java.lang.String; +import java.lang.SuppressWarnings; import java.util.Objects; -import java.util.Optional; +@JsonDeserialize( + using = CreatePromptRequest.Deserializer.class +) public final class CreatePromptRequest { - private final Value value; + private final Object value; - @JsonCreator( - mode = JsonCreator.Mode.DELEGATING - ) - private CreatePromptRequest(Value value) { - this.value = value; - } - - public T visit(Visitor visitor) { - return value.visit(visitor); - } - - public static CreatePromptRequest chat(CreateChatPromptRequest value) { - return new CreatePromptRequest(new ChatValue(value)); - } - - public static CreatePromptRequest text(CreateTextPromptRequest value) { - return new CreatePromptRequest(new TextValue(value)); - } + private final int type; - public boolean isChat() { - return value instanceof ChatValue; - } - - public boolean isText() { - return value instanceof TextValue; + private CreatePromptRequest(Object value, int type) { + this.value = value; + this.type = type; } - public boolean _isUnknown() { - return value instanceof _UnknownValue; + @JsonValue + public Object get() { + return this.value; } - public Optional getChat() { - if (isChat()) { - return Optional.of(((ChatValue) value).value); + @SuppressWarnings("unchecked") + public T visit(Visitor visitor) { + if(this.type == 0) { + return visitor.visit((CreateChatPromptRequest) this.value); + } else if(this.type == 1) { + return visitor.visit((CreateTextPromptRequest) this.value); } - return Optional.empty(); + throw new IllegalStateException("Failed to visit value. This should never happen."); } - public Optional getText() { - if (isText()) { - return Optional.of(((TextValue) value).value); - } - return Optional.empty(); + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CreatePromptRequest && equalTo((CreatePromptRequest) other); } - public Optional _getUnknown() { - if (_isUnknown()) { - return Optional.of(((_UnknownValue) value).value); - } - return Optional.empty(); + private boolean equalTo(CreatePromptRequest other) { + return value.equals(other.value); } - @JsonValue - private Value getValue() { - return this.value; + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value); } - public interface Visitor { - T visitChat(CreateChatPromptRequest chat); - - T visitText(CreateTextPromptRequest text); - - T _visitUnknown(Object unknownType); + @java.lang.Override + public String toString() { + return this.value.toString(); } - @JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "type", - visible = true, - defaultImpl = _UnknownValue.class - ) - @JsonSubTypes({ - @JsonSubTypes.Type(ChatValue.class), - @JsonSubTypes.Type(TextValue.class) - }) - @JsonIgnoreProperties( - ignoreUnknown = true - ) - private interface Value { - T visit(Visitor visitor); + public static CreatePromptRequest of(CreateChatPromptRequest value) { + return new CreatePromptRequest(value, 0); } - @JsonTypeName("chat") - @JsonIgnoreProperties("type") - private static final class ChatValue implements Value { - @JsonUnwrapped - private CreateChatPromptRequest value; - - @JsonCreator( - mode = JsonCreator.Mode.PROPERTIES - ) - private ChatValue() { - } - - private ChatValue(CreateChatPromptRequest value) { - this.value = value; - } - - @java.lang.Override - public T visit(Visitor visitor) { - return visitor.visitChat(value); - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof ChatValue && equalTo((ChatValue) other); - } - - private boolean equalTo(ChatValue other) { - return value.equals(other.value); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.value); - } - - @java.lang.Override - public String toString() { - return "CreatePromptRequest{" + "value: " + value + "}"; - } + public static CreatePromptRequest of(CreateTextPromptRequest value) { + return new CreatePromptRequest(value, 1); } - @JsonTypeName("text") - @JsonIgnoreProperties("type") - private static final class TextValue implements Value { - @JsonUnwrapped - private CreateTextPromptRequest value; - - @JsonCreator( - mode = JsonCreator.Mode.PROPERTIES - ) - private TextValue() { - } - - private TextValue(CreateTextPromptRequest value) { - this.value = value; - } - - @java.lang.Override - public T visit(Visitor visitor) { - return visitor.visitText(value); - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof TextValue && equalTo((TextValue) other); - } - - private boolean equalTo(TextValue other) { - return value.equals(other.value); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.value); - } + public interface Visitor { + T visit(CreateChatPromptRequest value); - @java.lang.Override - public String toString() { - return "CreatePromptRequest{" + "value: " + value + "}"; - } + T visit(CreateTextPromptRequest value); } - @JsonIgnoreProperties("type") - private static final class _UnknownValue implements Value { - private String type; - - @JsonValue - private Object value; - - @JsonCreator( - mode = JsonCreator.Mode.PROPERTIES - ) - private _UnknownValue(@JsonProperty("value") Object value) { - } - - @java.lang.Override - public T visit(Visitor visitor) { - return visitor._visitUnknown(value); - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof _UnknownValue && equalTo((_UnknownValue) other); - } - - private boolean equalTo(_UnknownValue other) { - return type.equals(other.type) && value.equals(other.value); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.type, this.value); + static final class Deserializer extends StdDeserializer { + Deserializer() { + super(CreatePromptRequest.class); } @java.lang.Override - public String toString() { - return "CreatePromptRequest{" + "type: " + type + ", value: " + value + "}"; + public CreatePromptRequest deserialize(JsonParser p, DeserializationContext context) throws + IOException { + Object value = p.readValueAs(Object.class); + try { + return of(ObjectMappers.JSON_MAPPER.convertValue(value, CreateChatPromptRequest.class)); + } catch(RuntimeException e) { + } + try { + return of(ObjectMappers.JSON_MAPPER.convertValue(value, CreateTextPromptRequest.class)); + } catch(RuntimeException e) { + } + throw new JsonParseException(p, "Failed to deserialize"); } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/CreateTextPromptRequest.java b/src/main/java/com/langfuse/client/resources/prompts/types/CreateTextPromptRequest.java index f55c5e9..8a1dd7e 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/CreateTextPromptRequest.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/CreateTextPromptRequest.java @@ -33,6 +33,8 @@ public final class CreateTextPromptRequest { private final Optional config; + private final Optional type; + private final Optional> labels; private final Optional> tags; @@ -42,11 +44,13 @@ public final class CreateTextPromptRequest { private final Map additionalProperties; private CreateTextPromptRequest(String name, String prompt, Optional config, - Optional> labels, Optional> tags, Optional commitMessage, + Optional type, Optional> labels, + Optional> tags, Optional commitMessage, Map additionalProperties) { this.name = name; this.prompt = prompt; this.config = config; + this.type = type; this.labels = labels; this.tags = tags; this.commitMessage = commitMessage; @@ -68,6 +72,11 @@ public Optional getConfig() { return config; } + @JsonProperty("type") + public Optional getType() { + return type; + } + /** * @return List of deployment labels of this prompt version. */ @@ -104,12 +113,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(CreateTextPromptRequest other) { - return name.equals(other.name) && prompt.equals(other.prompt) && config.equals(other.config) && labels.equals(other.labels) && tags.equals(other.tags) && commitMessage.equals(other.commitMessage); + return name.equals(other.name) && prompt.equals(other.prompt) && config.equals(other.config) && type.equals(other.type) && labels.equals(other.labels) && tags.equals(other.tags) && commitMessage.equals(other.commitMessage); } @java.lang.Override public int hashCode() { - return Objects.hash(this.name, this.prompt, this.config, this.labels, this.tags, this.commitMessage); + return Objects.hash(this.name, this.prompt, this.config, this.type, this.labels, this.tags, this.commitMessage); } @java.lang.Override @@ -134,18 +143,35 @@ public interface PromptStage { public interface _FinalStage { CreateTextPromptRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage config(Optional config); _FinalStage config(Object config); + _FinalStage type(Optional type); + + _FinalStage type(CreateTextPromptType type); + + /** + *

        List of deployment labels of this prompt version.

        + */ _FinalStage labels(Optional> labels); _FinalStage labels(List labels); + /** + *

        List of tags to apply to all versions of this prompt.

        + */ _FinalStage tags(Optional> tags); _FinalStage tags(List tags); + /** + *

        Commit message for this prompt version.

        + */ _FinalStage commitMessage(Optional commitMessage); _FinalStage commitMessage(String commitMessage); @@ -165,6 +191,8 @@ public static final class Builder implements NameStage, PromptStage, _FinalStage private Optional> labels = Optional.empty(); + private Optional type = Optional.empty(); + private Optional config = Optional.empty(); @JsonAnySetter @@ -178,6 +206,7 @@ public Builder from(CreateTextPromptRequest other) { name(other.getName()); prompt(other.getPrompt()); config(other.getConfig()); + type(other.getType()); labels(other.getLabels()); tags(other.getTags()); commitMessage(other.getCommitMessage()); @@ -208,6 +237,9 @@ public _FinalStage commitMessage(String commitMessage) { return this; } + /** + *

        Commit message for this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "commitMessage", @@ -228,6 +260,9 @@ public _FinalStage tags(List tags) { return this; } + /** + *

        List of tags to apply to all versions of this prompt.

        + */ @java.lang.Override @JsonSetter( value = "tags", @@ -248,6 +283,9 @@ public _FinalStage labels(List labels) { return this; } + /** + *

        List of deployment labels of this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "labels", @@ -258,6 +296,22 @@ public _FinalStage labels(Optional> labels) { return this; } + @java.lang.Override + public _FinalStage type(CreateTextPromptType type) { + this.type = Optional.ofNullable(type); + return this; + } + + @java.lang.Override + @JsonSetter( + value = "type", + nulls = Nulls.SKIP + ) + public _FinalStage type(Optional type) { + this.type = type; + return this; + } + @java.lang.Override public _FinalStage config(Object config) { this.config = Optional.ofNullable(config); @@ -276,7 +330,19 @@ public _FinalStage config(Optional config) { @java.lang.Override public CreateTextPromptRequest build() { - return new CreateTextPromptRequest(name, prompt, config, labels, tags, commitMessage, additionalProperties); + return new CreateTextPromptRequest(name, prompt, config, type, labels, tags, commitMessage, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/CreateTextPromptType.java b/src/main/java/com/langfuse/client/resources/prompts/types/CreateTextPromptType.java new file mode 100644 index 0000000..9730aa9 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/prompts/types/CreateTextPromptType.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.prompts.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; +import java.lang.String; + +public final class CreateTextPromptType { + public static final CreateTextPromptType TEXT = new CreateTextPromptType(Value.TEXT, "text"); + + private final Value value; + + private final String string; + + CreateTextPromptType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof CreateTextPromptType && this.string.equals(((CreateTextPromptType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case TEXT: + return visitor.visitText(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static CreateTextPromptType valueOf(String value) { + switch (value) { + case "text": + return TEXT; + default: + return new CreateTextPromptType(Value.UNKNOWN, value); + } + } + + public enum Value { + TEXT, + + UNKNOWN + } + + public interface Visitor { + T visitText(); + + T visitUnknown(String unknownType); + } +} diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/PlaceholderMessage.java b/src/main/java/com/langfuse/client/resources/prompts/types/PlaceholderMessage.java index 524cb67..4bded94 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/PlaceholderMessage.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/PlaceholderMessage.java @@ -10,6 +10,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; @@ -17,6 +18,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.Optional; import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) @@ -26,10 +28,14 @@ public final class PlaceholderMessage { private final String name; + private final Optional type; + private final Map additionalProperties; - private PlaceholderMessage(String name, Map additionalProperties) { + private PlaceholderMessage(String name, Optional type, + Map additionalProperties) { this.name = name; + this.type = type; this.additionalProperties = additionalProperties; } @@ -38,6 +44,11 @@ public String getName() { return name; } + @JsonProperty("type") + public Optional getType() { + return type; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -50,12 +61,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(PlaceholderMessage other) { - return name.equals(other.name); + return name.equals(other.name) && type.equals(other.type); } @java.lang.Override public int hashCode() { - return Objects.hash(this.name); + return Objects.hash(this.name, this.type); } @java.lang.Override @@ -75,6 +86,14 @@ public interface NameStage { public interface _FinalStage { PlaceholderMessage build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + _FinalStage type(Optional type); + + _FinalStage type(PlaceholderMessageType type); } @JsonIgnoreProperties( @@ -83,6 +102,8 @@ public interface _FinalStage { public static final class Builder implements NameStage, _FinalStage { private String name; + private Optional type = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -92,6 +113,7 @@ private Builder() { @java.lang.Override public Builder from(PlaceholderMessage other) { name(other.getName()); + type(other.getType()); return this; } @@ -102,9 +124,37 @@ public _FinalStage name(@NotNull String name) { return this; } + @java.lang.Override + public _FinalStage type(PlaceholderMessageType type) { + this.type = Optional.ofNullable(type); + return this; + } + + @java.lang.Override + @JsonSetter( + value = "type", + nulls = Nulls.SKIP + ) + public _FinalStage type(Optional type) { + this.type = type; + return this; + } + @java.lang.Override public PlaceholderMessage build() { - return new PlaceholderMessage(name, additionalProperties); + return new PlaceholderMessage(name, type, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/PlaceholderMessageType.java b/src/main/java/com/langfuse/client/resources/prompts/types/PlaceholderMessageType.java new file mode 100644 index 0000000..f400281 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/prompts/types/PlaceholderMessageType.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.prompts.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; +import java.lang.String; + +public final class PlaceholderMessageType { + public static final PlaceholderMessageType PLACEHOLDER = new PlaceholderMessageType(Value.PLACEHOLDER, "placeholder"); + + private final Value value; + + private final String string; + + PlaceholderMessageType(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof PlaceholderMessageType && this.string.equals(((PlaceholderMessageType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PLACEHOLDER: + return visitor.visitPlaceholder(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static PlaceholderMessageType valueOf(String value) { + switch (value) { + case "placeholder": + return PLACEHOLDER; + default: + return new PlaceholderMessageType(Value.UNKNOWN, value); + } + } + + public enum Value { + PLACEHOLDER, + + UNKNOWN + } + + public interface Visitor { + T visitPlaceholder(); + + T visitUnknown(String unknownType); + } +} diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/PromptMeta.java b/src/main/java/com/langfuse/client/resources/prompts/types/PromptMeta.java index ed0df14..6e793f0 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/PromptMeta.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/PromptMeta.java @@ -135,6 +135,9 @@ public interface NameStage { } public interface TypeStage { + /** + *

        Indicates whether the prompt is a text or chat prompt.

        + */ LastUpdatedAtStage type(@NotNull PromptType type); } @@ -143,12 +146,19 @@ public interface LastUpdatedAtStage { } public interface LastConfigStage { + /** + *

        Config object of the most recent prompt version that matches the filters (if any are provided)

        + */ _FinalStage lastConfig(Object lastConfig); } public interface _FinalStage { PromptMeta build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage versions(List versions); _FinalStage addVersions(Integer versions); @@ -212,6 +222,7 @@ public TypeStage name(@NotNull String name) { } /** + *

        Indicates whether the prompt is a text or chat prompt.

        *

        Indicates whether the prompt is a text or chat prompt.

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -230,6 +241,7 @@ public LastConfigStage lastUpdatedAt(@NotNull OffsetDateTime lastUpdatedAt) { } /** + *

        Config object of the most recent prompt version that matches the filters (if any are provided)

        *

        Config object of the most recent prompt version that matches the filters (if any are provided)

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -242,7 +254,9 @@ public _FinalStage lastConfig(Object lastConfig) { @java.lang.Override public _FinalStage addAllTags(List tags) { - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -259,13 +273,17 @@ public _FinalStage addTags(String tags) { ) public _FinalStage tags(List tags) { this.tags.clear(); - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @java.lang.Override public _FinalStage addAllLabels(List labels) { - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @@ -282,13 +300,17 @@ public _FinalStage addLabels(String labels) { ) public _FinalStage labels(List labels) { this.labels.clear(); - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @java.lang.Override public _FinalStage addAllVersions(List versions) { - this.versions.addAll(versions); + if (versions != null) { + this.versions.addAll(versions); + } return this; } @@ -305,7 +327,9 @@ public _FinalStage addVersions(Integer versions) { ) public _FinalStage versions(List versions) { this.versions.clear(); - this.versions.addAll(versions); + if (versions != null) { + this.versions.addAll(versions); + } return this; } @@ -313,5 +337,17 @@ public _FinalStage versions(List versions) { public PromptMeta build() { return new PromptMeta(name, type, versions, labels, tags, lastUpdatedAt, lastConfig, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/PromptMetaListResponse.java b/src/main/java/com/langfuse/client/resources/prompts/types/PromptMetaListResponse.java index 92ff247..978024b 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/PromptMetaListResponse.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/PromptMetaListResponse.java @@ -89,6 +89,10 @@ public interface MetaStage { public interface _FinalStage { PromptMetaListResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(PromptMeta data); @@ -126,7 +130,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -143,7 +149,9 @@ public _FinalStage addData(PromptMeta data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -151,5 +159,17 @@ public _FinalStage data(List data) { public PromptMetaListResponse build() { return new PromptMetaListResponse(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/PromptType.java b/src/main/java/com/langfuse/client/resources/prompts/types/PromptType.java index 6e80f8a..7ee8ecb 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/PromptType.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/PromptType.java @@ -4,23 +4,85 @@ package com.langfuse.client.resources.prompts.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; +import java.lang.Object; import java.lang.String; -public enum PromptType { - CHAT("chat"), +public final class PromptType { + public static final PromptType TEXT = new PromptType(Value.TEXT, "text"); - TEXT("text"); + public static final PromptType CHAT = new PromptType(Value.CHAT, "chat"); - private final String value; + private final Value value; - PromptType(String value) { + private final String string; + + PromptType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof PromptType && this.string.equals(((PromptType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case TEXT: + return visitor.visitText(); + case CHAT: + return visitor.visitChat(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator( + mode = JsonCreator.Mode.DELEGATING + ) + public static PromptType valueOf(String value) { + switch (value) { + case "text": + return TEXT; + case "chat": + return CHAT; + default: + return new PromptType(Value.UNKNOWN, value); + } + } + + public enum Value { + CHAT, + + TEXT, + + UNKNOWN + } + + public interface Visitor { + T visitChat(); + + T visitText(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/langfuse/client/resources/prompts/types/TextPrompt.java b/src/main/java/com/langfuse/client/resources/prompts/types/TextPrompt.java index 0a13fc5..82325bf 100644 --- a/src/main/java/com/langfuse/client/resources/prompts/types/TextPrompt.java +++ b/src/main/java/com/langfuse/client/resources/prompts/types/TextPrompt.java @@ -170,22 +170,38 @@ public interface PromptStage { public interface _FinalStage { TextPrompt build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        List of deployment labels of this prompt version.

        + */ _FinalStage labels(List labels); _FinalStage addLabels(String labels); _FinalStage addAllLabels(List labels); + /** + *

        List of tags. Used to filter via UI and API. The same across versions of a prompt.

        + */ _FinalStage tags(List tags); _FinalStage addTags(String tags); _FinalStage addAllTags(List tags); + /** + *

        Commit message for this prompt version.

        + */ _FinalStage commitMessage(Optional commitMessage); _FinalStage commitMessage(String commitMessage); + /** + *

        The dependency resolution graph for the current prompt. Null if prompt has no dependencies.

        + */ _FinalStage resolutionGraph(Optional> resolutionGraph); _FinalStage resolutionGraph(Map resolutionGraph); @@ -268,6 +284,9 @@ public _FinalStage resolutionGraph(Map resolutionGraph) { return this; } + /** + *

        The dependency resolution graph for the current prompt. Null if prompt has no dependencies.

        + */ @java.lang.Override @JsonSetter( value = "resolutionGraph", @@ -288,6 +307,9 @@ public _FinalStage commitMessage(String commitMessage) { return this; } + /** + *

        Commit message for this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "commitMessage", @@ -304,7 +326,9 @@ public _FinalStage commitMessage(Optional commitMessage) { */ @java.lang.Override public _FinalStage addAllTags(List tags) { - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -318,6 +342,9 @@ public _FinalStage addTags(String tags) { return this; } + /** + *

        List of tags. Used to filter via UI and API. The same across versions of a prompt.

        + */ @java.lang.Override @JsonSetter( value = "tags", @@ -325,7 +352,9 @@ public _FinalStage addTags(String tags) { ) public _FinalStage tags(List tags) { this.tags.clear(); - this.tags.addAll(tags); + if (tags != null) { + this.tags.addAll(tags); + } return this; } @@ -335,7 +364,9 @@ public _FinalStage tags(List tags) { */ @java.lang.Override public _FinalStage addAllLabels(List labels) { - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @@ -349,6 +380,9 @@ public _FinalStage addLabels(String labels) { return this; } + /** + *

        List of deployment labels of this prompt version.

        + */ @java.lang.Override @JsonSetter( value = "labels", @@ -356,7 +390,9 @@ public _FinalStage addLabels(String labels) { ) public _FinalStage labels(List labels) { this.labels.clear(); - this.labels.addAll(labels); + if (labels != null) { + this.labels.addAll(labels); + } return this; } @@ -364,5 +400,17 @@ public _FinalStage labels(List labels) { public TextPrompt build() { return new TextPrompt(name, version, config, labels, tags, commitMessage, resolutionGraph, prompt, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/promptversion/AsyncPromptVersionClient.java b/src/main/java/com/langfuse/client/resources/promptversion/AsyncPromptVersionClient.java new file mode 100644 index 0000000..8789b49 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/promptversion/AsyncPromptVersionClient.java @@ -0,0 +1,45 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.promptversion; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.promptversion.requests.UpdatePromptRequest; + +public class AsyncPromptVersionClient { + protected final ClientOptions clientOptions; + + private final AsyncRawPromptVersionClient rawClient; + + public AsyncPromptVersionClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawPromptVersionClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawPromptVersionClient withRawResponse() { + return this.rawClient; + } + + /** + * Update labels for a specific prompt version + */ + public CompletableFuture update(String name, int version, UpdatePromptRequest request) { + return this.rawClient.update(name, version, request).thenApply(response -> response.body()); + } + + /** + * Update labels for a specific prompt version + */ + public CompletableFuture update(String name, int version, UpdatePromptRequest request, + RequestOptions requestOptions) { + return this.rawClient.update(name, version, request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/promptversion/AsyncRawPromptVersionClient.java b/src/main/java/com/langfuse/client/resources/promptversion/AsyncRawPromptVersionClient.java new file mode 100644 index 0000000..71c5a54 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/promptversion/AsyncRawPromptVersionClient.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.promptversion; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Integer; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.promptversion.requests.UpdatePromptRequest; + +public class AsyncRawPromptVersionClient { + protected final ClientOptions clientOptions; + + public AsyncRawPromptVersionClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Update labels for a specific prompt version + */ + public CompletableFuture> update(String name, int version, + UpdatePromptRequest request) { + return update(name,version,request,null); + } + + /** + * Update labels for a specific prompt version + */ + public CompletableFuture> update(String name, int version, + UpdatePromptRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts") + .addPathSegment(name) + .addPathSegments("versions") + .addPathSegment(Integer.toString(version));if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Prompt.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/promptversion/PromptVersionClient.java b/src/main/java/com/langfuse/client/resources/promptversion/PromptVersionClient.java index 90288b4..0c452cf 100644 --- a/src/main/java/com/langfuse/client/resources/promptversion/PromptVersionClient.java +++ b/src/main/java/com/langfuse/client/resources/promptversion/PromptVersionClient.java @@ -4,44 +4,34 @@ package com.langfuse.client.resources.promptversion; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Integer; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.prompts.types.Prompt; import com.langfuse.client.resources.promptversion.requests.UpdatePromptRequest; public class PromptVersionClient { protected final ClientOptions clientOptions; + private final RawPromptVersionClient rawClient; + public PromptVersionClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawPromptVersionClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawPromptVersionClient withRawResponse() { + return this.rawClient; } /** * Update labels for a specific prompt version */ public Prompt update(String name, int version, UpdatePromptRequest request) { - return update(name,version,request,null); + return this.rawClient.update(name, version, request).body(); } /** @@ -49,53 +39,6 @@ public Prompt update(String name, int version, UpdatePromptRequest request) { */ public Prompt update(String name, int version, UpdatePromptRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/v2") - .addPathSegments("prompts") - .addPathSegment(name) - .addPathSegments("versions") - .addPathSegment(Integer.toString(version)) - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Prompt.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.update(name, version, request, requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/promptversion/RawPromptVersionClient.java b/src/main/java/com/langfuse/client/resources/promptversion/RawPromptVersionClient.java new file mode 100644 index 0000000..cf929d7 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/promptversion/RawPromptVersionClient.java @@ -0,0 +1,107 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.promptversion; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Integer; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.promptversion.requests.UpdatePromptRequest; + +public class RawPromptVersionClient { + protected final ClientOptions clientOptions; + + public RawPromptVersionClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Update labels for a specific prompt version + */ + public LangfuseClientHttpResponse update(String name, int version, + UpdatePromptRequest request) { + return update(name,version,request,null); + } + + /** + * Update labels for a specific prompt version + */ + public LangfuseClientHttpResponse update(String name, int version, + UpdatePromptRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("prompts") + .addPathSegment(name) + .addPathSegments("versions") + .addPathSegment(Integer.toString(version));if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Prompt.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/promptversion/requests/UpdatePromptRequest.java b/src/main/java/com/langfuse/client/resources/promptversion/requests/UpdatePromptRequest.java index 94854a4..1ca0031 100644 --- a/src/main/java/com/langfuse/client/resources/promptversion/requests/UpdatePromptRequest.java +++ b/src/main/java/com/langfuse/client/resources/promptversion/requests/UpdatePromptRequest.java @@ -89,13 +89,18 @@ public Builder from(UpdatePromptRequest other) { return this; } + /** + *

        New labels for the prompt version. Labels are unique across versions. The "latest" label is reserved and managed by Langfuse.

        + */ @JsonSetter( value = "newLabels", nulls = Nulls.SKIP ) public Builder newLabels(List newLabels) { this.newLabels.clear(); - this.newLabels.addAll(newLabels); + if (newLabels != null) { + this.newLabels.addAll(newLabels); + } return this; } @@ -105,12 +110,24 @@ public Builder addNewLabels(String newLabels) { } public Builder addAllNewLabels(List newLabels) { - this.newLabels.addAll(newLabels); + if (newLabels != null) { + this.newLabels.addAll(newLabels); + } return this; } public UpdatePromptRequest build() { return new UpdatePromptRequest(newLabels, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/AsyncRawScimClient.java b/src/main/java/com/langfuse/client/resources/scim/AsyncRawScimClient.java new file mode 100644 index 0000000..e394016 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scim/AsyncRawScimClient.java @@ -0,0 +1,600 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scim; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.scim.requests.CreateUserRequest; +import com.langfuse.client.resources.scim.requests.ListUsersRequest; +import com.langfuse.client.resources.scim.types.EmptyResponse; +import com.langfuse.client.resources.scim.types.ResourceTypesResponse; +import com.langfuse.client.resources.scim.types.SchemasResponse; +import com.langfuse.client.resources.scim.types.ScimUser; +import com.langfuse.client.resources.scim.types.ScimUsersListResponse; +import com.langfuse.client.resources.scim.types.ServiceProviderConfig; + +public class AsyncRawScimClient { + protected final ClientOptions clientOptions; + + public AsyncRawScimClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get SCIM Service Provider Configuration (requires organization-scoped API key) + */ + public CompletableFuture> getServiceProviderConfig( + ) { + return getServiceProviderConfig(null); + } + + /** + * Get SCIM Service Provider Configuration (requires organization-scoped API key) + */ + public CompletableFuture> getServiceProviderConfig( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("ServiceProviderConfig");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ServiceProviderConfig.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get SCIM Resource Types (requires organization-scoped API key) + */ + public CompletableFuture> getResourceTypes() { + return getResourceTypes(null); + } + + /** + * Get SCIM Resource Types (requires organization-scoped API key) + */ + public CompletableFuture> getResourceTypes( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("ResourceTypes");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ResourceTypesResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get SCIM Schemas (requires organization-scoped API key) + */ + public CompletableFuture> getSchemas() { + return getSchemas(null); + } + + /** + * Get SCIM Schemas (requires organization-scoped API key) + */ + public CompletableFuture> getSchemas( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Schemas");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, SchemasResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture> listUsers() { + return listUsers(ListUsersRequest.builder().build()); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture> listUsers( + RequestOptions requestOptions) { + return listUsers(ListUsersRequest.builder().build(),requestOptions); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture> listUsers( + ListUsersRequest request) { + return listUsers(request,null); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture> listUsers( + ListUsersRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users");if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getStartIndex().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "startIndex", request.getStartIndex().get(), false); + } + if (request.getCount().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "count", request.getCount().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScimUsersListResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public CompletableFuture> createUser( + CreateUserRequest request) { + return createUser(request,null); + } + + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public CompletableFuture> createUser( + CreateUserRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScimUser.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public CompletableFuture> getUser(String userId) { + return getUser(userId,null); + } + + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public CompletableFuture> getUser(String userId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users") + .addPathSegment(userId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScimUser.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public CompletableFuture> deleteUser( + String userId) { + return deleteUser(userId,null); + } + + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public CompletableFuture> deleteUser( + String userId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users") + .addPathSegment(userId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmptyResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/scim/AsyncScimClient.java b/src/main/java/com/langfuse/client/resources/scim/AsyncScimClient.java new file mode 100644 index 0000000..c28863f --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scim/AsyncScimClient.java @@ -0,0 +1,151 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scim; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.scim.requests.CreateUserRequest; +import com.langfuse.client.resources.scim.requests.ListUsersRequest; +import com.langfuse.client.resources.scim.types.EmptyResponse; +import com.langfuse.client.resources.scim.types.ResourceTypesResponse; +import com.langfuse.client.resources.scim.types.SchemasResponse; +import com.langfuse.client.resources.scim.types.ScimUser; +import com.langfuse.client.resources.scim.types.ScimUsersListResponse; +import com.langfuse.client.resources.scim.types.ServiceProviderConfig; + +public class AsyncScimClient { + protected final ClientOptions clientOptions; + + private final AsyncRawScimClient rawClient; + + public AsyncScimClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawScimClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawScimClient withRawResponse() { + return this.rawClient; + } + + /** + * Get SCIM Service Provider Configuration (requires organization-scoped API key) + */ + public CompletableFuture getServiceProviderConfig() { + return this.rawClient.getServiceProviderConfig().thenApply(response -> response.body()); + } + + /** + * Get SCIM Service Provider Configuration (requires organization-scoped API key) + */ + public CompletableFuture getServiceProviderConfig( + RequestOptions requestOptions) { + return this.rawClient.getServiceProviderConfig(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get SCIM Resource Types (requires organization-scoped API key) + */ + public CompletableFuture getResourceTypes() { + return this.rawClient.getResourceTypes().thenApply(response -> response.body()); + } + + /** + * Get SCIM Resource Types (requires organization-scoped API key) + */ + public CompletableFuture getResourceTypes(RequestOptions requestOptions) { + return this.rawClient.getResourceTypes(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get SCIM Schemas (requires organization-scoped API key) + */ + public CompletableFuture getSchemas() { + return this.rawClient.getSchemas().thenApply(response -> response.body()); + } + + /** + * Get SCIM Schemas (requires organization-scoped API key) + */ + public CompletableFuture getSchemas(RequestOptions requestOptions) { + return this.rawClient.getSchemas(requestOptions).thenApply(response -> response.body()); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture listUsers() { + return this.rawClient.listUsers().thenApply(response -> response.body()); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture listUsers(RequestOptions requestOptions) { + return this.rawClient.listUsers(requestOptions).thenApply(response -> response.body()); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture listUsers(ListUsersRequest request) { + return this.rawClient.listUsers(request).thenApply(response -> response.body()); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public CompletableFuture listUsers(ListUsersRequest request, + RequestOptions requestOptions) { + return this.rawClient.listUsers(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public CompletableFuture createUser(CreateUserRequest request) { + return this.rawClient.createUser(request).thenApply(response -> response.body()); + } + + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public CompletableFuture createUser(CreateUserRequest request, + RequestOptions requestOptions) { + return this.rawClient.createUser(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public CompletableFuture getUser(String userId) { + return this.rawClient.getUser(userId).thenApply(response -> response.body()); + } + + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public CompletableFuture getUser(String userId, RequestOptions requestOptions) { + return this.rawClient.getUser(userId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public CompletableFuture deleteUser(String userId) { + return this.rawClient.deleteUser(userId).thenApply(response -> response.body()); + } + + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public CompletableFuture deleteUser(String userId, RequestOptions requestOptions) { + return this.rawClient.deleteUser(userId, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/scim/RawScimClient.java b/src/main/java/com/langfuse/client/resources/scim/RawScimClient.java new file mode 100644 index 0000000..b966aa5 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scim/RawScimClient.java @@ -0,0 +1,465 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scim; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.scim.requests.CreateUserRequest; +import com.langfuse.client.resources.scim.requests.ListUsersRequest; +import com.langfuse.client.resources.scim.types.EmptyResponse; +import com.langfuse.client.resources.scim.types.ResourceTypesResponse; +import com.langfuse.client.resources.scim.types.SchemasResponse; +import com.langfuse.client.resources.scim.types.ScimUser; +import com.langfuse.client.resources.scim.types.ScimUsersListResponse; +import com.langfuse.client.resources.scim.types.ServiceProviderConfig; + +public class RawScimClient { + protected final ClientOptions clientOptions; + + public RawScimClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get SCIM Service Provider Configuration (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getServiceProviderConfig() { + return getServiceProviderConfig(null); + } + + /** + * Get SCIM Service Provider Configuration (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getServiceProviderConfig( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("ServiceProviderConfig");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ServiceProviderConfig.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get SCIM Resource Types (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getResourceTypes() { + return getResourceTypes(null); + } + + /** + * Get SCIM Resource Types (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getResourceTypes( + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("ResourceTypes");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ResourceTypesResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get SCIM Schemas (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getSchemas() { + return getSchemas(null); + } + + /** + * Get SCIM Schemas (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getSchemas(RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Schemas");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, SchemasResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse listUsers() { + return listUsers(ListUsersRequest.builder().build()); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse listUsers( + RequestOptions requestOptions) { + return listUsers(ListUsersRequest.builder().build(),requestOptions); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse listUsers( + ListUsersRequest request) { + return listUsers(request,null); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse listUsers(ListUsersRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users");if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getStartIndex().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "startIndex", request.getStartIndex().get(), false); + } + if (request.getCount().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "count", request.getCount().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScimUsersListResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse createUser(CreateUserRequest request) { + return createUser(request,null); + } + + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse createUser(CreateUserRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScimUser.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getUser(String userId) { + return getUser(userId,null); + } + + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public LangfuseClientHttpResponse getUser(String userId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users") + .addPathSegment(userId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScimUser.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public LangfuseClientHttpResponse deleteUser(String userId) { + return deleteUser(userId,null); + } + + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public LangfuseClientHttpResponse deleteUser(String userId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/scim") + .addPathSegments("Users") + .addPathSegment(userId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmptyResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/scim/ScimClient.java b/src/main/java/com/langfuse/client/resources/scim/ScimClient.java index ad3bf6b..5288743 100644 --- a/src/main/java/com/langfuse/client/resources/scim/ScimClient.java +++ b/src/main/java/com/langfuse/client/resources/scim/ScimClient.java @@ -4,29 +4,9 @@ package com.langfuse.client.resources.scim; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.scim.requests.CreateUserRequest; import com.langfuse.client.resources.scim.requests.ListUsersRequest; import com.langfuse.client.resources.scim.types.EmptyResponse; @@ -39,387 +19,129 @@ public class ScimClient { protected final ClientOptions clientOptions; + private final RawScimClient rawClient; + public ScimClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawScimClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawScimClient withRawResponse() { + return this.rawClient; } /** * Get SCIM Service Provider Configuration (requires organization-scoped API key) */ public ServiceProviderConfig getServiceProviderConfig() { - return getServiceProviderConfig(null); + return this.rawClient.getServiceProviderConfig().body(); } /** * Get SCIM Service Provider Configuration (requires organization-scoped API key) */ public ServiceProviderConfig getServiceProviderConfig(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/scim") - .addPathSegments("ServiceProviderConfig") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ServiceProviderConfig.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getServiceProviderConfig(requestOptions).body(); } /** * Get SCIM Resource Types (requires organization-scoped API key) */ public ResourceTypesResponse getResourceTypes() { - return getResourceTypes(null); + return this.rawClient.getResourceTypes().body(); } /** * Get SCIM Resource Types (requires organization-scoped API key) */ public ResourceTypesResponse getResourceTypes(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/scim") - .addPathSegments("ResourceTypes") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ResourceTypesResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getResourceTypes(requestOptions).body(); } /** * Get SCIM Schemas (requires organization-scoped API key) */ public SchemasResponse getSchemas() { - return getSchemas(null); + return this.rawClient.getSchemas().body(); } /** * Get SCIM Schemas (requires organization-scoped API key) */ public SchemasResponse getSchemas(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/scim") - .addPathSegments("Schemas") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SchemasResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.getSchemas(requestOptions).body(); } /** * List users in the organization (requires organization-scoped API key) */ public ScimUsersListResponse listUsers() { - return listUsers(ListUsersRequest.builder().build()); + return this.rawClient.listUsers().body(); + } + + /** + * List users in the organization (requires organization-scoped API key) + */ + public ScimUsersListResponse listUsers(RequestOptions requestOptions) { + return this.rawClient.listUsers(requestOptions).body(); } /** * List users in the organization (requires organization-scoped API key) */ public ScimUsersListResponse listUsers(ListUsersRequest request) { - return listUsers(request,null); + return this.rawClient.listUsers(request).body(); } /** * List users in the organization (requires organization-scoped API key) */ public ScimUsersListResponse listUsers(ListUsersRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/scim") - .addPathSegments("Users");if (request.getFilter().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); - } - if (request.getStartIndex().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "startIndex", request.getStartIndex().get().toString(), false); - } - if (request.getCount().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "count", request.getCount().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ScimUsersListResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.listUsers(request, requestOptions).body(); + } - /** - * Create a new user in the organization (requires organization-scoped API key) - */ - public ScimUser createUser(CreateUserRequest request) { - return createUser(request,null); - } + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public ScimUser createUser(CreateUserRequest request) { + return this.rawClient.createUser(request).body(); + } - /** - * Create a new user in the organization (requires organization-scoped API key) - */ - public ScimUser createUser(CreateUserRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/scim") - .addPathSegments("Users") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ScimUser.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Create a new user in the organization (requires organization-scoped API key) + */ + public ScimUser createUser(CreateUserRequest request, RequestOptions requestOptions) { + return this.rawClient.createUser(request, requestOptions).body(); + } - /** - * Get a specific user by ID (requires organization-scoped API key) - */ - public ScimUser getUser(String userId) { - return getUser(userId,null); - } + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public ScimUser getUser(String userId) { + return this.rawClient.getUser(userId).body(); + } - /** - * Get a specific user by ID (requires organization-scoped API key) - */ - public ScimUser getUser(String userId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/scim") - .addPathSegments("Users") - .addPathSegment(userId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ScimUser.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a specific user by ID (requires organization-scoped API key) + */ + public ScimUser getUser(String userId, RequestOptions requestOptions) { + return this.rawClient.getUser(userId, requestOptions).body(); + } - /** - * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. - */ - public EmptyResponse deleteUser(String userId) { - return deleteUser(userId,null); - } + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public EmptyResponse deleteUser(String userId) { + return this.rawClient.deleteUser(userId).body(); + } - /** - * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. - */ - public EmptyResponse deleteUser(String userId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/scim") - .addPathSegments("Users") - .addPathSegment(userId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmptyResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Remove a user from the organization (requires organization-scoped API key). Note that this only removes the user from the organization but does not delete the user entity itself. + */ + public EmptyResponse deleteUser(String userId, RequestOptions requestOptions) { + return this.rawClient.deleteUser(userId, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/scim/requests/CreateUserRequest.java b/src/main/java/com/langfuse/client/resources/scim/requests/CreateUserRequest.java index f3dba02..dc2276b 100644 --- a/src/main/java/com/langfuse/client/resources/scim/requests/CreateUserRequest.java +++ b/src/main/java/com/langfuse/client/resources/scim/requests/CreateUserRequest.java @@ -123,26 +123,45 @@ public static UserNameStage builder() { } public interface UserNameStage { + /** + *

        User's email address (required)

        + */ NameStage userName(@NotNull String userName); Builder from(CreateUserRequest other); } public interface NameStage { + /** + *

        User's name information

        + */ _FinalStage name(@NotNull ScimName name); } public interface _FinalStage { CreateUserRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        User's email addresses

        + */ _FinalStage emails(Optional> emails); _FinalStage emails(List emails); + /** + *

        Whether the user is active

        + */ _FinalStage active(Optional active); _FinalStage active(Boolean active); + /** + *

        Initial password for the user

        + */ _FinalStage password(Optional password); _FinalStage password(String password); @@ -179,6 +198,7 @@ public Builder from(CreateUserRequest other) { } /** + *

        User's email address (required)

        *

        User's email address (required)

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -190,6 +210,7 @@ public NameStage userName(@NotNull String userName) { } /** + *

        User's name information

        *

        User's name information

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -210,6 +231,9 @@ public _FinalStage password(String password) { return this; } + /** + *

        Initial password for the user

        + */ @java.lang.Override @JsonSetter( value = "password", @@ -230,6 +254,9 @@ public _FinalStage active(Boolean active) { return this; } + /** + *

        Whether the user is active

        + */ @java.lang.Override @JsonSetter( value = "active", @@ -250,6 +277,9 @@ public _FinalStage emails(List emails) { return this; } + /** + *

        User's email addresses

        + */ @java.lang.Override @JsonSetter( value = "emails", @@ -264,5 +294,17 @@ public _FinalStage emails(Optional> emails) { public CreateUserRequest build() { return new CreateUserRequest(userName, name, emails, active, password, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/requests/ListUsersRequest.java b/src/main/java/com/langfuse/client/resources/scim/requests/ListUsersRequest.java index 6d2527c..cd0d173 100644 --- a/src/main/java/com/langfuse/client/resources/scim/requests/ListUsersRequest.java +++ b/src/main/java/com/langfuse/client/resources/scim/requests/ListUsersRequest.java @@ -118,6 +118,9 @@ public Builder from(ListUsersRequest other) { return this; } + /** + *

        Filter expression (e.g. userName eq "value")

        + */ @JsonSetter( value = "filter", nulls = Nulls.SKIP @@ -132,6 +135,9 @@ public Builder filter(String filter) { return this; } + /** + *

        1-based index of the first result to return (default 1)

        + */ @JsonSetter( value = "startIndex", nulls = Nulls.SKIP @@ -146,6 +152,9 @@ public Builder startIndex(Integer startIndex) { return this; } + /** + *

        Maximum number of results to return (default 100)

        + */ @JsonSetter( value = "count", nulls = Nulls.SKIP @@ -163,5 +172,15 @@ public Builder count(Integer count) { public ListUsersRequest build() { return new ListUsersRequest(filter, startIndex, count, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/AuthenticationScheme.java b/src/main/java/com/langfuse/client/resources/scim/types/AuthenticationScheme.java index 8caeee3..5a94623 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/AuthenticationScheme.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/AuthenticationScheme.java @@ -124,6 +124,10 @@ public interface PrimaryStage { public interface _FinalStage { AuthenticationScheme build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -195,5 +199,17 @@ public _FinalStage primary(boolean primary) { public AuthenticationScheme build() { return new AuthenticationScheme(name, description, specUri, type, primary, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/BulkConfig.java b/src/main/java/com/langfuse/client/resources/scim/types/BulkConfig.java index 2098a77..0189678 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/BulkConfig.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/BulkConfig.java @@ -99,6 +99,10 @@ public interface MaxPayloadSizeStage { public interface _FinalStage { BulkConfig build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -150,5 +154,17 @@ public _FinalStage maxPayloadSize(int maxPayloadSize) { public BulkConfig build() { return new BulkConfig(supported, maxOperations, maxPayloadSize, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/EmptyResponse.java b/src/main/java/com/langfuse/client/resources/scim/types/EmptyResponse.java index 4b65fe7..dd5e2e7 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/EmptyResponse.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/EmptyResponse.java @@ -63,5 +63,15 @@ public Builder from(EmptyResponse other) { public EmptyResponse build() { return new EmptyResponse(additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/FilterConfig.java b/src/main/java/com/langfuse/client/resources/scim/types/FilterConfig.java index 0416711..b45a2d3 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/FilterConfig.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/FilterConfig.java @@ -87,6 +87,10 @@ public interface MaxResultsStage { public interface _FinalStage { FilterConfig build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -128,5 +132,17 @@ public _FinalStage maxResults(int maxResults) { public FilterConfig build() { return new FilterConfig(supported, maxResults, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ResourceMeta.java b/src/main/java/com/langfuse/client/resources/scim/types/ResourceMeta.java index 26fe4c7..6f3f957 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ResourceMeta.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ResourceMeta.java @@ -88,6 +88,10 @@ public interface LocationStage { public interface _FinalStage { ResourceMeta build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -129,5 +133,17 @@ public _FinalStage location(@NotNull String location) { public ResourceMeta build() { return new ResourceMeta(resourceType, location, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ResourceType.java b/src/main/java/com/langfuse/client/resources/scim/types/ResourceType.java index 5b1321f..fcc3586 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ResourceType.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ResourceType.java @@ -158,6 +158,10 @@ public interface MetaStage { public interface _FinalStage { ResourceType build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage schemas(Optional> schemas); _FinalStage schemas(List schemas); @@ -252,7 +256,9 @@ public _FinalStage meta(@NotNull ResourceMeta meta) { @java.lang.Override public _FinalStage addAllSchemaExtensions(List schemaExtensions) { - this.schemaExtensions.addAll(schemaExtensions); + if (schemaExtensions != null) { + this.schemaExtensions.addAll(schemaExtensions); + } return this; } @@ -269,7 +275,9 @@ public _FinalStage addSchemaExtensions(SchemaExtension schemaExtensions) { ) public _FinalStage schemaExtensions(List schemaExtensions) { this.schemaExtensions.clear(); - this.schemaExtensions.addAll(schemaExtensions); + if (schemaExtensions != null) { + this.schemaExtensions.addAll(schemaExtensions); + } return this; } @@ -293,5 +301,17 @@ public _FinalStage schemas(Optional> schemas) { public ResourceType build() { return new ResourceType(schemas, id, name, endpoint, description, schema, schemaExtensions, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ResourceTypesResponse.java b/src/main/java/com/langfuse/client/resources/scim/types/ResourceTypesResponse.java index a781ab0..f18a8aa 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ResourceTypesResponse.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ResourceTypesResponse.java @@ -95,6 +95,10 @@ public interface TotalResultsStage { public interface _FinalStage { ResourceTypesResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage schemas(List schemas); _FinalStage addSchemas(String schemas); @@ -141,7 +145,9 @@ public _FinalStage totalResults(int totalResults) { @java.lang.Override public _FinalStage addAllResources(List resources) { - this.resources.addAll(resources); + if (resources != null) { + this.resources.addAll(resources); + } return this; } @@ -158,13 +164,17 @@ public _FinalStage addResources(ResourceType resources) { ) public _FinalStage resources(List resources) { this.resources.clear(); - this.resources.addAll(resources); + if (resources != null) { + this.resources.addAll(resources); + } return this; } @java.lang.Override public _FinalStage addAllSchemas(List schemas) { - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -181,7 +191,9 @@ public _FinalStage addSchemas(String schemas) { ) public _FinalStage schemas(List schemas) { this.schemas.clear(); - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -189,5 +201,17 @@ public _FinalStage schemas(List schemas) { public ResourceTypesResponse build() { return new ResourceTypesResponse(schemas, totalResults, resources, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/SchemaExtension.java b/src/main/java/com/langfuse/client/resources/scim/types/SchemaExtension.java index f932654..28b9e95 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/SchemaExtension.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/SchemaExtension.java @@ -88,6 +88,10 @@ public interface RequiredStage { public interface _FinalStage { SchemaExtension build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -129,5 +133,17 @@ public _FinalStage required(boolean required) { public SchemaExtension build() { return new SchemaExtension(schema, required, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/SchemaResource.java b/src/main/java/com/langfuse/client/resources/scim/types/SchemaResource.java index 7b8f88a..95b86c1 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/SchemaResource.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/SchemaResource.java @@ -124,6 +124,10 @@ public interface MetaStage { public interface _FinalStage { SchemaResource build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage attributes(List attributes); _FinalStage addAttributes(Object attributes); @@ -191,7 +195,9 @@ public _FinalStage meta(@NotNull ResourceMeta meta) { @java.lang.Override public _FinalStage addAllAttributes(List attributes) { - this.attributes.addAll(attributes); + if (attributes != null) { + this.attributes.addAll(attributes); + } return this; } @@ -208,7 +214,9 @@ public _FinalStage addAttributes(Object attributes) { ) public _FinalStage attributes(List attributes) { this.attributes.clear(); - this.attributes.addAll(attributes); + if (attributes != null) { + this.attributes.addAll(attributes); + } return this; } @@ -216,5 +224,17 @@ public _FinalStage attributes(List attributes) { public SchemaResource build() { return new SchemaResource(id, name, description, attributes, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/SchemasResponse.java b/src/main/java/com/langfuse/client/resources/scim/types/SchemasResponse.java index 2f2839c..fe798fd 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/SchemasResponse.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/SchemasResponse.java @@ -95,6 +95,10 @@ public interface TotalResultsStage { public interface _FinalStage { SchemasResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage schemas(List schemas); _FinalStage addSchemas(String schemas); @@ -141,7 +145,9 @@ public _FinalStage totalResults(int totalResults) { @java.lang.Override public _FinalStage addAllResources(List resources) { - this.resources.addAll(resources); + if (resources != null) { + this.resources.addAll(resources); + } return this; } @@ -158,13 +164,17 @@ public _FinalStage addResources(SchemaResource resources) { ) public _FinalStage resources(List resources) { this.resources.clear(); - this.resources.addAll(resources); + if (resources != null) { + this.resources.addAll(resources); + } return this; } @java.lang.Override public _FinalStage addAllSchemas(List schemas) { - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -181,7 +191,9 @@ public _FinalStage addSchemas(String schemas) { ) public _FinalStage schemas(List schemas) { this.schemas.clear(); - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -189,5 +201,17 @@ public _FinalStage schemas(List schemas) { public SchemasResponse build() { return new SchemasResponse(schemas, totalResults, resources, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ScimEmail.java b/src/main/java/com/langfuse/client/resources/scim/types/ScimEmail.java index 4425248..d96ca08 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ScimEmail.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ScimEmail.java @@ -100,6 +100,10 @@ public interface TypeStage { public interface _FinalStage { ScimEmail build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -151,5 +155,17 @@ public _FinalStage type(@NotNull String type) { public ScimEmail build() { return new ScimEmail(primary, value, type, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ScimFeatureSupport.java b/src/main/java/com/langfuse/client/resources/scim/types/ScimFeatureSupport.java index d635316..bde1bf1 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ScimFeatureSupport.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ScimFeatureSupport.java @@ -74,6 +74,10 @@ public interface SupportedStage { public interface _FinalStage { ScimFeatureSupport build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -105,5 +109,17 @@ public _FinalStage supported(boolean supported) { public ScimFeatureSupport build() { return new ScimFeatureSupport(supported, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ScimName.java b/src/main/java/com/langfuse/client/resources/scim/types/ScimName.java index 9e69d08..334c426 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ScimName.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ScimName.java @@ -102,5 +102,15 @@ public Builder formatted(String formatted) { public ScimName build() { return new ScimName(formatted, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ScimUser.java b/src/main/java/com/langfuse/client/resources/scim/types/ScimUser.java index 2b6f09b..dceb098 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ScimUser.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ScimUser.java @@ -132,6 +132,10 @@ public interface MetaStage { public interface _FinalStage { ScimUser build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage schemas(List schemas); _FinalStage addSchemas(String schemas); @@ -208,7 +212,9 @@ public _FinalStage meta(@NotNull UserMeta meta) { @java.lang.Override public _FinalStage addAllEmails(List emails) { - this.emails.addAll(emails); + if (emails != null) { + this.emails.addAll(emails); + } return this; } @@ -225,13 +231,17 @@ public _FinalStage addEmails(ScimEmail emails) { ) public _FinalStage emails(List emails) { this.emails.clear(); - this.emails.addAll(emails); + if (emails != null) { + this.emails.addAll(emails); + } return this; } @java.lang.Override public _FinalStage addAllSchemas(List schemas) { - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -248,7 +258,9 @@ public _FinalStage addSchemas(String schemas) { ) public _FinalStage schemas(List schemas) { this.schemas.clear(); - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -256,5 +268,17 @@ public _FinalStage schemas(List schemas) { public ScimUser build() { return new ScimUser(schemas, id, userName, name, emails, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ScimUsersListResponse.java b/src/main/java/com/langfuse/client/resources/scim/types/ScimUsersListResponse.java index 0a42ac5..e56a8f5 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ScimUsersListResponse.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ScimUsersListResponse.java @@ -119,6 +119,10 @@ public interface ItemsPerPageStage { public interface _FinalStage { ScimUsersListResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage schemas(List schemas); _FinalStage addSchemas(String schemas); @@ -185,7 +189,9 @@ public _FinalStage itemsPerPage(int itemsPerPage) { @java.lang.Override public _FinalStage addAllResources(List resources) { - this.resources.addAll(resources); + if (resources != null) { + this.resources.addAll(resources); + } return this; } @@ -202,13 +208,17 @@ public _FinalStage addResources(ScimUser resources) { ) public _FinalStage resources(List resources) { this.resources.clear(); - this.resources.addAll(resources); + if (resources != null) { + this.resources.addAll(resources); + } return this; } @java.lang.Override public _FinalStage addAllSchemas(List schemas) { - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -225,7 +235,9 @@ public _FinalStage addSchemas(String schemas) { ) public _FinalStage schemas(List schemas) { this.schemas.clear(); - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -233,5 +245,17 @@ public _FinalStage schemas(List schemas) { public ScimUsersListResponse build() { return new ScimUsersListResponse(schemas, totalResults, startIndex, itemsPerPage, resources, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/ServiceProviderConfig.java b/src/main/java/com/langfuse/client/resources/scim/types/ServiceProviderConfig.java index 861c1ab..6a4d22e 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/ServiceProviderConfig.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/ServiceProviderConfig.java @@ -183,6 +183,10 @@ public interface MetaStage { public interface _FinalStage { ServiceProviderConfig build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage schemas(List schemas); _FinalStage addSchemas(String schemas); @@ -300,7 +304,9 @@ public _FinalStage meta(@NotNull ResourceMeta meta) { @java.lang.Override public _FinalStage addAllAuthenticationSchemes( List authenticationSchemes) { - this.authenticationSchemes.addAll(authenticationSchemes); + if (authenticationSchemes != null) { + this.authenticationSchemes.addAll(authenticationSchemes); + } return this; } @@ -317,13 +323,17 @@ public _FinalStage addAuthenticationSchemes(AuthenticationScheme authenticationS ) public _FinalStage authenticationSchemes(List authenticationSchemes) { this.authenticationSchemes.clear(); - this.authenticationSchemes.addAll(authenticationSchemes); + if (authenticationSchemes != null) { + this.authenticationSchemes.addAll(authenticationSchemes); + } return this; } @java.lang.Override public _FinalStage addAllSchemas(List schemas) { - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -340,7 +350,9 @@ public _FinalStage addSchemas(String schemas) { ) public _FinalStage schemas(List schemas) { this.schemas.clear(); - this.schemas.addAll(schemas); + if (schemas != null) { + this.schemas.addAll(schemas); + } return this; } @@ -348,5 +360,17 @@ public _FinalStage schemas(List schemas) { public ServiceProviderConfig build() { return new ServiceProviderConfig(schemas, documentationUri, patch, bulk, filter, changePassword, sort, etag, authenticationSchemes, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scim/types/UserMeta.java b/src/main/java/com/langfuse/client/resources/scim/types/UserMeta.java index a8fd12d..641ae12 100644 --- a/src/main/java/com/langfuse/client/resources/scim/types/UserMeta.java +++ b/src/main/java/com/langfuse/client/resources/scim/types/UserMeta.java @@ -95,6 +95,10 @@ public interface ResourceTypeStage { public interface _FinalStage { UserMeta build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage created(Optional created); _FinalStage created(String created); @@ -171,5 +175,17 @@ public _FinalStage created(Optional created) { public UserMeta build() { return new UserMeta(resourceType, created, lastModified, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/score/AsyncRawScoreClient.java b/src/main/java/com/langfuse/client/resources/score/AsyncRawScoreClient.java new file mode 100644 index 0000000..6c30d8f --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/score/AsyncRawScoreClient.java @@ -0,0 +1,201 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.score; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.score.types.CreateScoreRequest; +import com.langfuse.client.resources.score.types.CreateScoreResponse; + +public class AsyncRawScoreClient { + protected final ClientOptions clientOptions; + + public AsyncRawScoreClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a score (supports both trace and session scores) + */ + public CompletableFuture> create( + CreateScoreRequest request) { + return create(request,null); + } + + /** + * Create a score (supports both trace and session scores) + */ + public CompletableFuture> create( + CreateScoreRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("scores");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateScoreResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a score (supports both trace and session scores) + */ + public CompletableFuture> delete(String scoreId) { + return delete(scoreId,null); + } + + /** + * Delete a score (supports both trace and session scores) + */ + public CompletableFuture> delete(String scoreId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("scores") + .addPathSegment(scoreId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(null, response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/score/AsyncScoreClient.java b/src/main/java/com/langfuse/client/resources/score/AsyncScoreClient.java new file mode 100644 index 0000000..9833ab9 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/score/AsyncScoreClient.java @@ -0,0 +1,60 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.score; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.lang.Void; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.score.types.CreateScoreRequest; +import com.langfuse.client.resources.score.types.CreateScoreResponse; + +public class AsyncScoreClient { + protected final ClientOptions clientOptions; + + private final AsyncRawScoreClient rawClient; + + public AsyncScoreClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawScoreClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawScoreClient withRawResponse() { + return this.rawClient; + } + + /** + * Create a score (supports both trace and session scores) + */ + public CompletableFuture create(CreateScoreRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a score (supports both trace and session scores) + */ + public CompletableFuture create(CreateScoreRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a score (supports both trace and session scores) + */ + public CompletableFuture delete(String scoreId) { + return this.rawClient.delete(scoreId).thenApply(response -> response.body()); + } + + /** + * Delete a score (supports both trace and session scores) + */ + public CompletableFuture delete(String scoreId, RequestOptions requestOptions) { + return this.rawClient.delete(scoreId, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/score/RawScoreClient.java b/src/main/java/com/langfuse/client/resources/score/RawScoreClient.java new file mode 100644 index 0000000..c9d029b --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/score/RawScoreClient.java @@ -0,0 +1,158 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.score; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import java.lang.Void; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.score.types.CreateScoreRequest; +import com.langfuse.client.resources.score.types.CreateScoreResponse; + +public class RawScoreClient { + protected final ClientOptions clientOptions; + + public RawScoreClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a score (supports both trace and session scores) + */ + public LangfuseClientHttpResponse create(CreateScoreRequest request) { + return create(request,null); + } + + /** + * Create a score (supports both trace and session scores) + */ + public LangfuseClientHttpResponse create(CreateScoreRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("scores");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateScoreResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a score (supports both trace and session scores) + */ + public LangfuseClientHttpResponse delete(String scoreId) { + return delete(scoreId,null); + } + + /** + * Delete a score (supports both trace and session scores) + */ + public LangfuseClientHttpResponse delete(String scoreId, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("scores") + .addPathSegment(scoreId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(null, response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/score/ScoreClient.java b/src/main/java/com/langfuse/client/resources/score/ScoreClient.java index 7c16c6c..24f254d 100644 --- a/src/main/java/com/langfuse/client/resources/score/ScoreClient.java +++ b/src/main/java/com/langfuse/client/resources/score/ScoreClient.java @@ -4,144 +4,54 @@ package com.langfuse.client.resources.score; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.score.types.CreateScoreRequest; import com.langfuse.client.resources.score.types.CreateScoreResponse; public class ScoreClient { protected final ClientOptions clientOptions; + private final RawScoreClient rawClient; + public ScoreClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawScoreClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawScoreClient withRawResponse() { + return this.rawClient; } /** * Create a score (supports both trace and session scores) */ public CreateScoreResponse create(CreateScoreRequest request) { - return create(request,null); + return this.rawClient.create(request).body(); } /** * Create a score (supports both trace and session scores) */ public CreateScoreResponse create(CreateScoreRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("scores") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateScoreResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * Delete a score (supports both trace and session scores) */ public void delete(String scoreId) { - delete(scoreId,null); + this.rawClient.delete(scoreId).body(); } /** * Delete a score (supports both trace and session scores) */ public void delete(String scoreId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("scores") - .addPathSegment(scoreId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + this.rawClient.delete(scoreId, requestOptions).body(); } } diff --git a/src/main/java/com/langfuse/client/resources/score/types/CreateScoreRequest.java b/src/main/java/com/langfuse/client/resources/score/types/CreateScoreRequest.java index f44c598..7bcfd22 100644 --- a/src/main/java/com/langfuse/client/resources/score/types/CreateScoreRequest.java +++ b/src/main/java/com/langfuse/client/resources/score/types/CreateScoreRequest.java @@ -194,12 +194,19 @@ public interface NameStage { } public interface ValueStage { + /** + *

        The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)

        + */ _FinalStage value(@NotNull CreateScoreValue value); } public interface _FinalStage { CreateScoreRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage id(Optional id); _FinalStage id(String id); @@ -228,18 +235,30 @@ public interface _FinalStage { _FinalStage metadata(Map metadata); + /** + *

        The environment of the score. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ _FinalStage environment(Optional environment); _FinalStage environment(String environment); + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); + /** + *

        The data type of the score. When passing a configId this field is inferred. Otherwise, this field must be passed or will default to numeric.

        + */ _FinalStage dataType(Optional dataType); _FinalStage dataType(ScoreDataType dataType); + /** + *

        Reference a score config on a score. The unique langfuse identifier of a score config. When passing this field, the dataType and stringValue fields are automatically populated.

        + */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); @@ -307,6 +326,7 @@ public ValueStage name(@NotNull String name) { } /** + *

        The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)

        *

        The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -327,6 +347,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

        Reference a score config on a score. The unique langfuse identifier of a score config. When passing this field, the dataType and stringValue fields are automatically populated.

        + */ @java.lang.Override @JsonSetter( value = "configId", @@ -347,6 +370,9 @@ public _FinalStage dataType(ScoreDataType dataType) { return this; } + /** + *

        The data type of the score. When passing a configId this field is inferred. Otherwise, this field must be passed or will default to numeric.

        + */ @java.lang.Override @JsonSetter( value = "dataType", @@ -367,6 +393,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ @java.lang.Override @JsonSetter( value = "queueId", @@ -387,6 +416,9 @@ public _FinalStage environment(String environment) { return this; } + /** + *

        The environment of the score. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ @java.lang.Override @JsonSetter( value = "environment", @@ -513,5 +545,17 @@ public _FinalStage id(Optional id) { public CreateScoreRequest build() { return new CreateScoreRequest(id, traceId, sessionId, observationId, datasetRunId, name, value, comment, metadata, environment, queueId, dataType, configId, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/score/types/CreateScoreResponse.java b/src/main/java/com/langfuse/client/resources/score/types/CreateScoreResponse.java index 5876c61..3be2dac 100644 --- a/src/main/java/com/langfuse/client/resources/score/types/CreateScoreResponse.java +++ b/src/main/java/com/langfuse/client/resources/score/types/CreateScoreResponse.java @@ -71,6 +71,9 @@ public static IdStage builder() { } public interface IdStage { + /** + *

        The id of the created object in Langfuse

        + */ _FinalStage id(@NotNull String id); Builder from(CreateScoreResponse other); @@ -78,6 +81,10 @@ public interface IdStage { public interface _FinalStage { CreateScoreResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -99,6 +106,7 @@ public Builder from(CreateScoreResponse other) { } /** + *

        The id of the created object in Langfuse

        *

        The id of the created object in Langfuse

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -113,5 +121,17 @@ public _FinalStage id(@NotNull String id) { public CreateScoreResponse build() { return new CreateScoreResponse(id, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/AsyncRawScoreConfigsClient.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/AsyncRawScoreConfigsClient.java new file mode 100644 index 0000000..8741caa --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/AsyncRawScoreConfigsClient.java @@ -0,0 +1,397 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scoreconfigs; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.ScoreConfig; +import com.langfuse.client.resources.scoreconfigs.requests.GetScoreConfigsRequest; +import com.langfuse.client.resources.scoreconfigs.types.CreateScoreConfigRequest; +import com.langfuse.client.resources.scoreconfigs.types.ScoreConfigs; +import com.langfuse.client.resources.scoreconfigs.types.UpdateScoreConfigRequest; + +public class AsyncRawScoreConfigsClient { + protected final ClientOptions clientOptions; + + public AsyncRawScoreConfigsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a score configuration (config). Score configs are used to define the structure of scores + */ + public CompletableFuture> create( + CreateScoreConfigRequest request) { + return create(request,null); + } + + /** + * Create a score configuration (config). Score configs are used to define the structure of scores + */ + public CompletableFuture> create( + CreateScoreConfigRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfig.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get all score configs + */ + public CompletableFuture> get() { + return get(GetScoreConfigsRequest.builder().build()); + } + + /** + * Get all score configs + */ + public CompletableFuture> get( + RequestOptions requestOptions) { + return get(GetScoreConfigsRequest.builder().build(),requestOptions); + } + + /** + * Get all score configs + */ + public CompletableFuture> get( + GetScoreConfigsRequest request) { + return get(request,null); + } + + /** + * Get all score configs + */ + public CompletableFuture> get( + GetScoreConfigsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfigs.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a score config + */ + public CompletableFuture> getById(String configId) { + return getById(configId,null); + } + + /** + * Get a score config + */ + public CompletableFuture> getById(String configId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs") + .addPathSegment(configId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfig.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Update a score config + */ + public CompletableFuture> update(String configId) { + return update(configId,UpdateScoreConfigRequest.builder().build()); + } + + /** + * Update a score config + */ + public CompletableFuture> update(String configId, + RequestOptions requestOptions) { + return update(configId,UpdateScoreConfigRequest.builder().build(),requestOptions); + } + + /** + * Update a score config + */ + public CompletableFuture> update(String configId, + UpdateScoreConfigRequest request) { + return update(configId,request,null); + } + + /** + * Update a score config + */ + public CompletableFuture> update(String configId, + UpdateScoreConfigRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs") + .addPathSegment(configId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfig.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/AsyncScoreConfigsClient.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/AsyncScoreConfigsClient.java new file mode 100644 index 0000000..cfcc6df --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/AsyncScoreConfigsClient.java @@ -0,0 +1,120 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scoreconfigs; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.ScoreConfig; +import com.langfuse.client.resources.scoreconfigs.requests.GetScoreConfigsRequest; +import com.langfuse.client.resources.scoreconfigs.types.CreateScoreConfigRequest; +import com.langfuse.client.resources.scoreconfigs.types.ScoreConfigs; +import com.langfuse.client.resources.scoreconfigs.types.UpdateScoreConfigRequest; + +public class AsyncScoreConfigsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawScoreConfigsClient rawClient; + + public AsyncScoreConfigsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawScoreConfigsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawScoreConfigsClient withRawResponse() { + return this.rawClient; + } + + /** + * Create a score configuration (config). Score configs are used to define the structure of scores + */ + public CompletableFuture create(CreateScoreConfigRequest request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Create a score configuration (config). Score configs are used to define the structure of scores + */ + public CompletableFuture create(CreateScoreConfigRequest request, + RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all score configs + */ + public CompletableFuture get() { + return this.rawClient.get().thenApply(response -> response.body()); + } + + /** + * Get all score configs + */ + public CompletableFuture get(RequestOptions requestOptions) { + return this.rawClient.get(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get all score configs + */ + public CompletableFuture get(GetScoreConfigsRequest request) { + return this.rawClient.get(request).thenApply(response -> response.body()); + } + + /** + * Get all score configs + */ + public CompletableFuture get(GetScoreConfigsRequest request, + RequestOptions requestOptions) { + return this.rawClient.get(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a score config + */ + public CompletableFuture getById(String configId) { + return this.rawClient.getById(configId).thenApply(response -> response.body()); + } + + /** + * Get a score config + */ + public CompletableFuture getById(String configId, RequestOptions requestOptions) { + return this.rawClient.getById(configId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Update a score config + */ + public CompletableFuture update(String configId) { + return this.rawClient.update(configId).thenApply(response -> response.body()); + } + + /** + * Update a score config + */ + public CompletableFuture update(String configId, RequestOptions requestOptions) { + return this.rawClient.update(configId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Update a score config + */ + public CompletableFuture update(String configId, UpdateScoreConfigRequest request) { + return this.rawClient.update(configId, request).thenApply(response -> response.body()); + } + + /** + * Update a score config + */ + public CompletableFuture update(String configId, UpdateScoreConfigRequest request, + RequestOptions requestOptions) { + return this.rawClient.update(configId, request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/RawScoreConfigsClient.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/RawScoreConfigsClient.java new file mode 100644 index 0000000..ed8280b --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/RawScoreConfigsClient.java @@ -0,0 +1,317 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scoreconfigs; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.ScoreConfig; +import com.langfuse.client.resources.scoreconfigs.requests.GetScoreConfigsRequest; +import com.langfuse.client.resources.scoreconfigs.types.CreateScoreConfigRequest; +import com.langfuse.client.resources.scoreconfigs.types.ScoreConfigs; +import com.langfuse.client.resources.scoreconfigs.types.UpdateScoreConfigRequest; + +public class RawScoreConfigsClient { + protected final ClientOptions clientOptions; + + public RawScoreConfigsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Create a score configuration (config). Score configs are used to define the structure of scores + */ + public LangfuseClientHttpResponse create(CreateScoreConfigRequest request) { + return create(request,null); + } + + /** + * Create a score configuration (config). Score configs are used to define the structure of scores + */ + public LangfuseClientHttpResponse create(CreateScoreConfigRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfig.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get all score configs + */ + public LangfuseClientHttpResponse get() { + return get(GetScoreConfigsRequest.builder().build()); + } + + /** + * Get all score configs + */ + public LangfuseClientHttpResponse get(RequestOptions requestOptions) { + return get(GetScoreConfigsRequest.builder().build(),requestOptions); + } + + /** + * Get all score configs + */ + public LangfuseClientHttpResponse get(GetScoreConfigsRequest request) { + return get(request,null); + } + + /** + * Get all score configs + */ + public LangfuseClientHttpResponse get(GetScoreConfigsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfigs.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a score config + */ + public LangfuseClientHttpResponse getById(String configId) { + return getById(configId,null); + } + + /** + * Get a score config + */ + public LangfuseClientHttpResponse getById(String configId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs") + .addPathSegment(configId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfig.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Update a score config + */ + public LangfuseClientHttpResponse update(String configId) { + return update(configId,UpdateScoreConfigRequest.builder().build()); + } + + /** + * Update a score config + */ + public LangfuseClientHttpResponse update(String configId, + RequestOptions requestOptions) { + return update(configId,UpdateScoreConfigRequest.builder().build(),requestOptions); + } + + /** + * Update a score config + */ + public LangfuseClientHttpResponse update(String configId, + UpdateScoreConfigRequest request) { + return update(configId,request,null); + } + + /** + * Update a score config + */ + public LangfuseClientHttpResponse update(String configId, + UpdateScoreConfigRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("score-configs") + .addPathSegment(configId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ScoreConfig.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/ScoreConfigsClient.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/ScoreConfigsClient.java index 857a81d..626c22d 100644 --- a/src/main/java/com/langfuse/client/resources/scoreconfigs/ScoreConfigsClient.java +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/ScoreConfigsClient.java @@ -4,29 +4,9 @@ package com.langfuse.client.resources.scoreconfigs; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.ScoreConfig; import com.langfuse.client.resources.scoreconfigs.requests.GetScoreConfigsRequest; import com.langfuse.client.resources.scoreconfigs.types.CreateScoreConfigRequest; @@ -36,246 +16,102 @@ public class ScoreConfigsClient { protected final ClientOptions clientOptions; + private final RawScoreConfigsClient rawClient; + public ScoreConfigsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawScoreConfigsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawScoreConfigsClient withRawResponse() { + return this.rawClient; } /** * Create a score configuration (config). Score configs are used to define the structure of scores */ public ScoreConfig create(CreateScoreConfigRequest request) { - return create(request,null); + return this.rawClient.create(request).body(); } /** * Create a score configuration (config). Score configs are used to define the structure of scores */ public ScoreConfig create(CreateScoreConfigRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("score-configs") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ScoreConfig.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.create(request, requestOptions).body(); } /** * Get all score configs */ public ScoreConfigs get() { - return get(GetScoreConfigsRequest.builder().build()); + return this.rawClient.get().body(); + } + + /** + * Get all score configs + */ + public ScoreConfigs get(RequestOptions requestOptions) { + return this.rawClient.get(requestOptions).body(); } /** * Get all score configs */ public ScoreConfigs get(GetScoreConfigsRequest request) { - return get(request,null); + return this.rawClient.get(request).body(); } /** * Get all score configs */ public ScoreConfigs get(GetScoreConfigsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("score-configs");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ScoreConfigs.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.get(request, requestOptions).body(); + } - /** - * Get a score config - */ - public ScoreConfig getById(String configId) { - return getById(configId,null); - } + /** + * Get a score config + */ + public ScoreConfig getById(String configId) { + return this.rawClient.getById(configId).body(); + } - /** - * Get a score config - */ - public ScoreConfig getById(String configId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("score-configs") - .addPathSegment(configId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ScoreConfig.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a score config + */ + public ScoreConfig getById(String configId, RequestOptions requestOptions) { + return this.rawClient.getById(configId, requestOptions).body(); + } - /** - * Update a score config - */ - public ScoreConfig update(String configId) { - return update(configId,UpdateScoreConfigRequest.builder().build()); - } + /** + * Update a score config + */ + public ScoreConfig update(String configId) { + return this.rawClient.update(configId).body(); + } + + /** + * Update a score config + */ + public ScoreConfig update(String configId, RequestOptions requestOptions) { + return this.rawClient.update(configId, requestOptions).body(); + } - /** - * Update a score config - */ - public ScoreConfig update(String configId, UpdateScoreConfigRequest request) { - return update(configId,request,null); - } + /** + * Update a score config + */ + public ScoreConfig update(String configId, UpdateScoreConfigRequest request) { + return this.rawClient.update(configId, request).body(); + } - /** - * Update a score config - */ - public ScoreConfig update(String configId, UpdateScoreConfigRequest request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("score-configs") - .addPathSegment(configId) - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ScoreConfig.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Update a score config + */ + public ScoreConfig update(String configId, UpdateScoreConfigRequest request, + RequestOptions requestOptions) { + return this.rawClient.update(configId, request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/requests/GetScoreConfigsRequest.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/requests/GetScoreConfigsRequest.java index 655b884..861ddfa 100644 --- a/src/main/java/com/langfuse/client/resources/scoreconfigs/requests/GetScoreConfigsRequest.java +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/requests/GetScoreConfigsRequest.java @@ -104,6 +104,9 @@ public Builder from(GetScoreConfigsRequest other) { return this; } + /** + *

        Page number, starts at 1.

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -118,6 +121,9 @@ public Builder page(Integer page) { return this; } + /** + *

        Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -135,5 +141,15 @@ public Builder limit(Integer limit) { public GetScoreConfigsRequest build() { return new GetScoreConfigsRequest(page, limit, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/types/CreateScoreConfigRequest.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/types/CreateScoreConfigRequest.java index 3fb700d..c0c911b 100644 --- a/src/main/java/com/langfuse/client/resources/scoreconfigs/types/CreateScoreConfigRequest.java +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/types/CreateScoreConfigRequest.java @@ -141,18 +141,34 @@ public interface DataTypeStage { public interface _FinalStage { CreateScoreConfigRequest build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        Configure custom categories for categorical scores. Pass a list of objects with label and value properties. Categories are autogenerated for boolean configs and cannot be passed

        + */ _FinalStage categories(Optional> categories); _FinalStage categories(List categories); + /** + *

        Configure a minimum value for numerical scores. If not set, the minimum value defaults to -∞

        + */ _FinalStage minValue(Optional minValue); _FinalStage minValue(Double minValue); + /** + *

        Configure a maximum value for numerical scores. If not set, the maximum value defaults to +∞

        + */ _FinalStage maxValue(Optional maxValue); _FinalStage maxValue(Double maxValue); + /** + *

        Description is shown across the Langfuse UI and can be used to e.g. explain the config categories in detail, why a numeric range was set, or provide additional context on config name or usage

        + */ _FinalStage description(Optional description); _FinalStage description(String description); @@ -215,6 +231,9 @@ public _FinalStage description(String description) { return this; } + /** + *

        Description is shown across the Langfuse UI and can be used to e.g. explain the config categories in detail, why a numeric range was set, or provide additional context on config name or usage

        + */ @java.lang.Override @JsonSetter( value = "description", @@ -235,6 +254,9 @@ public _FinalStage maxValue(Double maxValue) { return this; } + /** + *

        Configure a maximum value for numerical scores. If not set, the maximum value defaults to +∞

        + */ @java.lang.Override @JsonSetter( value = "maxValue", @@ -255,6 +277,9 @@ public _FinalStage minValue(Double minValue) { return this; } + /** + *

        Configure a minimum value for numerical scores. If not set, the minimum value defaults to -∞

        + */ @java.lang.Override @JsonSetter( value = "minValue", @@ -275,6 +300,9 @@ public _FinalStage categories(List categories) { return this; } + /** + *

        Configure custom categories for categorical scores. Pass a list of objects with label and value properties. Categories are autogenerated for boolean configs and cannot be passed

        + */ @java.lang.Override @JsonSetter( value = "categories", @@ -289,5 +317,17 @@ public _FinalStage categories(Optional> categories) { public CreateScoreConfigRequest build() { return new CreateScoreConfigRequest(name, dataType, categories, minValue, maxValue, description, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/types/ScoreConfigs.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/types/ScoreConfigs.java index 5e0b21f..40ec4b6 100644 --- a/src/main/java/com/langfuse/client/resources/scoreconfigs/types/ScoreConfigs.java +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/types/ScoreConfigs.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { ScoreConfigs build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(ScoreConfig data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(ScoreConfig data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public ScoreConfigs build() { return new ScoreConfigs(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scoreconfigs/types/UpdateScoreConfigRequest.java b/src/main/java/com/langfuse/client/resources/scoreconfigs/types/UpdateScoreConfigRequest.java index 90cf116..80a3d71 100644 --- a/src/main/java/com/langfuse/client/resources/scoreconfigs/types/UpdateScoreConfigRequest.java +++ b/src/main/java/com/langfuse/client/resources/scoreconfigs/types/UpdateScoreConfigRequest.java @@ -165,6 +165,9 @@ public Builder from(UpdateScoreConfigRequest other) { return this; } + /** + *

        The status of the score config showing if it is archived or not

        + */ @JsonSetter( value = "isArchived", nulls = Nulls.SKIP @@ -179,6 +182,9 @@ public Builder isArchived(Boolean isArchived) { return this; } + /** + *

        The name of the score config

        + */ @JsonSetter( value = "name", nulls = Nulls.SKIP @@ -193,6 +199,9 @@ public Builder name(String name) { return this; } + /** + *

        Configure custom categories for categorical scores. Pass a list of objects with label and value properties. Categories are autogenerated for boolean configs and cannot be passed

        + */ @JsonSetter( value = "categories", nulls = Nulls.SKIP @@ -207,6 +216,9 @@ public Builder categories(List categories) { return this; } + /** + *

        Configure a minimum value for numerical scores. If not set, the minimum value defaults to -∞

        + */ @JsonSetter( value = "minValue", nulls = Nulls.SKIP @@ -221,6 +233,9 @@ public Builder minValue(Double minValue) { return this; } + /** + *

        Configure a maximum value for numerical scores. If not set, the maximum value defaults to +∞

        + */ @JsonSetter( value = "maxValue", nulls = Nulls.SKIP @@ -235,6 +250,9 @@ public Builder maxValue(Double maxValue) { return this; } + /** + *

        Description is shown across the Langfuse UI and can be used to e.g. explain the config categories in detail, why a numeric range was set, or provide additional context on config name or usage

        + */ @JsonSetter( value = "description", nulls = Nulls.SKIP @@ -252,5 +270,15 @@ public Builder description(String description) { public UpdateScoreConfigRequest build() { return new UpdateScoreConfigRequest(isArchived, name, categories, minValue, maxValue, description, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/AsyncRawScoreV2Client.java b/src/main/java/com/langfuse/client/resources/scorev2/AsyncRawScoreV2Client.java new file mode 100644 index 0000000..32f329b --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scorev2/AsyncRawScoreV2Client.java @@ -0,0 +1,270 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scorev2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Score; +import com.langfuse.client.resources.scorev2.requests.GetScoresRequest; +import com.langfuse.client.resources.scorev2.types.GetScoresResponse; + +public class AsyncRawScoreV2Client { + protected final ClientOptions clientOptions; + + public AsyncRawScoreV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture> get() { + return get(GetScoresRequest.builder().build()); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture> get( + RequestOptions requestOptions) { + return get(GetScoresRequest.builder().build(),requestOptions); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture> get( + GetScoresRequest request) { + return get(request,null); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture> get( + GetScoresRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("scores");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getFromTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get(), false); + } + if (request.getToTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get(), false); + } + if (request.getSource().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "source", request.getSource().get(), false); + } + if (request.getOperator().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "operator", request.getOperator().get(), false); + } + if (request.getValue().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "value", request.getValue().get(), false); + } + if (request.getScoreIds().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "scoreIds", request.getScoreIds().get(), false); + } + if (request.getConfigId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "configId", request.getConfigId().get(), false); + } + if (request.getSessionId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sessionId", request.getSessionId().get(), false); + } + if (request.getDatasetRunId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "datasetRunId", request.getDatasetRunId().get(), false); + } + if (request.getTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); + } + if (request.getObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "observationId", request.getObservationId().get(), false); + } + if (request.getQueueId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "queueId", request.getQueueId().get(), false); + } + if (request.getDataType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "dataType", request.getDataType().get(), false); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (request.getTraceTags().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceTags", request.getTraceTags().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetScoresResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a score (supports both trace and session scores) + */ + public CompletableFuture> getById(String scoreId) { + return getById(scoreId,null); + } + + /** + * Get a score (supports both trace and session scores) + */ + public CompletableFuture> getById(String scoreId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("scores") + .addPathSegment(scoreId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Score.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/AsyncScoreV2Client.java b/src/main/java/com/langfuse/client/resources/scorev2/AsyncScoreV2Client.java new file mode 100644 index 0000000..5ea5380 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scorev2/AsyncScoreV2Client.java @@ -0,0 +1,74 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scorev2; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.Score; +import com.langfuse.client.resources.scorev2.requests.GetScoresRequest; +import com.langfuse.client.resources.scorev2.types.GetScoresResponse; + +public class AsyncScoreV2Client { + protected final ClientOptions clientOptions; + + private final AsyncRawScoreV2Client rawClient; + + public AsyncScoreV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawScoreV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawScoreV2Client withRawResponse() { + return this.rawClient; + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture get() { + return this.rawClient.get().thenApply(response -> response.body()); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture get(RequestOptions requestOptions) { + return this.rawClient.get(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture get(GetScoresRequest request) { + return this.rawClient.get(request).thenApply(response -> response.body()); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public CompletableFuture get(GetScoresRequest request, + RequestOptions requestOptions) { + return this.rawClient.get(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a score (supports both trace and session scores) + */ + public CompletableFuture getById(String scoreId) { + return this.rawClient.getById(scoreId).thenApply(response -> response.body()); + } + + /** + * Get a score (supports both trace and session scores) + */ + public CompletableFuture getById(String scoreId, RequestOptions requestOptions) { + return this.rawClient.getById(scoreId, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/scorev2/RawScoreV2Client.java b/src/main/java/com/langfuse/client/resources/scorev2/RawScoreV2Client.java new file mode 100644 index 0000000..ead2999 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scorev2/RawScoreV2Client.java @@ -0,0 +1,227 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scorev2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.Score; +import com.langfuse.client.resources.scorev2.requests.GetScoresRequest; +import com.langfuse.client.resources.scorev2.types.GetScoresResponse; + +public class RawScoreV2Client { + protected final ClientOptions clientOptions; + + public RawScoreV2Client(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public LangfuseClientHttpResponse get() { + return get(GetScoresRequest.builder().build()); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public LangfuseClientHttpResponse get(RequestOptions requestOptions) { + return get(GetScoresRequest.builder().build(),requestOptions); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public LangfuseClientHttpResponse get(GetScoresRequest request) { + return get(request,null); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public LangfuseClientHttpResponse get(GetScoresRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("scores");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getFromTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get(), false); + } + if (request.getToTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get(), false); + } + if (request.getSource().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "source", request.getSource().get(), false); + } + if (request.getOperator().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "operator", request.getOperator().get(), false); + } + if (request.getValue().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "value", request.getValue().get(), false); + } + if (request.getScoreIds().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "scoreIds", request.getScoreIds().get(), false); + } + if (request.getConfigId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "configId", request.getConfigId().get(), false); + } + if (request.getSessionId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sessionId", request.getSessionId().get(), false); + } + if (request.getDatasetRunId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "datasetRunId", request.getDatasetRunId().get(), false); + } + if (request.getTraceId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); + } + if (request.getObservationId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "observationId", request.getObservationId().get(), false); + } + if (request.getQueueId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "queueId", request.getQueueId().get(), false); + } + if (request.getDataType().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "dataType", request.getDataType().get(), false); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (request.getTraceTags().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "traceTags", request.getTraceTags().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetScoresResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a score (supports both trace and session scores) + */ + public LangfuseClientHttpResponse getById(String scoreId) { + return getById(scoreId,null); + } + + /** + * Get a score (supports both trace and session scores) + */ + public LangfuseClientHttpResponse getById(String scoreId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public/v2") + .addPathSegments("scores") + .addPathSegment(scoreId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Score.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/ScoreV2Client.java b/src/main/java/com/langfuse/client/resources/scorev2/ScoreV2Client.java index 42ce992..1ac5d44 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/ScoreV2Client.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/ScoreV2Client.java @@ -4,27 +4,9 @@ package com.langfuse.client.resources.scorev2; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.Score; import com.langfuse.client.resources.scorev2.requests.GetScoresRequest; import com.langfuse.client.resources.scorev2.types.GetScoresResponse; @@ -32,172 +14,59 @@ public class ScoreV2Client { protected final ClientOptions clientOptions; + private final RawScoreV2Client rawClient; + public ScoreV2Client(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawScoreV2Client(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawScoreV2Client withRawResponse() { + return this.rawClient; } /** * Get a list of scores (supports both trace and session scores) */ public GetScoresResponse get() { - return get(GetScoresRequest.builder().build()); + return this.rawClient.get().body(); + } + + /** + * Get a list of scores (supports both trace and session scores) + */ + public GetScoresResponse get(RequestOptions requestOptions) { + return this.rawClient.get(requestOptions).body(); } /** * Get a list of scores (supports both trace and session scores) */ public GetScoresResponse get(GetScoresRequest request) { - return get(request,null); + return this.rawClient.get(request).body(); } /** * Get a list of scores (supports both trace and session scores) */ public GetScoresResponse get(GetScoresRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/v2") - .addPathSegments("scores");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - if (request.getUserId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); - } - if (request.getName().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); - } - if (request.getFromTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get().toString(), false); - } - if (request.getToTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get().toString(), false); - } - if (request.getEnvironment().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), false); - } - if (request.getSource().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "source", request.getSource().get().toString(), false); - } - if (request.getOperator().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "operator", request.getOperator().get(), false); - } - if (request.getValue().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "value", request.getValue().get().toString(), false); - } - if (request.getScoreIds().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "scoreIds", request.getScoreIds().get(), false); - } - if (request.getConfigId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "configId", request.getConfigId().get(), false); - } - if (request.getSessionId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "sessionId", request.getSessionId().get(), false); - } - if (request.getDatasetRunId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "datasetRunId", request.getDatasetRunId().get(), false); - } - if (request.getTraceId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "traceId", request.getTraceId().get(), false); - } - if (request.getQueueId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "queueId", request.getQueueId().get(), false); - } - if (request.getDataType().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "dataType", request.getDataType().get().toString(), false); - } - if (request.getTraceTags().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "traceTags", request.getTraceTags().get(), false); - } - if (request.getFields().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetScoresResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.get(request, requestOptions).body(); + } - /** - * Get a score (supports both trace and session scores) - */ - public Score getById(String scoreId) { - return getById(scoreId,null); - } + /** + * Get a score (supports both trace and session scores) + */ + public Score getById(String scoreId) { + return this.rawClient.getById(scoreId).body(); + } - /** - * Get a score (supports both trace and session scores) - */ - public Score getById(String scoreId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public/v2") - .addPathSegments("scores") - .addPathSegment(scoreId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Score.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a score (supports both trace and session scores) + */ + public Score getById(String scoreId, RequestOptions requestOptions) { + return this.rawClient.getById(scoreId, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/scorev2/requests/GetScoresRequest.java b/src/main/java/com/langfuse/client/resources/scorev2/requests/GetScoresRequest.java index 62ff080..7b9c1e2 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/requests/GetScoresRequest.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/requests/GetScoresRequest.java @@ -18,7 +18,9 @@ import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -30,6 +32,10 @@ builder = GetScoresRequest.Builder.class ) public final class GetScoresRequest { + private final Optional> environment; + + private final Optional> traceTags; + private final Optional page; private final Optional limit; @@ -42,8 +48,6 @@ public final class GetScoresRequest { private final Optional toTimestamp; - private final Optional environment; - private final Optional source; private final Optional operator; @@ -60,31 +64,34 @@ public final class GetScoresRequest { private final Optional traceId; + private final Optional observationId; + private final Optional queueId; private final Optional dataType; - private final Optional traceTags; - private final Optional fields; + private final Optional filter; + private final Map additionalProperties; - private GetScoresRequest(Optional page, Optional limit, Optional userId, + private GetScoresRequest(Optional> environment, Optional> traceTags, + Optional page, Optional limit, Optional userId, Optional name, Optional fromTimestamp, - Optional toTimestamp, Optional environment, - Optional source, Optional operator, Optional value, - Optional scoreIds, Optional configId, Optional sessionId, - Optional datasetRunId, Optional traceId, Optional queueId, - Optional dataType, Optional traceTags, Optional fields, - Map additionalProperties) { + Optional toTimestamp, Optional source, Optional operator, + Optional value, Optional scoreIds, Optional configId, + Optional sessionId, Optional datasetRunId, Optional traceId, + Optional observationId, Optional queueId, Optional dataType, + Optional fields, Optional filter, Map additionalProperties) { + this.environment = environment; + this.traceTags = traceTags; this.page = page; this.limit = limit; this.userId = userId; this.name = name; this.fromTimestamp = fromTimestamp; this.toTimestamp = toTimestamp; - this.environment = environment; this.source = source; this.operator = operator; this.value = value; @@ -93,13 +100,30 @@ private GetScoresRequest(Optional page, Optional limit, Option this.sessionId = sessionId; this.datasetRunId = datasetRunId; this.traceId = traceId; + this.observationId = observationId; this.queueId = queueId; this.dataType = dataType; - this.traceTags = traceTags; this.fields = fields; + this.filter = filter; this.additionalProperties = additionalProperties; } + /** + * @return Optional filter for scores where the environment is one of the provided values. + */ + @JsonProperty("environment") + public Optional> getEnvironment() { + return environment; + } + + /** + * @return Only scores linked to traces that include all of these tags will be returned. + */ + @JsonProperty("traceTags") + public Optional> getTraceTags() { + return traceTags; + } + /** * @return Page number, starts at 1. */ @@ -148,14 +172,6 @@ public Optional getToTimestamp() { return toTimestamp; } - /** - * @return Optional filter for scores where the environment is one of the provided values. - */ - @JsonProperty("environment") - public Optional getEnvironment() { - return environment; - } - /** * @return Retrieve only scores from a specific source. */ @@ -220,6 +236,14 @@ public Optional getTraceId() { return traceId; } + /** + * @return Comma-separated list of observation IDs to filter scores by. + */ + @JsonProperty("observationId") + public Optional getObservationId() { + return observationId; + } + /** * @return Retrieve only scores with a specific annotation queueId. */ @@ -236,14 +260,6 @@ public Optional getDataType() { return dataType; } - /** - * @return Only scores linked to traces that include all of these tags will be returned. - */ - @JsonProperty("traceTags") - public Optional getTraceTags() { - return traceTags; - } - /** * @return Comma-separated list of field groups to include in the response. Available field groups: 'score' (core score fields), 'trace' (trace properties: userId, tags, environment). If not specified, both 'score' and 'trace' are returned by default. Example: 'score' to exclude trace data, 'score,trace' to include both. Note: When filtering by trace properties (using userId or traceTags parameters), the 'trace' field group must be included, otherwise a 400 error will be returned. */ @@ -252,6 +268,14 @@ public Optional getFields() { return fields; } + /** + * @return A JSON stringified array of filter objects. Each object requires type, column, operator, and value. Supports filtering by score metadata using the stringObject type. Example: [{"type":"stringObject","column":"metadata","key":"user_id","operator":"=","value":"abc123"}]. Supported types: stringObject (metadata key-value filtering), string, number, datetime, stringOptions, arrayOptions. Supported operators for stringObject: =, contains, does not contain, starts with, ends with. + */ + @JsonProperty("filter") + public Optional getFilter() { + return filter; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -264,12 +288,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(GetScoresRequest other) { - return page.equals(other.page) && limit.equals(other.limit) && userId.equals(other.userId) && name.equals(other.name) && fromTimestamp.equals(other.fromTimestamp) && toTimestamp.equals(other.toTimestamp) && environment.equals(other.environment) && source.equals(other.source) && operator.equals(other.operator) && value.equals(other.value) && scoreIds.equals(other.scoreIds) && configId.equals(other.configId) && sessionId.equals(other.sessionId) && datasetRunId.equals(other.datasetRunId) && traceId.equals(other.traceId) && queueId.equals(other.queueId) && dataType.equals(other.dataType) && traceTags.equals(other.traceTags) && fields.equals(other.fields); + return environment.equals(other.environment) && traceTags.equals(other.traceTags) && page.equals(other.page) && limit.equals(other.limit) && userId.equals(other.userId) && name.equals(other.name) && fromTimestamp.equals(other.fromTimestamp) && toTimestamp.equals(other.toTimestamp) && source.equals(other.source) && operator.equals(other.operator) && value.equals(other.value) && scoreIds.equals(other.scoreIds) && configId.equals(other.configId) && sessionId.equals(other.sessionId) && datasetRunId.equals(other.datasetRunId) && traceId.equals(other.traceId) && observationId.equals(other.observationId) && queueId.equals(other.queueId) && dataType.equals(other.dataType) && fields.equals(other.fields) && filter.equals(other.filter); } @java.lang.Override public int hashCode() { - return Objects.hash(this.page, this.limit, this.userId, this.name, this.fromTimestamp, this.toTimestamp, this.environment, this.source, this.operator, this.value, this.scoreIds, this.configId, this.sessionId, this.datasetRunId, this.traceId, this.queueId, this.dataType, this.traceTags, this.fields); + return Objects.hash(this.environment, this.traceTags, this.page, this.limit, this.userId, this.name, this.fromTimestamp, this.toTimestamp, this.source, this.operator, this.value, this.scoreIds, this.configId, this.sessionId, this.datasetRunId, this.traceId, this.observationId, this.queueId, this.dataType, this.fields, this.filter); } @java.lang.Override @@ -285,6 +309,10 @@ public static Builder builder() { ignoreUnknown = true ) public static final class Builder { + private Optional> environment = Optional.empty(); + + private Optional> traceTags = Optional.empty(); + private Optional page = Optional.empty(); private Optional limit = Optional.empty(); @@ -297,8 +325,6 @@ public static final class Builder { private Optional toTimestamp = Optional.empty(); - private Optional environment = Optional.empty(); - private Optional source = Optional.empty(); private Optional operator = Optional.empty(); @@ -315,14 +341,16 @@ public static final class Builder { private Optional traceId = Optional.empty(); + private Optional observationId = Optional.empty(); + private Optional queueId = Optional.empty(); private Optional dataType = Optional.empty(); - private Optional traceTags = Optional.empty(); - private Optional fields = Optional.empty(); + private Optional filter = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -330,13 +358,14 @@ private Builder() { } public Builder from(GetScoresRequest other) { + environment(other.getEnvironment()); + traceTags(other.getTraceTags()); page(other.getPage()); limit(other.getLimit()); userId(other.getUserId()); name(other.getName()); fromTimestamp(other.getFromTimestamp()); toTimestamp(other.getToTimestamp()); - environment(other.getEnvironment()); source(other.getSource()); operator(other.getOperator()); value(other.getValue()); @@ -345,13 +374,61 @@ public Builder from(GetScoresRequest other) { sessionId(other.getSessionId()); datasetRunId(other.getDatasetRunId()); traceId(other.getTraceId()); + observationId(other.getObservationId()); queueId(other.getQueueId()); dataType(other.getDataType()); - traceTags(other.getTraceTags()); fields(other.getFields()); + filter(other.getFilter()); + return this; + } + + /** + *

        Optional filter for scores where the environment is one of the provided values.

        + */ + @JsonSetter( + value = "environment", + nulls = Nulls.SKIP + ) + public Builder environment(Optional> environment) { + this.environment = environment; + return this; + } + + public Builder environment(List environment) { + this.environment = Optional.ofNullable(environment); return this; } + public Builder environment(String environment) { + this.environment = Optional.of(Collections.singletonList(environment)); + return this; + } + + /** + *

        Only scores linked to traces that include all of these tags will be returned.

        + */ + @JsonSetter( + value = "traceTags", + nulls = Nulls.SKIP + ) + public Builder traceTags(Optional> traceTags) { + this.traceTags = traceTags; + return this; + } + + public Builder traceTags(List traceTags) { + this.traceTags = Optional.ofNullable(traceTags); + return this; + } + + public Builder traceTags(String traceTags) { + this.traceTags = Optional.of(Collections.singletonList(traceTags)); + return this; + } + + /** + *

        Page number, starts at 1.

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -366,6 +443,9 @@ public Builder page(Integer page) { return this; } + /** + *

        Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -380,6 +460,9 @@ public Builder limit(Integer limit) { return this; } + /** + *

        Retrieve only scores with this userId associated to the trace.

        + */ @JsonSetter( value = "userId", nulls = Nulls.SKIP @@ -394,6 +477,9 @@ public Builder userId(String userId) { return this; } + /** + *

        Retrieve only scores with this name.

        + */ @JsonSetter( value = "name", nulls = Nulls.SKIP @@ -408,6 +494,9 @@ public Builder name(String name) { return this; } + /** + *

        Optional filter to only include scores created on or after a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "fromTimestamp", nulls = Nulls.SKIP @@ -422,6 +511,9 @@ public Builder fromTimestamp(OffsetDateTime fromTimestamp) { return this; } + /** + *

        Optional filter to only include scores created before a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "toTimestamp", nulls = Nulls.SKIP @@ -436,20 +528,9 @@ public Builder toTimestamp(OffsetDateTime toTimestamp) { return this; } - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public Builder environment(Optional environment) { - this.environment = environment; - return this; - } - - public Builder environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - + /** + *

        Retrieve only scores from a specific source.

        + */ @JsonSetter( value = "source", nulls = Nulls.SKIP @@ -464,6 +545,9 @@ public Builder source(ScoreSource source) { return this; } + /** + *

        Retrieve only scores with <operator> value.

        + */ @JsonSetter( value = "operator", nulls = Nulls.SKIP @@ -478,6 +562,9 @@ public Builder operator(String operator) { return this; } + /** + *

        Retrieve only scores with <operator> value.

        + */ @JsonSetter( value = "value", nulls = Nulls.SKIP @@ -492,6 +579,9 @@ public Builder value(Double value) { return this; } + /** + *

        Comma-separated list of score IDs to limit the results to.

        + */ @JsonSetter( value = "scoreIds", nulls = Nulls.SKIP @@ -506,6 +596,9 @@ public Builder scoreIds(String scoreIds) { return this; } + /** + *

        Retrieve only scores with a specific configId.

        + */ @JsonSetter( value = "configId", nulls = Nulls.SKIP @@ -520,6 +613,9 @@ public Builder configId(String configId) { return this; } + /** + *

        Retrieve only scores with a specific sessionId.

        + */ @JsonSetter( value = "sessionId", nulls = Nulls.SKIP @@ -534,6 +630,9 @@ public Builder sessionId(String sessionId) { return this; } + /** + *

        Retrieve only scores with a specific datasetRunId.

        + */ @JsonSetter( value = "datasetRunId", nulls = Nulls.SKIP @@ -548,6 +647,9 @@ public Builder datasetRunId(String datasetRunId) { return this; } + /** + *

        Retrieve only scores with a specific traceId.

        + */ @JsonSetter( value = "traceId", nulls = Nulls.SKIP @@ -562,6 +664,26 @@ public Builder traceId(String traceId) { return this; } + /** + *

        Comma-separated list of observation IDs to filter scores by.

        + */ + @JsonSetter( + value = "observationId", + nulls = Nulls.SKIP + ) + public Builder observationId(Optional observationId) { + this.observationId = observationId; + return this; + } + + public Builder observationId(String observationId) { + this.observationId = Optional.ofNullable(observationId); + return this; + } + + /** + *

        Retrieve only scores with a specific annotation queueId.

        + */ @JsonSetter( value = "queueId", nulls = Nulls.SKIP @@ -576,6 +698,9 @@ public Builder queueId(String queueId) { return this; } + /** + *

        Retrieve only scores with a specific dataType.

        + */ @JsonSetter( value = "dataType", nulls = Nulls.SKIP @@ -590,36 +715,52 @@ public Builder dataType(ScoreDataType dataType) { return this; } + /** + *

        Comma-separated list of field groups to include in the response. Available field groups: 'score' (core score fields), 'trace' (trace properties: userId, tags, environment). If not specified, both 'score' and 'trace' are returned by default. Example: 'score' to exclude trace data, 'score,trace' to include both. Note: When filtering by trace properties (using userId or traceTags parameters), the 'trace' field group must be included, otherwise a 400 error will be returned.

        + */ @JsonSetter( - value = "traceTags", + value = "fields", nulls = Nulls.SKIP ) - public Builder traceTags(Optional traceTags) { - this.traceTags = traceTags; + public Builder fields(Optional fields) { + this.fields = fields; return this; } - public Builder traceTags(String traceTags) { - this.traceTags = Optional.ofNullable(traceTags); + public Builder fields(String fields) { + this.fields = Optional.ofNullable(fields); return this; } + /** + *

        A JSON stringified array of filter objects. Each object requires type, column, operator, and value. Supports filtering by score metadata using the stringObject type. Example: [{"type":"stringObject","column":"metadata","key":"user_id","operator":"=","value":"abc123"}]. Supported types: stringObject (metadata key-value filtering), string, number, datetime, stringOptions, arrayOptions. Supported operators for stringObject: =, contains, does not contain, starts with, ends with.

        + */ @JsonSetter( - value = "fields", + value = "filter", nulls = Nulls.SKIP ) - public Builder fields(Optional fields) { - this.fields = fields; + public Builder filter(Optional filter) { + this.filter = filter; return this; } - public Builder fields(String fields) { - this.fields = Optional.ofNullable(fields); + public Builder filter(String filter) { + this.filter = Optional.ofNullable(filter); return this; } public GetScoresRequest build() { - return new GetScoresRequest(page, limit, userId, name, fromTimestamp, toTimestamp, environment, source, operator, value, scoreIds, configId, sessionId, datasetRunId, traceId, queueId, dataType, traceTags, fields, additionalProperties); + return new GetScoresRequest(environment, traceTags, page, limit, userId, name, fromTimestamp, toTimestamp, source, operator, value, scoreIds, configId, sessionId, datasetRunId, traceId, observationId, queueId, dataType, fields, filter, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponse.java b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponse.java index e35b1fa..8fc0613 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponse.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponse.java @@ -89,6 +89,10 @@ public interface MetaStage { public interface _FinalStage { GetScoresResponse build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(GetScoresResponseData data); @@ -126,7 +130,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -143,7 +149,9 @@ public _FinalStage addData(GetScoresResponseData data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -151,5 +159,17 @@ public _FinalStage data(List data) { public GetScoresResponse build() { return new GetScoresResponse(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseData.java b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseData.java index b245504..bc41e5c 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseData.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseData.java @@ -43,6 +43,10 @@ public static GetScoresResponseData boolean_(GetScoresResponseDataBoolean value) return new GetScoresResponseData(new BooleanValue(value)); } + public static GetScoresResponseData correction(GetScoresResponseDataCorrection value) { + return new GetScoresResponseData(new CorrectionValue(value)); + } + public boolean isNumeric() { return value instanceof NumericValue; } @@ -55,6 +59,10 @@ public boolean isBoolean() { return value instanceof BooleanValue; } + public boolean isCorrection() { + return value instanceof CorrectionValue; + } + public boolean _isUnknown() { return value instanceof _UnknownValue; } @@ -80,6 +88,13 @@ public Optional getBoolean() { return Optional.empty(); } + public Optional getCorrection() { + if (isCorrection()) { + return Optional.of(((CorrectionValue) value).value); + } + return Optional.empty(); + } + public Optional _getUnknown() { if (_isUnknown()) { return Optional.of(((_UnknownValue) value).value); @@ -99,6 +114,8 @@ public interface Visitor { T visitBoolean(GetScoresResponseDataBoolean boolean_); + T visitCorrection(GetScoresResponseDataCorrection correction); + T _visitUnknown(Object unknownType); } @@ -111,7 +128,8 @@ public interface Visitor { @JsonSubTypes({ @JsonSubTypes.Type(NumericValue.class), @JsonSubTypes.Type(CategoricalValue.class), - @JsonSubTypes.Type(BooleanValue.class) + @JsonSubTypes.Type(BooleanValue.class), + @JsonSubTypes.Type(CorrectionValue.class) }) @JsonIgnoreProperties( ignoreUnknown = true @@ -246,6 +264,48 @@ public String toString() { } } + @JsonTypeName("CORRECTION") + @JsonIgnoreProperties("dataType") + private static final class CorrectionValue implements Value { + @JsonUnwrapped + private GetScoresResponseDataCorrection value; + + @JsonCreator( + mode = JsonCreator.Mode.PROPERTIES + ) + private CorrectionValue() { + } + + private CorrectionValue(GetScoresResponseDataCorrection value) { + this.value = value; + } + + @java.lang.Override + public T visit(Visitor visitor) { + return visitor.visitCorrection(value); + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CorrectionValue && equalTo((CorrectionValue) other); + } + + private boolean equalTo(CorrectionValue other) { + return value.equals(other.value); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value); + } + + @java.lang.Override + public String toString() { + return "GetScoresResponseData{" + "value: " + value + "}"; + } + } + @JsonIgnoreProperties("dataType") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataBoolean.java b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataBoolean.java index 6f0e365..69ae823 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataBoolean.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataBoolean.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -58,13 +61,13 @@ public final class GetScoresResponseDataBoolean implements IBooleanScore, IBaseS private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Optional trace; @@ -74,9 +77,9 @@ private GetScoresResponseDataBoolean(double value, String stringValue, String id Optional traceId, Optional sessionId, Optional observationId, Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, - Optional comment, Optional metadata, Optional configId, - Optional queueId, Optional environment, - Optional trace, Map additionalProperties) { + Optional comment, Object metadata, Optional configId, + Optional queueId, String environment, Optional trace, + Map additionalProperties) { this.value = value; this.stringValue = stringValue; this.id = id; @@ -123,27 +126,51 @@ public String getId() { return id; } - @JsonProperty("traceId") + /** + * @return The trace ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } - @JsonProperty("sessionId") + /** + * @return The session ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } - @JsonProperty("datasetRunId") + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } return datasetRunId; } @@ -177,39 +204,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -218,7 +266,7 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -227,6 +275,78 @@ public Optional getTrace() { return trace; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -257,12 +377,18 @@ public static ValueStage builder() { } public interface ValueStage { + /** + *

        The numeric value of the score. Equals 1 for "True" and 0 for "False"

        + */ StringValueStage value(double value); Builder from(GetScoresResponseDataBoolean other); } public interface StringValueStage { + /** + *

        The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

        + */ IdStage stringValue(@NotNull String stringValue); } @@ -287,51 +413,101 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

        Metadata associated with the score

        + */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { GetScoresResponseDataBoolean build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The trace ID associated with the score

        + */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

        The session ID associated with the score

        + */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

        The observation ID associated with the score

        + */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

        The dataset run ID associated with the score

        + */ _FinalStage datasetRunId(Optional datasetRunId); _FinalStage datasetRunId(String datasetRunId); + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

        The user ID of the author

        + */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

        Comment on the score

        + */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); _FinalStage trace(Optional trace); @@ -341,7 +517,7 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private double value; private String stringValue; @@ -358,16 +534,16 @@ public static final class Builder implements ValueStage, StringValueStage, IdSta private OffsetDateTime updatedAt; - private Optional trace = Optional.empty(); + private Object metadata; - private Optional environment = Optional.empty(); + private String environment; + + private Optional trace = Optional.empty(); private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -411,6 +587,7 @@ public Builder from(GetScoresResponseDataBoolean other) { } /** + *

        The numeric value of the score. Equals 1 for "True" and 0 for "False"

        *

        The numeric value of the score. Equals 1 for "True" and 0 for "False"

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -422,6 +599,7 @@ public StringValueStage value(double value) { } /** + *

        The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

        *

        The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -469,11 +647,35 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } + /** + *

        Metadata associated with the score

        + *

        Metadata associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + @java.lang.Override public _FinalStage trace(GetScoresResponseTraceData trace) { this.trace = Optional.ofNullable(trace); @@ -491,22 +693,20 @@ public _FinalStage trace(Optional trace) { } /** - *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -520,6 +720,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ @java.lang.Override @JsonSetter( value = "queueId", @@ -530,6 +733,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        * @return Reference to {@code this} so that method calls can be chained together. @@ -540,6 +761,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ @java.lang.Override @JsonSetter( value = "configId", @@ -550,28 +774,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

        Comment on the score

        + */ @java.lang.Override @JsonSetter( value = "comment", @@ -582,12 +815,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

        The user ID of the author

        + */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -598,12 +856,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage datasetRunId(String datasetRunId) { this.datasetRunId = Optional.ofNullable(datasetRunId); return this; } + /** + *

        The dataset run ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "datasetRunId", @@ -614,12 +897,37 @@ public _FinalStage datasetRunId(Optional datasetRunId) { return this; } + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

        The observation ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "observationId", @@ -630,12 +938,37 @@ public _FinalStage observationId(Optional observationId) { return this; } + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sessionId(String sessionId) { this.sessionId = Optional.ofNullable(sessionId); return this; } + /** + *

        The session ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -646,12 +979,37 @@ public _FinalStage sessionId(Optional sessionId) { return this; } + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage traceId(String traceId) { this.traceId = Optional.ofNullable(traceId); return this; } + /** + *

        The trace ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "traceId", @@ -666,5 +1024,17 @@ public _FinalStage traceId(Optional traceId) { public GetScoresResponseDataBoolean build() { return new GetScoresResponseDataBoolean(value, stringValue, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, trace, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataCategorical.java b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataCategorical.java index 56574f9..ea0b83a 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataCategorical.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataCategorical.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -58,13 +61,13 @@ public final class GetScoresResponseDataCategorical implements ICategoricalScore private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Optional trace; @@ -74,9 +77,9 @@ private GetScoresResponseDataCategorical(double value, String stringValue, Strin Optional traceId, Optional sessionId, Optional observationId, Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, - Optional comment, Optional metadata, Optional configId, - Optional queueId, Optional environment, - Optional trace, Map additionalProperties) { + Optional comment, Object metadata, Optional configId, + Optional queueId, String environment, Optional trace, + Map additionalProperties) { this.value = value; this.stringValue = stringValue; this.id = id; @@ -123,27 +126,51 @@ public String getId() { return id; } - @JsonProperty("traceId") + /** + * @return The trace ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } - @JsonProperty("sessionId") + /** + * @return The session ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } - @JsonProperty("datasetRunId") + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } return datasetRunId; } @@ -177,39 +204,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -218,7 +266,7 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -227,6 +275,78 @@ public Optional getTrace() { return trace; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -257,12 +377,18 @@ public static ValueStage builder() { } public interface ValueStage { + /** + *

        Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

        + */ StringValueStage value(double value); Builder from(GetScoresResponseDataCategorical other); } public interface StringValueStage { + /** + *

        The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

        + */ IdStage stringValue(@NotNull String stringValue); } @@ -287,51 +413,101 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

        Metadata associated with the score

        + */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { GetScoresResponseDataCategorical build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The trace ID associated with the score

        + */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

        The session ID associated with the score

        + */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

        The observation ID associated with the score

        + */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

        The dataset run ID associated with the score

        + */ _FinalStage datasetRunId(Optional datasetRunId); _FinalStage datasetRunId(String datasetRunId); + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

        The user ID of the author

        + */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

        Comment on the score

        + */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); _FinalStage trace(Optional trace); @@ -341,7 +517,7 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private double value; private String stringValue; @@ -358,16 +534,16 @@ public static final class Builder implements ValueStage, StringValueStage, IdSta private OffsetDateTime updatedAt; - private Optional trace = Optional.empty(); + private Object metadata; - private Optional environment = Optional.empty(); + private String environment; + + private Optional trace = Optional.empty(); private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -411,6 +587,7 @@ public Builder from(GetScoresResponseDataCategorical other) { } /** + *

        Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

        *

        Represents the numeric category mapping of the stringValue. If no config is linked, defaults to 0.

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -422,6 +599,7 @@ public StringValueStage value(double value) { } /** + *

        The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

        *

        The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -469,11 +647,35 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } + /** + *

        Metadata associated with the score

        + *

        Metadata associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + @java.lang.Override public _FinalStage trace(GetScoresResponseTraceData trace) { this.trace = Optional.ofNullable(trace); @@ -491,22 +693,20 @@ public _FinalStage trace(Optional trace) { } /** - *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -520,6 +720,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ @java.lang.Override @JsonSetter( value = "queueId", @@ -530,6 +733,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        * @return Reference to {@code this} so that method calls can be chained together. @@ -540,6 +761,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ @java.lang.Override @JsonSetter( value = "configId", @@ -550,28 +774,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

        Comment on the score

        + */ @java.lang.Override @JsonSetter( value = "comment", @@ -582,12 +815,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

        The user ID of the author

        + */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -598,12 +856,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage datasetRunId(String datasetRunId) { this.datasetRunId = Optional.ofNullable(datasetRunId); return this; } + /** + *

        The dataset run ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "datasetRunId", @@ -614,12 +897,37 @@ public _FinalStage datasetRunId(Optional datasetRunId) { return this; } + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

        The observation ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "observationId", @@ -630,12 +938,37 @@ public _FinalStage observationId(Optional observationId) { return this; } + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sessionId(String sessionId) { this.sessionId = Optional.ofNullable(sessionId); return this; } + /** + *

        The session ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -646,12 +979,37 @@ public _FinalStage sessionId(Optional sessionId) { return this; } + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage traceId(String traceId) { this.traceId = Optional.ofNullable(traceId); return this; } + /** + *

        The trace ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "traceId", @@ -666,5 +1024,17 @@ public _FinalStage traceId(Optional traceId) { public GetScoresResponseDataCategorical build() { return new GetScoresResponseDataCategorical(value, stringValue, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, trace, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataCorrection.java b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataCorrection.java new file mode 100644 index 0000000..b3cf42b --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataCorrection.java @@ -0,0 +1,1040 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.scorev2.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; +import com.langfuse.client.core.ObjectMappers; +import java.lang.Object; +import java.lang.String; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.types.IBaseScore; +import com.langfuse.client.resources.commons.types.ICorrectionScore; +import com.langfuse.client.resources.commons.types.ScoreSource; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize( + builder = GetScoresResponseDataCorrection.Builder.class +) +public final class GetScoresResponseDataCorrection implements ICorrectionScore, IBaseScore { + private final double value; + + private final String stringValue; + + private final String id; + + private final Optional traceId; + + private final Optional sessionId; + + private final Optional observationId; + + private final Optional datasetRunId; + + private final String name; + + private final ScoreSource source; + + private final OffsetDateTime timestamp; + + private final OffsetDateTime createdAt; + + private final OffsetDateTime updatedAt; + + private final Optional authorUserId; + + private final Optional comment; + + private final Object metadata; + + private final Optional configId; + + private final Optional queueId; + + private final String environment; + + private final Optional trace; + + private final Map additionalProperties; + + private GetScoresResponseDataCorrection(double value, String stringValue, String id, + Optional traceId, Optional sessionId, Optional observationId, + Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, + OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, + Optional comment, Object metadata, Optional configId, + Optional queueId, String environment, Optional trace, + Map additionalProperties) { + this.value = value; + this.stringValue = stringValue; + this.id = id; + this.traceId = traceId; + this.sessionId = sessionId; + this.observationId = observationId; + this.datasetRunId = datasetRunId; + this.name = name; + this.source = source; + this.timestamp = timestamp; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.authorUserId = authorUserId; + this.comment = comment; + this.metadata = metadata; + this.configId = configId; + this.queueId = queueId; + this.environment = environment; + this.trace = trace; + this.additionalProperties = additionalProperties; + } + + /** + * @return The numeric value of the score. Always 0 for correction scores. + */ + @JsonProperty("value") + @java.lang.Override + public double getValue() { + return value; + } + + /** + * @return The string representation of the correction content + */ + @JsonProperty("stringValue") + @java.lang.Override + public String getStringValue() { + return stringValue; + } + + @JsonProperty("id") + @java.lang.Override + public String getId() { + return id; + } + + /** + * @return The trace ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } + return traceId; + } + + /** + * @return The session ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } + return sessionId; + } + + /** + * @return The observation ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } + return observationId; + } + + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore + @java.lang.Override + public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } + return datasetRunId; + } + + @JsonProperty("name") + @java.lang.Override + public String getName() { + return name; + } + + @JsonProperty("source") + @java.lang.Override + public ScoreSource getSource() { + return source; + } + + @JsonProperty("timestamp") + @java.lang.Override + public OffsetDateTime getTimestamp() { + return timestamp; + } + + @JsonProperty("createdAt") + @java.lang.Override + public OffsetDateTime getCreatedAt() { + return createdAt; + } + + @JsonProperty("updatedAt") + @java.lang.Override + public OffsetDateTime getUpdatedAt() { + return updatedAt; + } + + /** + * @return The user ID of the author + */ + @JsonIgnore + @java.lang.Override + public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } + return authorUserId; + } + + /** + * @return Comment on the score + */ + @JsonIgnore + @java.lang.Override + public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } + return comment; + } + + /** + * @return Metadata associated with the score + */ + @JsonProperty("metadata") + @java.lang.Override + public Object getMetadata() { + return metadata; + } + + /** + * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range + */ + @JsonIgnore + @java.lang.Override + public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } + return configId; + } + + /** + * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. + */ + @JsonIgnore + @java.lang.Override + public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } + return queueId; + } + + /** + * @return The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'. + */ + @JsonProperty("environment") + @java.lang.Override + public String getEnvironment() { + return environment; + } + + @JsonProperty("trace") + public Optional getTrace() { + return trace; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetScoresResponseDataCorrection && equalTo((GetScoresResponseDataCorrection) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetScoresResponseDataCorrection other) { + return value == other.value && stringValue.equals(other.stringValue) && id.equals(other.id) && traceId.equals(other.traceId) && sessionId.equals(other.sessionId) && observationId.equals(other.observationId) && datasetRunId.equals(other.datasetRunId) && name.equals(other.name) && source.equals(other.source) && timestamp.equals(other.timestamp) && createdAt.equals(other.createdAt) && updatedAt.equals(other.updatedAt) && authorUserId.equals(other.authorUserId) && comment.equals(other.comment) && metadata.equals(other.metadata) && configId.equals(other.configId) && queueId.equals(other.queueId) && environment.equals(other.environment) && trace.equals(other.trace); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value, this.stringValue, this.id, this.traceId, this.sessionId, this.observationId, this.datasetRunId, this.name, this.source, this.timestamp, this.createdAt, this.updatedAt, this.authorUserId, this.comment, this.metadata, this.configId, this.queueId, this.environment, this.trace); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ValueStage builder() { + return new Builder(); + } + + public interface ValueStage { + /** + *

        The numeric value of the score. Always 0 for correction scores.

        + */ + StringValueStage value(double value); + + Builder from(GetScoresResponseDataCorrection other); + } + + public interface StringValueStage { + /** + *

        The string representation of the correction content

        + */ + IdStage stringValue(@NotNull String stringValue); + } + + public interface IdStage { + NameStage id(@NotNull String id); + } + + public interface NameStage { + SourceStage name(@NotNull String name); + } + + public interface SourceStage { + TimestampStage source(@NotNull ScoreSource source); + } + + public interface TimestampStage { + CreatedAtStage timestamp(@NotNull OffsetDateTime timestamp); + } + + public interface CreatedAtStage { + UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt); + } + + public interface UpdatedAtStage { + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

        Metadata associated with the score

        + */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ + _FinalStage environment(@NotNull String environment); + } + + public interface _FinalStage { + GetScoresResponseDataCorrection build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The trace ID associated with the score

        + */ + _FinalStage traceId(Optional traceId); + + _FinalStage traceId(String traceId); + + _FinalStage traceId(Nullable traceId); + + /** + *

        The session ID associated with the score

        + */ + _FinalStage sessionId(Optional sessionId); + + _FinalStage sessionId(String sessionId); + + _FinalStage sessionId(Nullable sessionId); + + /** + *

        The observation ID associated with the score

        + */ + _FinalStage observationId(Optional observationId); + + _FinalStage observationId(String observationId); + + _FinalStage observationId(Nullable observationId); + + /** + *

        The dataset run ID associated with the score

        + */ + _FinalStage datasetRunId(Optional datasetRunId); + + _FinalStage datasetRunId(String datasetRunId); + + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

        The user ID of the author

        + */ + _FinalStage authorUserId(Optional authorUserId); + + _FinalStage authorUserId(String authorUserId); + + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

        Comment on the score

        + */ + _FinalStage comment(Optional comment); + + _FinalStage comment(String comment); + + _FinalStage comment(Nullable comment); + + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ + _FinalStage configId(Optional configId); + + _FinalStage configId(String configId); + + _FinalStage configId(Nullable configId); + + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ + _FinalStage queueId(Optional queueId); + + _FinalStage queueId(String queueId); + + _FinalStage queueId(Nullable queueId); + + _FinalStage trace(Optional trace); + + _FinalStage trace(GetScoresResponseTraceData trace); + } + + @JsonIgnoreProperties( + ignoreUnknown = true + ) + public static final class Builder implements ValueStage, StringValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { + private double value; + + private String stringValue; + + private String id; + + private String name; + + private ScoreSource source; + + private OffsetDateTime timestamp; + + private OffsetDateTime createdAt; + + private OffsetDateTime updatedAt; + + private Object metadata; + + private String environment; + + private Optional trace = Optional.empty(); + + private Optional queueId = Optional.empty(); + + private Optional configId = Optional.empty(); + + private Optional comment = Optional.empty(); + + private Optional authorUserId = Optional.empty(); + + private Optional datasetRunId = Optional.empty(); + + private Optional observationId = Optional.empty(); + + private Optional sessionId = Optional.empty(); + + private Optional traceId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() { + } + + @java.lang.Override + public Builder from(GetScoresResponseDataCorrection other) { + value(other.getValue()); + stringValue(other.getStringValue()); + id(other.getId()); + traceId(other.getTraceId()); + sessionId(other.getSessionId()); + observationId(other.getObservationId()); + datasetRunId(other.getDatasetRunId()); + name(other.getName()); + source(other.getSource()); + timestamp(other.getTimestamp()); + createdAt(other.getCreatedAt()); + updatedAt(other.getUpdatedAt()); + authorUserId(other.getAuthorUserId()); + comment(other.getComment()); + metadata(other.getMetadata()); + configId(other.getConfigId()); + queueId(other.getQueueId()); + environment(other.getEnvironment()); + trace(other.getTrace()); + return this; + } + + /** + *

        The numeric value of the score. Always 0 for correction scores.

        + *

        The numeric value of the score. Always 0 for correction scores.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("value") + public StringValueStage value(double value) { + this.value = value; + return this; + } + + /** + *

        The string representation of the correction content

        + *

        The string representation of the correction content

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("stringValue") + public IdStage stringValue(@NotNull String stringValue) { + this.stringValue = Objects.requireNonNull(stringValue, "stringValue must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("id") + public NameStage id(@NotNull String id) { + this.id = Objects.requireNonNull(id, "id must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("name") + public SourceStage name(@NotNull String name) { + this.name = Objects.requireNonNull(name, "name must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("source") + public TimestampStage source(@NotNull ScoreSource source) { + this.source = Objects.requireNonNull(source, "source must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("timestamp") + public CreatedAtStage timestamp(@NotNull OffsetDateTime timestamp) { + this.timestamp = Objects.requireNonNull(timestamp, "timestamp must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("createdAt") + public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { + this.createdAt = Objects.requireNonNull(createdAt, "createdAt must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("updatedAt") + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { + this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); + return this; + } + + /** + *

        Metadata associated with the score

        + *

        Metadata associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage trace(GetScoresResponseTraceData trace) { + this.trace = Optional.ofNullable(trace); + return this; + } + + @java.lang.Override + @JsonSetter( + value = "trace", + nulls = Nulls.SKIP + ) + public _FinalStage trace(Optional trace) { + this.trace = trace; + return this; + } + + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } + return this; + } + + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage queueId(String queueId) { + this.queueId = Optional.ofNullable(queueId); + return this; + } + + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ + @java.lang.Override + @JsonSetter( + value = "queueId", + nulls = Nulls.SKIP + ) + public _FinalStage queueId(Optional queueId) { + this.queueId = queueId; + return this; + } + + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(String configId) { + this.configId = Optional.ofNullable(configId); + return this; + } + + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ + @java.lang.Override + @JsonSetter( + value = "configId", + nulls = Nulls.SKIP + ) + public _FinalStage configId(Optional configId) { + this.configId = configId; + return this; + } + + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } + return this; + } + + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage comment(String comment) { + this.comment = Optional.ofNullable(comment); + return this; + } + + /** + *

        Comment on the score

        + */ + @java.lang.Override + @JsonSetter( + value = "comment", + nulls = Nulls.SKIP + ) + public _FinalStage comment(Optional comment) { + this.comment = comment; + return this; + } + + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(String authorUserId) { + this.authorUserId = Optional.ofNullable(authorUserId); + return this; + } + + /** + *

        The user ID of the author

        + */ + @java.lang.Override + @JsonSetter( + value = "authorUserId", + nulls = Nulls.SKIP + ) + public _FinalStage authorUserId(Optional authorUserId) { + this.authorUserId = authorUserId; + return this; + } + + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(String datasetRunId) { + this.datasetRunId = Optional.ofNullable(datasetRunId); + return this; + } + + /** + *

        The dataset run ID associated with the score

        + */ + @java.lang.Override + @JsonSetter( + value = "datasetRunId", + nulls = Nulls.SKIP + ) + public _FinalStage datasetRunId(Optional datasetRunId) { + this.datasetRunId = datasetRunId; + return this; + } + + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(String observationId) { + this.observationId = Optional.ofNullable(observationId); + return this; + } + + /** + *

        The observation ID associated with the score

        + */ + @java.lang.Override + @JsonSetter( + value = "observationId", + nulls = Nulls.SKIP + ) + public _FinalStage observationId(Optional observationId) { + this.observationId = observationId; + return this; + } + + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(String sessionId) { + this.sessionId = Optional.ofNullable(sessionId); + return this; + } + + /** + *

        The session ID associated with the score

        + */ + @java.lang.Override + @JsonSetter( + value = "sessionId", + nulls = Nulls.SKIP + ) + public _FinalStage sessionId(Optional sessionId) { + this.sessionId = sessionId; + return this; + } + + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(String traceId) { + this.traceId = Optional.ofNullable(traceId); + return this; + } + + /** + *

        The trace ID associated with the score

        + */ + @java.lang.Override + @JsonSetter( + value = "traceId", + nulls = Nulls.SKIP + ) + public _FinalStage traceId(Optional traceId) { + this.traceId = traceId; + return this; + } + + @java.lang.Override + public GetScoresResponseDataCorrection build() { + return new GetScoresResponseDataCorrection(value, stringValue, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, trace, additionalProperties); + } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } + } +} diff --git a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataNumeric.java b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataNumeric.java index 9f26c32..d947598 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataNumeric.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseDataNumeric.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.langfuse.client.core.Nullable; +import com.langfuse.client.core.NullableNonemptyFilter; import com.langfuse.client.core.ObjectMappers; import java.lang.Object; import java.lang.String; @@ -56,13 +59,13 @@ public final class GetScoresResponseDataNumeric implements INumericScore, IBaseS private final Optional comment; - private final Optional metadata; + private final Object metadata; private final Optional configId; private final Optional queueId; - private final Optional environment; + private final String environment; private final Optional trace; @@ -72,9 +75,8 @@ private GetScoresResponseDataNumeric(double value, String id, Optional t Optional sessionId, Optional observationId, Optional datasetRunId, String name, ScoreSource source, OffsetDateTime timestamp, OffsetDateTime createdAt, OffsetDateTime updatedAt, Optional authorUserId, Optional comment, - Optional metadata, Optional configId, Optional queueId, - Optional environment, Optional trace, - Map additionalProperties) { + Object metadata, Optional configId, Optional queueId, String environment, + Optional trace, Map additionalProperties) { this.value = value; this.id = id; this.traceId = traceId; @@ -111,27 +113,51 @@ public String getId() { return id; } - @JsonProperty("traceId") + /** + * @return The trace ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getTraceId() { + if (traceId == null) { + return Optional.empty(); + } return traceId; } - @JsonProperty("sessionId") + /** + * @return The session ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getSessionId() { + if (sessionId == null) { + return Optional.empty(); + } return sessionId; } - @JsonProperty("observationId") + /** + * @return The observation ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getObservationId() { + if (observationId == null) { + return Optional.empty(); + } return observationId; } - @JsonProperty("datasetRunId") + /** + * @return The dataset run ID associated with the score + */ + @JsonIgnore @java.lang.Override public Optional getDatasetRunId() { + if (datasetRunId == null) { + return Optional.empty(); + } return datasetRunId; } @@ -165,39 +191,60 @@ public OffsetDateTime getUpdatedAt() { return updatedAt; } - @JsonProperty("authorUserId") + /** + * @return The user ID of the author + */ + @JsonIgnore @java.lang.Override public Optional getAuthorUserId() { + if (authorUserId == null) { + return Optional.empty(); + } return authorUserId; } - @JsonProperty("comment") + /** + * @return Comment on the score + */ + @JsonIgnore @java.lang.Override public Optional getComment() { + if (comment == null) { + return Optional.empty(); + } return comment; } + /** + * @return Metadata associated with the score + */ @JsonProperty("metadata") @java.lang.Override - public Optional getMetadata() { + public Object getMetadata() { return metadata; } /** * @return Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range */ - @JsonProperty("configId") + @JsonIgnore @java.lang.Override public Optional getConfigId() { + if (configId == null) { + return Optional.empty(); + } return configId; } /** * @return The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue. */ - @JsonProperty("queueId") + @JsonIgnore @java.lang.Override public Optional getQueueId() { + if (queueId == null) { + return Optional.empty(); + } return queueId; } @@ -206,7 +253,7 @@ public Optional getQueueId() { */ @JsonProperty("environment") @java.lang.Override - public Optional getEnvironment() { + public String getEnvironment() { return environment; } @@ -215,6 +262,78 @@ public Optional getTrace() { return trace; } + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("traceId") + private Optional _getTraceId() { + return traceId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("sessionId") + private Optional _getSessionId() { + return sessionId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("observationId") + private Optional _getObservationId() { + return observationId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("datasetRunId") + private Optional _getDatasetRunId() { + return datasetRunId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("authorUserId") + private Optional _getAuthorUserId() { + return authorUserId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("comment") + private Optional _getComment() { + return comment; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("configId") + private Optional _getConfigId() { + return configId; + } + + @JsonInclude( + value = JsonInclude.Include.CUSTOM, + valueFilter = NullableNonemptyFilter.class + ) + @JsonProperty("queueId") + private Optional _getQueueId() { + return queueId; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -245,6 +364,9 @@ public static ValueStage builder() { } public interface ValueStage { + /** + *

        The numeric value of the score

        + */ IdStage value(double value); Builder from(GetScoresResponseDataNumeric other); @@ -271,51 +393,101 @@ public interface CreatedAtStage { } public interface UpdatedAtStage { - _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); + MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt); + } + + public interface MetadataStage { + /** + *

        Metadata associated with the score

        + */ + EnvironmentStage metadata(Object metadata); + } + + public interface EnvironmentStage { + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + */ + _FinalStage environment(@NotNull String environment); } public interface _FinalStage { GetScoresResponseDataNumeric build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + + /** + *

        The trace ID associated with the score

        + */ _FinalStage traceId(Optional traceId); _FinalStage traceId(String traceId); + _FinalStage traceId(Nullable traceId); + + /** + *

        The session ID associated with the score

        + */ _FinalStage sessionId(Optional sessionId); _FinalStage sessionId(String sessionId); + _FinalStage sessionId(Nullable sessionId); + + /** + *

        The observation ID associated with the score

        + */ _FinalStage observationId(Optional observationId); _FinalStage observationId(String observationId); + _FinalStage observationId(Nullable observationId); + + /** + *

        The dataset run ID associated with the score

        + */ _FinalStage datasetRunId(Optional datasetRunId); _FinalStage datasetRunId(String datasetRunId); + _FinalStage datasetRunId(Nullable datasetRunId); + + /** + *

        The user ID of the author

        + */ _FinalStage authorUserId(Optional authorUserId); _FinalStage authorUserId(String authorUserId); + _FinalStage authorUserId(Nullable authorUserId); + + /** + *

        Comment on the score

        + */ _FinalStage comment(Optional comment); _FinalStage comment(String comment); - _FinalStage metadata(Optional metadata); - - _FinalStage metadata(Object metadata); + _FinalStage comment(Nullable comment); + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ _FinalStage configId(Optional configId); _FinalStage configId(String configId); + _FinalStage configId(Nullable configId); + + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ _FinalStage queueId(Optional queueId); _FinalStage queueId(String queueId); - _FinalStage environment(Optional environment); - - _FinalStage environment(String environment); + _FinalStage queueId(Nullable queueId); _FinalStage trace(Optional trace); @@ -325,7 +497,7 @@ public interface _FinalStage { @JsonIgnoreProperties( ignoreUnknown = true ) - public static final class Builder implements ValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, _FinalStage { + public static final class Builder implements ValueStage, IdStage, NameStage, SourceStage, TimestampStage, CreatedAtStage, UpdatedAtStage, MetadataStage, EnvironmentStage, _FinalStage { private double value; private String id; @@ -340,16 +512,16 @@ public static final class Builder implements ValueStage, IdStage, NameStage, Sou private OffsetDateTime updatedAt; - private Optional trace = Optional.empty(); + private Object metadata; - private Optional environment = Optional.empty(); + private String environment; + + private Optional trace = Optional.empty(); private Optional queueId = Optional.empty(); private Optional configId = Optional.empty(); - private Optional metadata = Optional.empty(); - private Optional comment = Optional.empty(); private Optional authorUserId = Optional.empty(); @@ -392,6 +564,7 @@ public Builder from(GetScoresResponseDataNumeric other) { } /** + *

        The numeric value of the score

        *

        The numeric value of the score

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -439,11 +612,35 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { @java.lang.Override @JsonSetter("updatedAt") - public _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt) { + public MetadataStage updatedAt(@NotNull OffsetDateTime updatedAt) { this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt must not be null"); return this; } + /** + *

        Metadata associated with the score

        + *

        Metadata associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("metadata") + public EnvironmentStage metadata(Object metadata) { + this.metadata = metadata; + return this; + } + + /** + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("environment") + public _FinalStage environment(@NotNull String environment) { + this.environment = Objects.requireNonNull(environment, "environment must not be null"); + return this; + } + @java.lang.Override public _FinalStage trace(GetScoresResponseTraceData trace) { this.trace = Optional.ofNullable(trace); @@ -461,22 +658,20 @@ public _FinalStage trace(Optional trace) { } /** - *

        The environment from which this score originated. Can be any lowercase alphanumeric string with hyphens and underscores that does not start with 'langfuse'.

        + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public _FinalStage environment(Optional environment) { - this.environment = environment; + public _FinalStage queueId(Nullable queueId) { + if (queueId.isNull()) { + this.queueId = null; + } + else if (queueId.isEmpty()) { + this.queueId = Optional.empty(); + } + else { + this.queueId = Optional.of(queueId.get()); + } return this; } @@ -490,6 +685,9 @@ public _FinalStage queueId(String queueId) { return this; } + /** + *

        The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.

        + */ @java.lang.Override @JsonSetter( value = "queueId", @@ -500,6 +698,24 @@ public _FinalStage queueId(Optional queueId) { return this; } + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage configId(Nullable configId) { + if (configId.isNull()) { + this.configId = null; + } + else if (configId.isEmpty()) { + this.configId = Optional.empty(); + } + else { + this.configId = Optional.of(configId.get()); + } + return this; + } + /** *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        * @return Reference to {@code this} so that method calls can be chained together. @@ -510,6 +726,9 @@ public _FinalStage configId(String configId) { return this; } + /** + *

        Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range

        + */ @java.lang.Override @JsonSetter( value = "configId", @@ -520,28 +739,37 @@ public _FinalStage configId(Optional configId) { return this; } + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override - public _FinalStage metadata(Object metadata) { - this.metadata = Optional.ofNullable(metadata); - return this; - } - - @java.lang.Override - @JsonSetter( - value = "metadata", - nulls = Nulls.SKIP - ) - public _FinalStage metadata(Optional metadata) { - this.metadata = metadata; + public _FinalStage comment(Nullable comment) { + if (comment.isNull()) { + this.comment = null; + } + else if (comment.isEmpty()) { + this.comment = Optional.empty(); + } + else { + this.comment = Optional.of(comment.get()); + } return this; } + /** + *

        Comment on the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage comment(String comment) { this.comment = Optional.ofNullable(comment); return this; } + /** + *

        Comment on the score

        + */ @java.lang.Override @JsonSetter( value = "comment", @@ -552,12 +780,37 @@ public _FinalStage comment(Optional comment) { return this; } + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage authorUserId(Nullable authorUserId) { + if (authorUserId.isNull()) { + this.authorUserId = null; + } + else if (authorUserId.isEmpty()) { + this.authorUserId = Optional.empty(); + } + else { + this.authorUserId = Optional.of(authorUserId.get()); + } + return this; + } + + /** + *

        The user ID of the author

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage authorUserId(String authorUserId) { this.authorUserId = Optional.ofNullable(authorUserId); return this; } + /** + *

        The user ID of the author

        + */ @java.lang.Override @JsonSetter( value = "authorUserId", @@ -568,12 +821,37 @@ public _FinalStage authorUserId(Optional authorUserId) { return this; } + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage datasetRunId(Nullable datasetRunId) { + if (datasetRunId.isNull()) { + this.datasetRunId = null; + } + else if (datasetRunId.isEmpty()) { + this.datasetRunId = Optional.empty(); + } + else { + this.datasetRunId = Optional.of(datasetRunId.get()); + } + return this; + } + + /** + *

        The dataset run ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage datasetRunId(String datasetRunId) { this.datasetRunId = Optional.ofNullable(datasetRunId); return this; } + /** + *

        The dataset run ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "datasetRunId", @@ -584,12 +862,37 @@ public _FinalStage datasetRunId(Optional datasetRunId) { return this; } + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage observationId(Nullable observationId) { + if (observationId.isNull()) { + this.observationId = null; + } + else if (observationId.isEmpty()) { + this.observationId = Optional.empty(); + } + else { + this.observationId = Optional.of(observationId.get()); + } + return this; + } + + /** + *

        The observation ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage observationId(String observationId) { this.observationId = Optional.ofNullable(observationId); return this; } + /** + *

        The observation ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "observationId", @@ -600,12 +903,37 @@ public _FinalStage observationId(Optional observationId) { return this; } + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(Nullable sessionId) { + if (sessionId.isNull()) { + this.sessionId = null; + } + else if (sessionId.isEmpty()) { + this.sessionId = Optional.empty(); + } + else { + this.sessionId = Optional.of(sessionId.get()); + } + return this; + } + + /** + *

        The session ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage sessionId(String sessionId) { this.sessionId = Optional.ofNullable(sessionId); return this; } + /** + *

        The session ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "sessionId", @@ -616,12 +944,37 @@ public _FinalStage sessionId(Optional sessionId) { return this; } + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage traceId(Nullable traceId) { + if (traceId.isNull()) { + this.traceId = null; + } + else if (traceId.isEmpty()) { + this.traceId = Optional.empty(); + } + else { + this.traceId = Optional.of(traceId.get()); + } + return this; + } + + /** + *

        The trace ID associated with the score

        + * @return Reference to {@code this} so that method calls can be chained together. + */ @java.lang.Override public _FinalStage traceId(String traceId) { this.traceId = Optional.ofNullable(traceId); return this; } + /** + *

        The trace ID associated with the score

        + */ @java.lang.Override @JsonSetter( value = "traceId", @@ -636,5 +989,17 @@ public _FinalStage traceId(Optional traceId) { public GetScoresResponseDataNumeric build() { return new GetScoresResponseDataNumeric(value, id, traceId, sessionId, observationId, datasetRunId, name, source, timestamp, createdAt, updatedAt, authorUserId, comment, metadata, configId, queueId, environment, trace, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseTraceData.java b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseTraceData.java index 7eff37b..63d3651 100644 --- a/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseTraceData.java +++ b/src/main/java/com/langfuse/client/resources/scorev2/types/GetScoresResponseTraceData.java @@ -118,6 +118,9 @@ public Builder from(GetScoresResponseTraceData other) { return this; } + /** + *

        The user ID associated with the trace referenced by score

        + */ @JsonSetter( value = "userId", nulls = Nulls.SKIP @@ -132,6 +135,9 @@ public Builder userId(String userId) { return this; } + /** + *

        A list of tags associated with the trace referenced by score

        + */ @JsonSetter( value = "tags", nulls = Nulls.SKIP @@ -146,6 +152,9 @@ public Builder tags(List tags) { return this; } + /** + *

        The environment of the trace referenced by score

        + */ @JsonSetter( value = "environment", nulls = Nulls.SKIP @@ -163,5 +172,15 @@ public Builder environment(String environment) { public GetScoresResponseTraceData build() { return new GetScoresResponseTraceData(userId, tags, environment, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/sessions/AsyncRawSessionsClient.java b/src/main/java/com/langfuse/client/resources/sessions/AsyncRawSessionsClient.java new file mode 100644 index 0000000..1ff2aa6 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/sessions/AsyncRawSessionsClient.java @@ -0,0 +1,222 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.sessions; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.SessionWithTraces; +import com.langfuse.client.resources.sessions.requests.GetSessionsRequest; +import com.langfuse.client.resources.sessions.types.PaginatedSessions; + +public class AsyncRawSessionsClient { + protected final ClientOptions clientOptions; + + public AsyncRawSessionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get sessions + */ + public CompletableFuture> list() { + return list(GetSessionsRequest.builder().build()); + } + + /** + * Get sessions + */ + public CompletableFuture> list( + RequestOptions requestOptions) { + return list(GetSessionsRequest.builder().build(),requestOptions); + } + + /** + * Get sessions + */ + public CompletableFuture> list( + GetSessionsRequest request) { + return list(request,null); + } + + /** + * Get sessions + */ + public CompletableFuture> list( + GetSessionsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("sessions");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getFromTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get(), false); + } + if (request.getToTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedSessions.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public CompletableFuture> get(String sessionId) { + return get(sessionId,null); + } + + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public CompletableFuture> get(String sessionId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("sessions") + .addPathSegment(sessionId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, SessionWithTraces.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/sessions/AsyncSessionsClient.java b/src/main/java/com/langfuse/client/resources/sessions/AsyncSessionsClient.java new file mode 100644 index 0000000..f0bd843 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/sessions/AsyncSessionsClient.java @@ -0,0 +1,74 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.sessions; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.SessionWithTraces; +import com.langfuse.client.resources.sessions.requests.GetSessionsRequest; +import com.langfuse.client.resources.sessions.types.PaginatedSessions; + +public class AsyncSessionsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawSessionsClient rawClient; + + public AsyncSessionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawSessionsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawSessionsClient withRawResponse() { + return this.rawClient; + } + + /** + * Get sessions + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * Get sessions + */ + public CompletableFuture list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get sessions + */ + public CompletableFuture list(GetSessionsRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * Get sessions + */ + public CompletableFuture list(GetSessionsRequest request, + RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public CompletableFuture get(String sessionId) { + return this.rawClient.get(sessionId).thenApply(response -> response.body()); + } + + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public CompletableFuture get(String sessionId, RequestOptions requestOptions) { + return this.rawClient.get(sessionId, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/sessions/RawSessionsClient.java b/src/main/java/com/langfuse/client/resources/sessions/RawSessionsClient.java new file mode 100644 index 0000000..83769b8 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/sessions/RawSessionsClient.java @@ -0,0 +1,179 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.sessions; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.SessionWithTraces; +import com.langfuse.client.resources.sessions.requests.GetSessionsRequest; +import com.langfuse.client.resources.sessions.types.PaginatedSessions; + +public class RawSessionsClient { + protected final ClientOptions clientOptions; + + public RawSessionsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get sessions + */ + public LangfuseClientHttpResponse list() { + return list(GetSessionsRequest.builder().build()); + } + + /** + * Get sessions + */ + public LangfuseClientHttpResponse list(RequestOptions requestOptions) { + return list(GetSessionsRequest.builder().build(),requestOptions); + } + + /** + * Get sessions + */ + public LangfuseClientHttpResponse list(GetSessionsRequest request) { + return list(request,null); + } + + /** + * Get sessions + */ + public LangfuseClientHttpResponse list(GetSessionsRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("sessions");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getFromTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get(), false); + } + if (request.getToTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get(), false); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, PaginatedSessions.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public LangfuseClientHttpResponse get(String sessionId) { + return get(sessionId,null); + } + + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public LangfuseClientHttpResponse get(String sessionId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("sessions") + .addPathSegment(sessionId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, SessionWithTraces.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/sessions/SessionsClient.java b/src/main/java/com/langfuse/client/resources/sessions/SessionsClient.java index f1bab7b..8218acd 100644 --- a/src/main/java/com/langfuse/client/resources/sessions/SessionsClient.java +++ b/src/main/java/com/langfuse/client/resources/sessions/SessionsClient.java @@ -4,27 +4,9 @@ package com.langfuse.client.resources.sessions; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.SessionWithTraces; import com.langfuse.client.resources.sessions.requests.GetSessionsRequest; import com.langfuse.client.resources.sessions.types.PaginatedSessions; @@ -32,130 +14,59 @@ public class SessionsClient { protected final ClientOptions clientOptions; + private final RawSessionsClient rawClient; + public SessionsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawSessionsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawSessionsClient withRawResponse() { + return this.rawClient; } /** * Get sessions */ public PaginatedSessions list() { - return list(GetSessionsRequest.builder().build()); + return this.rawClient.list().body(); + } + + /** + * Get sessions + */ + public PaginatedSessions list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).body(); } /** * Get sessions */ public PaginatedSessions list(GetSessionsRequest request) { - return list(request,null); + return this.rawClient.list(request).body(); } /** * Get sessions */ public PaginatedSessions list(GetSessionsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("sessions");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - if (request.getFromTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get().toString(), false); - } - if (request.getToTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get().toString(), false); - } - if (request.getEnvironment().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), PaginatedSessions.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.list(request, requestOptions).body(); + } - /** - * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> - */ - public SessionWithTraces get(String sessionId) { - return get(sessionId,null); - } + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public SessionWithTraces get(String sessionId) { + return this.rawClient.get(sessionId).body(); + } - /** - * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> - */ - public SessionWithTraces get(String sessionId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("sessions") - .addPathSegment(sessionId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SessionWithTraces.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Get a session. Please note that traces on this endpoint are not paginated, if you plan to fetch large sessions, consider GET /api/public/traces?sessionId=<sessionId> + */ + public SessionWithTraces get(String sessionId, RequestOptions requestOptions) { + return this.rawClient.get(sessionId, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/sessions/requests/GetSessionsRequest.java b/src/main/java/com/langfuse/client/resources/sessions/requests/GetSessionsRequest.java index 15b8090..5d8bdc7 100644 --- a/src/main/java/com/langfuse/client/resources/sessions/requests/GetSessionsRequest.java +++ b/src/main/java/com/langfuse/client/resources/sessions/requests/GetSessionsRequest.java @@ -17,7 +17,9 @@ import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -27,6 +29,8 @@ builder = GetSessionsRequest.Builder.class ) public final class GetSessionsRequest { + private final Optional> environment; + private final Optional page; private final Optional limit; @@ -35,21 +39,27 @@ public final class GetSessionsRequest { private final Optional toTimestamp; - private final Optional environment; - private final Map additionalProperties; - private GetSessionsRequest(Optional page, Optional limit, - Optional fromTimestamp, Optional toTimestamp, - Optional environment, Map additionalProperties) { + private GetSessionsRequest(Optional> environment, Optional page, + Optional limit, Optional fromTimestamp, + Optional toTimestamp, Map additionalProperties) { + this.environment = environment; this.page = page; this.limit = limit; this.fromTimestamp = fromTimestamp; this.toTimestamp = toTimestamp; - this.environment = environment; this.additionalProperties = additionalProperties; } + /** + * @return Optional filter for sessions where the environment is one of the provided values. + */ + @JsonProperty("environment") + public Optional> getEnvironment() { + return environment; + } + /** * @return Page number, starts at 1 */ @@ -82,14 +92,6 @@ public Optional getToTimestamp() { return toTimestamp; } - /** - * @return Optional filter for sessions where the environment is one of the provided values. - */ - @JsonProperty("environment") - public Optional getEnvironment() { - return environment; - } - @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -102,12 +104,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(GetSessionsRequest other) { - return page.equals(other.page) && limit.equals(other.limit) && fromTimestamp.equals(other.fromTimestamp) && toTimestamp.equals(other.toTimestamp) && environment.equals(other.environment); + return environment.equals(other.environment) && page.equals(other.page) && limit.equals(other.limit) && fromTimestamp.equals(other.fromTimestamp) && toTimestamp.equals(other.toTimestamp); } @java.lang.Override public int hashCode() { - return Objects.hash(this.page, this.limit, this.fromTimestamp, this.toTimestamp, this.environment); + return Objects.hash(this.environment, this.page, this.limit, this.fromTimestamp, this.toTimestamp); } @java.lang.Override @@ -123,6 +125,8 @@ public static Builder builder() { ignoreUnknown = true ) public static final class Builder { + private Optional> environment = Optional.empty(); + private Optional page = Optional.empty(); private Optional limit = Optional.empty(); @@ -131,8 +135,6 @@ public static final class Builder { private Optional toTimestamp = Optional.empty(); - private Optional environment = Optional.empty(); - @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -140,14 +142,39 @@ private Builder() { } public Builder from(GetSessionsRequest other) { + environment(other.getEnvironment()); page(other.getPage()); limit(other.getLimit()); fromTimestamp(other.getFromTimestamp()); toTimestamp(other.getToTimestamp()); - environment(other.getEnvironment()); return this; } + /** + *

        Optional filter for sessions where the environment is one of the provided values.

        + */ + @JsonSetter( + value = "environment", + nulls = Nulls.SKIP + ) + public Builder environment(Optional> environment) { + this.environment = environment; + return this; + } + + public Builder environment(List environment) { + this.environment = Optional.ofNullable(environment); + return this; + } + + public Builder environment(String environment) { + this.environment = Optional.of(Collections.singletonList(environment)); + return this; + } + + /** + *

        Page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -162,6 +189,9 @@ public Builder page(Integer page) { return this; } + /** + *

        Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -176,6 +206,9 @@ public Builder limit(Integer limit) { return this; } + /** + *

        Optional filter to only include sessions created on or after a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "fromTimestamp", nulls = Nulls.SKIP @@ -190,6 +223,9 @@ public Builder fromTimestamp(OffsetDateTime fromTimestamp) { return this; } + /** + *

        Optional filter to only include sessions created before a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "toTimestamp", nulls = Nulls.SKIP @@ -204,22 +240,18 @@ public Builder toTimestamp(OffsetDateTime toTimestamp) { return this; } - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public Builder environment(Optional environment) { - this.environment = environment; - return this; + public GetSessionsRequest build() { + return new GetSessionsRequest(environment, page, limit, fromTimestamp, toTimestamp, additionalProperties); } - public Builder environment(String environment) { - this.environment = Optional.ofNullable(environment); + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); return this; } - public GetSessionsRequest build() { - return new GetSessionsRequest(page, limit, fromTimestamp, toTimestamp, environment, additionalProperties); + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/sessions/types/PaginatedSessions.java b/src/main/java/com/langfuse/client/resources/sessions/types/PaginatedSessions.java index 453124e..1199c1c 100644 --- a/src/main/java/com/langfuse/client/resources/sessions/types/PaginatedSessions.java +++ b/src/main/java/com/langfuse/client/resources/sessions/types/PaginatedSessions.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { PaginatedSessions build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(Session data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(Session data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public PaginatedSessions build() { return new PaginatedSessions(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/trace/AsyncRawTraceClient.java b/src/main/java/com/langfuse/client/resources/trace/AsyncRawTraceClient.java new file mode 100644 index 0000000..5ad925e --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/trace/AsyncRawTraceClient.java @@ -0,0 +1,409 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.trace; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.Override; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.TraceWithFullDetails; +import com.langfuse.client.resources.trace.requests.DeleteTracesRequest; +import com.langfuse.client.resources.trace.requests.GetTracesRequest; +import com.langfuse.client.resources.trace.types.DeleteTraceResponse; +import com.langfuse.client.resources.trace.types.Traces; + +public class AsyncRawTraceClient { + protected final ClientOptions clientOptions; + + public AsyncRawTraceClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a specific trace + */ + public CompletableFuture> get(String traceId) { + return get(traceId,null); + } + + /** + * Get a specific trace + */ + public CompletableFuture> get(String traceId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces") + .addPathSegment(traceId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TraceWithFullDetails.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete a specific trace + */ + public CompletableFuture> delete( + String traceId) { + return delete(traceId,null); + } + + /** + * Delete a specific trace + */ + public CompletableFuture> delete(String traceId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces") + .addPathSegment(traceId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteTraceResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Get list of traces + */ + public CompletableFuture> list() { + return list(GetTracesRequest.builder().build()); + } + + /** + * Get list of traces + */ + public CompletableFuture> list( + RequestOptions requestOptions) { + return list(GetTracesRequest.builder().build(),requestOptions); + } + + /** + * Get list of traces + */ + public CompletableFuture> list(GetTracesRequest request) { + return list(request,null); + } + + /** + * Get list of traces + */ + public CompletableFuture> list(GetTracesRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getSessionId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sessionId", request.getSessionId().get(), false); + } + if (request.getFromTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get(), false); + } + if (request.getToTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get(), false); + } + if (request.getOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "orderBy", request.getOrderBy().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getRelease().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "release", request.getRelease().get(), false); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getTags().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "tags", request.getTags().get(), true); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Traces.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Delete multiple traces + */ + public CompletableFuture> deleteMultiple( + DeleteTracesRequest request) { + return deleteMultiple(request,null); + } + + /** + * Delete multiple traces + */ + public CompletableFuture> deleteMultiple( + DeleteTracesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteTraceResponse.class), response)); + return; + } + try { + switch (response.code()) { + case 400:future.completeExceptionally(new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 401:future.completeExceptionally(new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 403:future.completeExceptionally(new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 404:future.completeExceptionally(new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + case 405:future.completeExceptionally(new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } + catch (IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new LangfuseClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + } diff --git a/src/main/java/com/langfuse/client/resources/trace/AsyncTraceClient.java b/src/main/java/com/langfuse/client/resources/trace/AsyncTraceClient.java new file mode 100644 index 0000000..9207994 --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/trace/AsyncTraceClient.java @@ -0,0 +1,106 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.trace; + +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.RequestOptions; +import java.lang.String; +import java.util.concurrent.CompletableFuture; +import com.langfuse.client.resources.commons.types.TraceWithFullDetails; +import com.langfuse.client.resources.trace.requests.DeleteTracesRequest; +import com.langfuse.client.resources.trace.requests.GetTracesRequest; +import com.langfuse.client.resources.trace.types.DeleteTraceResponse; +import com.langfuse.client.resources.trace.types.Traces; + +public class AsyncTraceClient { + protected final ClientOptions clientOptions; + + private final AsyncRawTraceClient rawClient; + + public AsyncTraceClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawTraceClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawTraceClient withRawResponse() { + return this.rawClient; + } + + /** + * Get a specific trace + */ + public CompletableFuture get(String traceId) { + return this.rawClient.get(traceId).thenApply(response -> response.body()); + } + + /** + * Get a specific trace + */ + public CompletableFuture get(String traceId, + RequestOptions requestOptions) { + return this.rawClient.get(traceId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete a specific trace + */ + public CompletableFuture delete(String traceId) { + return this.rawClient.delete(traceId).thenApply(response -> response.body()); + } + + /** + * Delete a specific trace + */ + public CompletableFuture delete(String traceId, + RequestOptions requestOptions) { + return this.rawClient.delete(traceId, requestOptions).thenApply(response -> response.body()); + } + + /** + * Get list of traces + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * Get list of traces + */ + public CompletableFuture list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).thenApply(response -> response.body()); + } + + /** + * Get list of traces + */ + public CompletableFuture list(GetTracesRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * Get list of traces + */ + public CompletableFuture list(GetTracesRequest request, RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Delete multiple traces + */ + public CompletableFuture deleteMultiple(DeleteTracesRequest request) { + return this.rawClient.deleteMultiple(request).thenApply(response -> response.body()); + } + + /** + * Delete multiple traces + */ + public CompletableFuture deleteMultiple(DeleteTracesRequest request, + RequestOptions requestOptions) { + return this.rawClient.deleteMultiple(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/langfuse/client/resources/trace/RawTraceClient.java b/src/main/java/com/langfuse/client/resources/trace/RawTraceClient.java new file mode 100644 index 0000000..b38409e --- /dev/null +++ b/src/main/java/com/langfuse/client/resources/trace/RawTraceClient.java @@ -0,0 +1,330 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +package com.langfuse.client.resources.trace; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.langfuse.client.core.ClientOptions; +import com.langfuse.client.core.LangfuseClientApiException; +import com.langfuse.client.core.LangfuseClientException; +import com.langfuse.client.core.LangfuseClientHttpResponse; +import com.langfuse.client.core.MediaTypes; +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.core.QueryStringMapper; +import com.langfuse.client.core.RequestOptions; +import java.io.IOException; +import java.lang.Object; +import java.lang.String; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import com.langfuse.client.resources.commons.errors.AccessDeniedError; +import com.langfuse.client.resources.commons.errors.Error; +import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; +import com.langfuse.client.resources.commons.errors.NotFoundError; +import com.langfuse.client.resources.commons.errors.UnauthorizedError; +import com.langfuse.client.resources.commons.types.TraceWithFullDetails; +import com.langfuse.client.resources.trace.requests.DeleteTracesRequest; +import com.langfuse.client.resources.trace.requests.GetTracesRequest; +import com.langfuse.client.resources.trace.types.DeleteTraceResponse; +import com.langfuse.client.resources.trace.types.Traces; + +public class RawTraceClient { + protected final ClientOptions clientOptions; + + public RawTraceClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Get a specific trace + */ + public LangfuseClientHttpResponse get(String traceId) { + return get(traceId,null); + } + + /** + * Get a specific trace + */ + public LangfuseClientHttpResponse get(String traceId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces") + .addPathSegment(traceId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TraceWithFullDetails.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete a specific trace + */ + public LangfuseClientHttpResponse delete(String traceId) { + return delete(traceId,null); + } + + /** + * Delete a specific trace + */ + public LangfuseClientHttpResponse delete(String traceId, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces") + .addPathSegment(traceId);if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteTraceResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Get list of traces + */ + public LangfuseClientHttpResponse list() { + return list(GetTracesRequest.builder().build()); + } + + /** + * Get list of traces + */ + public LangfuseClientHttpResponse list(RequestOptions requestOptions) { + return list(GetTracesRequest.builder().build(),requestOptions); + } + + /** + * Get list of traces + */ + public LangfuseClientHttpResponse list(GetTracesRequest request) { + return list(request,null); + } + + /** + * Get list of traces + */ + public LangfuseClientHttpResponse list(GetTracesRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces");if (request.getPage().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getUserId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); + } + if (request.getName().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); + } + if (request.getSessionId().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "sessionId", request.getSessionId().get(), false); + } + if (request.getFromTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get(), false); + } + if (request.getToTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get(), false); + } + if (request.getOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "orderBy", request.getOrderBy().get(), false); + } + if (request.getVersion().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); + } + if (request.getRelease().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "release", request.getRelease().get(), false); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); + } + if (request.getFilter().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); + } + if (request.getTags().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "tags", request.getTags().get(), true); + } + if (request.getEnvironment().isPresent()) { + QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), true); + } + if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Traces.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + + /** + * Delete multiple traces + */ + public LangfuseClientHttpResponse deleteMultiple( + DeleteTracesRequest request) { + return deleteMultiple(request,null); + } + + /** + * Delete multiple traces + */ + public LangfuseClientHttpResponse deleteMultiple( + DeleteTracesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() + .addPathSegments("api/public") + .addPathSegments("traces");if (requestOptions != null) { + requestOptions.getQueryParameters().forEach((_key, _value) -> { + httpUrl.addQueryParameter(_key, _value); + } ); + } + RequestBody body; + try { + body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } + catch(JsonProcessingException e) { + throw new LangfuseClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl.build()) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new LangfuseClientHttpResponse<>(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DeleteTraceResponse.class), response); + } + try { + switch (response.code()) { + case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } + catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), errorBody, response); + } + catch (IOException e) { + throw new LangfuseClientException("Network error executing HTTP request", e); + } + } + } diff --git a/src/main/java/com/langfuse/client/resources/trace/TraceClient.java b/src/main/java/com/langfuse/client/resources/trace/TraceClient.java index a4fbd6b..63354f5 100644 --- a/src/main/java/com/langfuse/client/resources/trace/TraceClient.java +++ b/src/main/java/com/langfuse/client/resources/trace/TraceClient.java @@ -4,29 +4,9 @@ package com.langfuse.client.resources.trace; -import com.fasterxml.jackson.core.JsonProcessingException; import com.langfuse.client.core.ClientOptions; -import com.langfuse.client.core.LangfuseClientApiException; -import com.langfuse.client.core.LangfuseClientException; -import com.langfuse.client.core.MediaTypes; -import com.langfuse.client.core.ObjectMappers; -import com.langfuse.client.core.QueryStringMapper; import com.langfuse.client.core.RequestOptions; -import java.io.IOException; -import java.lang.Object; import java.lang.String; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import com.langfuse.client.resources.commons.errors.AccessDeniedError; -import com.langfuse.client.resources.commons.errors.Error; -import com.langfuse.client.resources.commons.errors.MethodNotAllowedError; -import com.langfuse.client.resources.commons.errors.NotFoundError; -import com.langfuse.client.resources.commons.errors.UnauthorizedError; import com.langfuse.client.resources.commons.types.TraceWithFullDetails; import com.langfuse.client.resources.trace.requests.DeleteTracesRequest; import com.langfuse.client.resources.trace.requests.GetTracesRequest; @@ -36,268 +16,88 @@ public class TraceClient { protected final ClientOptions clientOptions; + private final RawTraceClient rawClient; + public TraceClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; + this.rawClient = new RawTraceClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawTraceClient withRawResponse() { + return this.rawClient; } /** * Get a specific trace */ public TraceWithFullDetails get(String traceId) { - return get(traceId,null); + return this.rawClient.get(traceId).body(); } /** * Get a specific trace */ public TraceWithFullDetails get(String traceId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("traces") - .addPathSegment(traceId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TraceWithFullDetails.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.get(traceId, requestOptions).body(); } /** * Delete a specific trace */ public DeleteTraceResponse delete(String traceId) { - return delete(traceId,null); + return this.rawClient.delete(traceId).body(); } /** * Delete a specific trace */ public DeleteTraceResponse delete(String traceId, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("traces") - .addPathSegment(traceId) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeleteTraceResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } + return this.rawClient.delete(traceId, requestOptions).body(); } /** * Get list of traces */ public Traces list() { - return list(GetTracesRequest.builder().build()); + return this.rawClient.list().body(); + } + + /** + * Get list of traces + */ + public Traces list(RequestOptions requestOptions) { + return this.rawClient.list(requestOptions).body(); } /** * Get list of traces */ public Traces list(GetTracesRequest request) { - return list(request,null); + return this.rawClient.list(request).body(); } /** * Get list of traces */ public Traces list(GetTracesRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("traces");if (request.getPage().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "page", request.getPage().get().toString(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "limit", request.getLimit().get().toString(), false); - } - if (request.getUserId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "userId", request.getUserId().get(), false); - } - if (request.getName().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName().get(), false); - } - if (request.getSessionId().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "sessionId", request.getSessionId().get(), false); - } - if (request.getFromTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fromTimestamp", request.getFromTimestamp().get().toString(), false); - } - if (request.getToTimestamp().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "toTimestamp", request.getToTimestamp().get().toString(), false); - } - if (request.getOrderBy().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "orderBy", request.getOrderBy().get(), false); - } - if (request.getTags().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "tags", request.getTags().get(), false); - } - if (request.getVersion().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "version", request.getVersion().get(), false); - } - if (request.getRelease().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "release", request.getRelease().get(), false); - } - if (request.getEnvironment().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "environment", request.getEnvironment().get(), false); - } - if (request.getFields().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "fields", request.getFields().get(), false); - } - if (request.getFilter().isPresent()) { - QueryStringMapper.addQueryParameter(httpUrl, "filter", request.getFilter().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Traces.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + return this.rawClient.list(request, requestOptions).body(); + } - /** - * Delete multiple traces - */ - public DeleteTraceResponse deleteMultiple(DeleteTracesRequest request) { - return deleteMultiple(request,null); - } + /** + * Delete multiple traces + */ + public DeleteTraceResponse deleteMultiple(DeleteTracesRequest request) { + return this.rawClient.deleteMultiple(request).body(); + } - /** - * Delete multiple traces - */ - public DeleteTraceResponse deleteMultiple(DeleteTracesRequest request, - RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()).newBuilder() - .addPathSegments("api/public") - .addPathSegments("traces") - .build(); - RequestBody body; - try { - body = RequestBody.create(ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } - catch(JsonProcessingException e) { - throw new LangfuseClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeleteTraceResponse.class); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400:throw new Error(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 401:throw new UnauthorizedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 403:throw new AccessDeniedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 404:throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - case 405:throw new MethodNotAllowedError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - } - catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new LangfuseClientApiException("Error with status code " + response.code(), response.code(), ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); - } - catch (IOException e) { - throw new LangfuseClientException("Network error executing HTTP request", e); - } - } + /** + * Delete multiple traces + */ + public DeleteTraceResponse deleteMultiple(DeleteTracesRequest request, + RequestOptions requestOptions) { + return this.rawClient.deleteMultiple(request, requestOptions).body(); } +} diff --git a/src/main/java/com/langfuse/client/resources/trace/requests/DeleteTracesRequest.java b/src/main/java/com/langfuse/client/resources/trace/requests/DeleteTracesRequest.java index 9a6317a..de16e90 100644 --- a/src/main/java/com/langfuse/client/resources/trace/requests/DeleteTracesRequest.java +++ b/src/main/java/com/langfuse/client/resources/trace/requests/DeleteTracesRequest.java @@ -89,13 +89,18 @@ public Builder from(DeleteTracesRequest other) { return this; } + /** + *

        List of trace IDs to delete

        + */ @JsonSetter( value = "traceIds", nulls = Nulls.SKIP ) public Builder traceIds(List traceIds) { this.traceIds.clear(); - this.traceIds.addAll(traceIds); + if (traceIds != null) { + this.traceIds.addAll(traceIds); + } return this; } @@ -105,12 +110,24 @@ public Builder addTraceIds(String traceIds) { } public Builder addAllTraceIds(List traceIds) { - this.traceIds.addAll(traceIds); + if (traceIds != null) { + this.traceIds.addAll(traceIds); + } return this; } public DeleteTracesRequest build() { return new DeleteTracesRequest(traceIds, additionalProperties); } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/trace/requests/GetTracesRequest.java b/src/main/java/com/langfuse/client/resources/trace/requests/GetTracesRequest.java index b94a26c..899eb21 100644 --- a/src/main/java/com/langfuse/client/resources/trace/requests/GetTracesRequest.java +++ b/src/main/java/com/langfuse/client/resources/trace/requests/GetTracesRequest.java @@ -17,7 +17,9 @@ import java.lang.Object; import java.lang.String; import java.time.OffsetDateTime; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -27,6 +29,10 @@ builder = GetTracesRequest.Builder.class ) public final class GetTracesRequest { + private final Optional> tags; + + private final Optional> environment; + private final Optional page; private final Optional limit; @@ -43,25 +49,24 @@ public final class GetTracesRequest { private final Optional orderBy; - private final Optional tags; - private final Optional version; private final Optional release; - private final Optional environment; - private final Optional fields; private final Optional filter; private final Map additionalProperties; - private GetTracesRequest(Optional page, Optional limit, Optional userId, + private GetTracesRequest(Optional> tags, Optional> environment, + Optional page, Optional limit, Optional userId, Optional name, Optional sessionId, Optional fromTimestamp, - Optional toTimestamp, Optional orderBy, Optional tags, - Optional version, Optional release, Optional environment, - Optional fields, Optional filter, Map additionalProperties) { + Optional toTimestamp, Optional orderBy, Optional version, + Optional release, Optional fields, Optional filter, + Map additionalProperties) { + this.tags = tags; + this.environment = environment; this.page = page; this.limit = limit; this.userId = userId; @@ -70,15 +75,29 @@ private GetTracesRequest(Optional page, Optional limit, Option this.fromTimestamp = fromTimestamp; this.toTimestamp = toTimestamp; this.orderBy = orderBy; - this.tags = tags; this.version = version; this.release = release; - this.environment = environment; this.fields = fields; this.filter = filter; this.additionalProperties = additionalProperties; } + /** + * @return Only traces that include all of these tags will be returned. + */ + @JsonProperty("tags") + public Optional> getTags() { + return tags; + } + + /** + * @return Optional filter for traces where the environment is one of the provided values. + */ + @JsonProperty("environment") + public Optional> getEnvironment() { + return environment; + } + /** * @return Page number, starts at 1 */ @@ -134,14 +153,6 @@ public Optional getOrderBy() { return orderBy; } - /** - * @return Only traces that include all of these tags will be returned. - */ - @JsonProperty("tags") - public Optional getTags() { - return tags; - } - /** * @return Optional filter to only include traces with a certain version. */ @@ -158,14 +169,6 @@ public Optional getRelease() { return release; } - /** - * @return Optional filter for traces where the environment is one of the provided values. - */ - @JsonProperty("environment") - public Optional getEnvironment() { - return environment; - } - /** * @return Comma-separated list of fields to include in the response. Available field groups: 'core' (always included), 'io' (input, output, metadata), 'scores', 'observations', 'metrics'. If not specified, all fields are returned. Example: 'core,scores,metrics'. Note: Excluded 'observations' or 'scores' fields return empty arrays; excluded 'metrics' returns -1 for 'totalCost' and 'latency'. */ @@ -194,12 +197,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(GetTracesRequest other) { - return page.equals(other.page) && limit.equals(other.limit) && userId.equals(other.userId) && name.equals(other.name) && sessionId.equals(other.sessionId) && fromTimestamp.equals(other.fromTimestamp) && toTimestamp.equals(other.toTimestamp) && orderBy.equals(other.orderBy) && tags.equals(other.tags) && version.equals(other.version) && release.equals(other.release) && environment.equals(other.environment) && fields.equals(other.fields) && filter.equals(other.filter); + return tags.equals(other.tags) && environment.equals(other.environment) && page.equals(other.page) && limit.equals(other.limit) && userId.equals(other.userId) && name.equals(other.name) && sessionId.equals(other.sessionId) && fromTimestamp.equals(other.fromTimestamp) && toTimestamp.equals(other.toTimestamp) && orderBy.equals(other.orderBy) && version.equals(other.version) && release.equals(other.release) && fields.equals(other.fields) && filter.equals(other.filter); } @java.lang.Override public int hashCode() { - return Objects.hash(this.page, this.limit, this.userId, this.name, this.sessionId, this.fromTimestamp, this.toTimestamp, this.orderBy, this.tags, this.version, this.release, this.environment, this.fields, this.filter); + return Objects.hash(this.tags, this.environment, this.page, this.limit, this.userId, this.name, this.sessionId, this.fromTimestamp, this.toTimestamp, this.orderBy, this.version, this.release, this.fields, this.filter); } @java.lang.Override @@ -215,6 +218,10 @@ public static Builder builder() { ignoreUnknown = true ) public static final class Builder { + private Optional> tags = Optional.empty(); + + private Optional> environment = Optional.empty(); + private Optional page = Optional.empty(); private Optional limit = Optional.empty(); @@ -231,14 +238,10 @@ public static final class Builder { private Optional orderBy = Optional.empty(); - private Optional tags = Optional.empty(); - private Optional version = Optional.empty(); private Optional release = Optional.empty(); - private Optional environment = Optional.empty(); - private Optional fields = Optional.empty(); private Optional filter = Optional.empty(); @@ -250,6 +253,8 @@ private Builder() { } public Builder from(GetTracesRequest other) { + tags(other.getTags()); + environment(other.getEnvironment()); page(other.getPage()); limit(other.getLimit()); userId(other.getUserId()); @@ -258,15 +263,60 @@ public Builder from(GetTracesRequest other) { fromTimestamp(other.getFromTimestamp()); toTimestamp(other.getToTimestamp()); orderBy(other.getOrderBy()); - tags(other.getTags()); version(other.getVersion()); release(other.getRelease()); - environment(other.getEnvironment()); fields(other.getFields()); filter(other.getFilter()); return this; } + /** + *

        Only traces that include all of these tags will be returned.

        + */ + @JsonSetter( + value = "tags", + nulls = Nulls.SKIP + ) + public Builder tags(Optional> tags) { + this.tags = tags; + return this; + } + + public Builder tags(List tags) { + this.tags = Optional.ofNullable(tags); + return this; + } + + public Builder tags(String tags) { + this.tags = Optional.of(Collections.singletonList(tags)); + return this; + } + + /** + *

        Optional filter for traces where the environment is one of the provided values.

        + */ + @JsonSetter( + value = "environment", + nulls = Nulls.SKIP + ) + public Builder environment(Optional> environment) { + this.environment = environment; + return this; + } + + public Builder environment(List environment) { + this.environment = Optional.ofNullable(environment); + return this; + } + + public Builder environment(String environment) { + this.environment = Optional.of(Collections.singletonList(environment)); + return this; + } + + /** + *

        Page number, starts at 1

        + */ @JsonSetter( value = "page", nulls = Nulls.SKIP @@ -281,6 +331,9 @@ public Builder page(Integer page) { return this; } + /** + *

        Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.

        + */ @JsonSetter( value = "limit", nulls = Nulls.SKIP @@ -337,6 +390,9 @@ public Builder sessionId(String sessionId) { return this; } + /** + *

        Optional filter to only include traces with a trace.timestamp on or after a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "fromTimestamp", nulls = Nulls.SKIP @@ -351,6 +407,9 @@ public Builder fromTimestamp(OffsetDateTime fromTimestamp) { return this; } + /** + *

        Optional filter to only include traces with a trace.timestamp before a certain datetime (ISO 8601)

        + */ @JsonSetter( value = "toTimestamp", nulls = Nulls.SKIP @@ -365,6 +424,9 @@ public Builder toTimestamp(OffsetDateTime toTimestamp) { return this; } + /** + *

        Format of the string [field].[asc/desc]. Fields: id, timestamp, name, userId, release, version, public, bookmarked, sessionId. Example: timestamp.asc

        + */ @JsonSetter( value = "orderBy", nulls = Nulls.SKIP @@ -379,20 +441,9 @@ public Builder orderBy(String orderBy) { return this; } - @JsonSetter( - value = "tags", - nulls = Nulls.SKIP - ) - public Builder tags(Optional tags) { - this.tags = tags; - return this; - } - - public Builder tags(String tags) { - this.tags = Optional.ofNullable(tags); - return this; - } - + /** + *

        Optional filter to only include traces with a certain version.

        + */ @JsonSetter( value = "version", nulls = Nulls.SKIP @@ -407,6 +458,9 @@ public Builder version(String version) { return this; } + /** + *

        Optional filter to only include traces with a certain release.

        + */ @JsonSetter( value = "release", nulls = Nulls.SKIP @@ -421,20 +475,9 @@ public Builder release(String release) { return this; } - @JsonSetter( - value = "environment", - nulls = Nulls.SKIP - ) - public Builder environment(Optional environment) { - this.environment = environment; - return this; - } - - public Builder environment(String environment) { - this.environment = Optional.ofNullable(environment); - return this; - } - + /** + *

        Comma-separated list of fields to include in the response. Available field groups: 'core' (always included), 'io' (input, output, metadata), 'scores', 'observations', 'metrics'. If not specified, all fields are returned. Example: 'core,scores,metrics'. Note: Excluded 'observations' or 'scores' fields return empty arrays; excluded 'metrics' returns -1 for 'totalCost' and 'latency'.

        + */ @JsonSetter( value = "fields", nulls = Nulls.SKIP @@ -449,6 +492,9 @@ public Builder fields(String fields) { return this; } + /** + * JSON string containing an array of filter conditions. When provided, this takes precedence over query parameter filters (userId, name, sessionId, tags, version, release, environment, fromTimestamp, toTimestamp). + */ @JsonSetter( value = "filter", nulls = Nulls.SKIP @@ -464,7 +510,17 @@ public Builder filter(String filter) { } public GetTracesRequest build() { - return new GetTracesRequest(page, limit, userId, name, sessionId, fromTimestamp, toTimestamp, orderBy, tags, version, release, environment, fields, filter, additionalProperties); + return new GetTracesRequest(tags, environment, page, limit, userId, name, sessionId, fromTimestamp, toTimestamp, orderBy, version, release, fields, filter, additionalProperties); + } + + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; } } } diff --git a/src/main/java/com/langfuse/client/resources/trace/types/DeleteTraceResponse.java b/src/main/java/com/langfuse/client/resources/trace/types/DeleteTraceResponse.java index 6e6614f..43e971f 100644 --- a/src/main/java/com/langfuse/client/resources/trace/types/DeleteTraceResponse.java +++ b/src/main/java/com/langfuse/client/resources/trace/types/DeleteTraceResponse.java @@ -75,6 +75,10 @@ public interface MessageStage { public interface _FinalStage { DeleteTraceResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -106,5 +110,17 @@ public _FinalStage message(@NotNull String message) { public DeleteTraceResponse build() { return new DeleteTraceResponse(message, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/trace/types/Sort.java b/src/main/java/com/langfuse/client/resources/trace/types/Sort.java index fbea73e..b8da8fa 100644 --- a/src/main/java/com/langfuse/client/resources/trace/types/Sort.java +++ b/src/main/java/com/langfuse/client/resources/trace/types/Sort.java @@ -75,6 +75,10 @@ public interface IdStage { public interface _FinalStage { Sort build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -106,5 +110,17 @@ public _FinalStage id(@NotNull String id) { public Sort build() { return new Sort(id, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/trace/types/Traces.java b/src/main/java/com/langfuse/client/resources/trace/types/Traces.java index a2d9717..716d110 100644 --- a/src/main/java/com/langfuse/client/resources/trace/types/Traces.java +++ b/src/main/java/com/langfuse/client/resources/trace/types/Traces.java @@ -90,6 +90,10 @@ public interface MetaStage { public interface _FinalStage { Traces build(); + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); + _FinalStage data(List data); _FinalStage addData(TraceWithDetails data); @@ -127,7 +131,9 @@ public _FinalStage meta(@NotNull MetaResponse meta) { @java.lang.Override public _FinalStage addAllData(List data) { - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -144,7 +150,9 @@ public _FinalStage addData(TraceWithDetails data) { ) public _FinalStage data(List data) { this.data.clear(); - this.data.addAll(data); + if (data != null) { + this.data.addAll(data); + } return this; } @@ -152,5 +160,17 @@ public _FinalStage data(List data) { public Traces build() { return new Traces(data, meta, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/main/java/com/langfuse/client/resources/utils/pagination/types/MetaResponse.java b/src/main/java/com/langfuse/client/resources/utils/pagination/types/MetaResponse.java index 67319fe..b840f0a 100644 --- a/src/main/java/com/langfuse/client/resources/utils/pagination/types/MetaResponse.java +++ b/src/main/java/com/langfuse/client/resources/utils/pagination/types/MetaResponse.java @@ -104,25 +104,41 @@ public static PageStage builder() { } public interface PageStage { + /** + *

        current page number

        + */ LimitStage page(int page); Builder from(MetaResponse other); } public interface LimitStage { + /** + *

        number of items per page

        + */ TotalItemsStage limit(int limit); } public interface TotalItemsStage { + /** + *

        number of total items given the current filters/selection (if any)

        + */ TotalPagesStage totalItems(int totalItems); } public interface TotalPagesStage { + /** + *

        number of total pages given the current limit

        + */ _FinalStage totalPages(int totalPages); } public interface _FinalStage { MetaResponse build(); + + _FinalStage additionalProperty(String key, Object value); + + _FinalStage additionalProperties(Map additionalProperties); } @JsonIgnoreProperties( @@ -153,6 +169,7 @@ public Builder from(MetaResponse other) { } /** + *

        current page number

        *

        current page number

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -164,6 +181,7 @@ public LimitStage page(int page) { } /** + *

        number of items per page

        *

        number of items per page

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -175,6 +193,7 @@ public TotalItemsStage limit(int limit) { } /** + *

        number of total items given the current filters/selection (if any)

        *

        number of total items given the current filters/selection (if any)

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -186,6 +205,7 @@ public TotalPagesStage totalItems(int totalItems) { } /** + *

        number of total pages given the current limit

        *

        number of total pages given the current limit

        * @return Reference to {@code this} so that method calls can be chained together. */ @@ -200,5 +220,17 @@ public _FinalStage totalPages(int totalPages) { public MetaResponse build() { return new MetaResponse(page, limit, totalItems, totalPages, additionalProperties); } + + @java.lang.Override + public Builder additionalProperty(String key, Object value) { + this.additionalProperties.put(key, value); + return this; + } + + @java.lang.Override + public Builder additionalProperties(Map additionalProperties) { + this.additionalProperties.putAll(additionalProperties); + return this; + } } } diff --git a/src/test/java/com/langfuse/client/TestClientFactory.java b/src/test/java/com/langfuse/client/TestClientFactory.java new file mode 100644 index 0000000..4b57781 --- /dev/null +++ b/src/test/java/com/langfuse/client/TestClientFactory.java @@ -0,0 +1,37 @@ +package com.langfuse.client; + +import io.github.cdimascio.dotenv.Dotenv; + +/** + * Utility for integration tests: loads Langfuse credentials from a {@code .env} + * file (or system/environment variables) and builds a {@link LangfuseClient}. + */ +public final class TestClientFactory { + + private static final Dotenv DOTENV = Dotenv.configure() + .ignoreIfMissing() + .load(); + + private TestClientFactory() {} + + public static String getEnv(String key) { + // dotenv-java checks .env first, then falls back to system env + return DOTENV.get(key); + } + + public static boolean hasCredentials() { + String publicKey = getEnv("LANGFUSE_PUBLIC_KEY"); + String secretKey = getEnv("LANGFUSE_SECRET_KEY"); + String host = getEnv("LANGFUSE_HOST"); + return publicKey != null && !publicKey.isEmpty() + && secretKey != null && !secretKey.isEmpty() + && host != null && !host.isEmpty(); + } + + public static LangfuseClient createClient() { + return LangfuseClient.builder() + .credentials(getEnv("LANGFUSE_PUBLIC_KEY"), getEnv("LANGFUSE_SECRET_KEY")) + .url(getEnv("LANGFUSE_HOST")) + .build(); + } +} diff --git a/src/main/java/com/langfuse/client/core/QueryStringMapperTest.java b/src/test/java/com/langfuse/client/core/QueryStringMapperTest.java similarity index 100% rename from src/main/java/com/langfuse/client/core/QueryStringMapperTest.java rename to src/test/java/com/langfuse/client/core/QueryStringMapperTest.java diff --git a/src/test/java/com/langfuse/client/deserialization/ChatPromptDeserializationTest.java b/src/test/java/com/langfuse/client/deserialization/ChatPromptDeserializationTest.java new file mode 100644 index 0000000..d7160d5 --- /dev/null +++ b/src/test/java/com/langfuse/client/deserialization/ChatPromptDeserializationTest.java @@ -0,0 +1,82 @@ +package com.langfuse.client.deserialization; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.resources.prompts.types.ChatMessage; +import com.langfuse.client.resources.prompts.types.ChatMessageWithPlaceholders; +import com.langfuse.client.resources.prompts.types.ChatPrompt; +import com.langfuse.client.resources.prompts.types.PlaceholderMessage; +import com.langfuse.client.resources.prompts.types.Prompt; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for chat prompt deserialization through the same code path as + * {@code PromptsClient.get()} — i.e. {@code ObjectMappers.JSON_MAPPER.readValue(..., Prompt.class)}. + * + *

        These tests use a hardcoded JSON fixture and require no credentials or network access. + * They exist primarily to catch the regression where {@code ChatMessage.getRole()} and + * {@code ChatMessage.getContent()} return {@code null} after deserialization. + */ +class ChatPromptDeserializationTest { + + private static final String FIXTURE = "/fixtures/chat_prompt_response.json"; + + @Test + void deserializeChatPrompt_hasCorrectTopLevelFields() throws Exception { + Prompt prompt = deserializeFixture(); + + assertThat(prompt.isChat()).isTrue(); + assertThat(prompt.isText()).isFalse(); + + ChatPrompt chatPrompt = prompt.getChat().orElseThrow(); + assertThat(chatPrompt.getName()).isEqualTo("test-chat-prompt"); + assertThat(chatPrompt.getVersion()).isEqualTo(1); + assertThat(chatPrompt.getLabels()).contains("production"); + } + + @Test + void deserializeChatPrompt_chatMessageHasNonNullRoleAndContent() throws Exception { + Prompt prompt = deserializeFixture(); + ChatPrompt chatPrompt = prompt.getChat().orElseThrow(); + List messages = chatPrompt.getPrompt(); + + assertThat(messages).hasSize(2); + + // First entry — chat message (no "type" discriminator in real API response) + assertThat(messages.get(0).get()).isInstanceOf(ChatMessage.class); + ChatMessage system = (ChatMessage) messages.get(0).get(); + assertThat(system.getRole()).isNotNull().isEqualTo("system"); + assertThat(system.getContent()).isNotNull().isEqualTo("Hello World"); + + // Second entry — placeholder (has "type": "placeholder") + assertThat(messages.get(1).get()).isInstanceOf(PlaceholderMessage.class); + PlaceholderMessage placeholder = (PlaceholderMessage) messages.get(1).get(); + assertThat(placeholder.getName()).isEqualTo("username"); + } + + @Test + void chatMessageRoundTripSerialization() throws Exception { + Prompt prompt = deserializeFixture(); + ChatPrompt chatPrompt = prompt.getChat().orElseThrow(); + ChatMessage original = (ChatMessage) chatPrompt.getPrompt().get(0).get(); + + // Serialize to JSON and back + String json = ObjectMappers.JSON_MAPPER.writeValueAsString(original); + ChatMessage roundTripped = ObjectMappers.JSON_MAPPER.readValue(json, ChatMessage.class); + + assertThat(roundTripped.getRole()).isEqualTo(original.getRole()); + assertThat(roundTripped.getContent()).isEqualTo(original.getContent()); + } + + private Prompt deserializeFixture() throws Exception { + try (InputStream is = getClass().getResourceAsStream(FIXTURE)) { + assertThat(is).as("Fixture %s must be on the classpath", FIXTURE).isNotNull(); + String json = new String(is.readAllBytes(), StandardCharsets.UTF_8); + return ObjectMappers.JSON_MAPPER.readValue(json, Prompt.class); + } + } +} diff --git a/src/test/java/com/langfuse/client/deserialization/TextPromptDeserializationTest.java b/src/test/java/com/langfuse/client/deserialization/TextPromptDeserializationTest.java new file mode 100644 index 0000000..63ae100 --- /dev/null +++ b/src/test/java/com/langfuse/client/deserialization/TextPromptDeserializationTest.java @@ -0,0 +1,50 @@ +package com.langfuse.client.deserialization; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.langfuse.client.core.ObjectMappers; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.prompts.types.TextPrompt; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for text prompt deserialization through + * {@code ObjectMappers.JSON_MAPPER.readValue(..., Prompt.class)}. + * + *

        Uses a hardcoded JSON fixture — no credentials or network access required. + */ +class TextPromptDeserializationTest { + + private static final String FIXTURE = "/fixtures/text_prompt_response.json"; + + @Test + void deserializeTextPrompt_hasCorrectTopLevelFields() throws Exception { + Prompt prompt = deserializeFixture(); + + assertThat(prompt.isText()).isTrue(); + assertThat(prompt.isChat()).isFalse(); + + TextPrompt textPrompt = prompt.getText().orElseThrow(); + assertThat(textPrompt.getName()).isEqualTo("test-text-prompt"); + assertThat(textPrompt.getVersion()).isEqualTo(1); + } + + @Test + void deserializeTextPrompt_promptIsNonNullAndNonEmpty() throws Exception { + Prompt prompt = deserializeFixture(); + TextPrompt textPrompt = prompt.getText().orElseThrow(); + + assertThat(textPrompt.getPrompt()).isNotNull().isNotEmpty(); + assertThat(textPrompt.getPrompt()).isEqualTo("Hello World"); + } + + private Prompt deserializeFixture() throws Exception { + try (InputStream is = getClass().getResourceAsStream(FIXTURE)) { + assertThat(is).as("Fixture %s must be on the classpath", FIXTURE).isNotNull(); + String json = new String(is.readAllBytes(), StandardCharsets.UTF_8); + return ObjectMappers.JSON_MAPPER.readValue(json, Prompt.class); + } + } +} diff --git a/src/test/java/com/langfuse/client/integration/PromptIntegrationTest.java b/src/test/java/com/langfuse/client/integration/PromptIntegrationTest.java new file mode 100644 index 0000000..00b0ab8 --- /dev/null +++ b/src/test/java/com/langfuse/client/integration/PromptIntegrationTest.java @@ -0,0 +1,88 @@ +package com.langfuse.client.integration; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.langfuse.client.LangfuseClient; +import com.langfuse.client.TestClientFactory; +import com.langfuse.client.resources.prompts.types.ChatMessage; +import com.langfuse.client.resources.prompts.types.ChatMessageWithPlaceholders; +import com.langfuse.client.resources.prompts.types.ChatPrompt; +import com.langfuse.client.resources.prompts.types.Prompt; +import com.langfuse.client.resources.prompts.types.TextPrompt; +import java.util.List; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Integration tests that connect to a real Langfuse project. + * + *

        Prerequisites: The target Langfuse project must contain: + *

          + *
        • {@code test-chat-prompt} — a chat-type prompt with at least one message + * that has both {@code role} and {@code content} set.
        • + *
        • {@code test-text-prompt} — a text-type prompt with non-empty text.
        • + *
        + * + *

        Credentials are loaded from a {@code .env} file (or system env vars). + * See {@code .env.example} for the required variables. When credentials are + * absent the tests are skipped rather than failed. + */ +@Tag("integration") +class PromptIntegrationTest { + + private static LangfuseClient client; + + @BeforeAll + static void setUp() { + Assumptions.assumeTrue( + TestClientFactory.hasCredentials(), + "Skipping integration tests — LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY / LANGFUSE_HOST not set"); + client = TestClientFactory.createClient(); + } + + @Test + void fetchChatPrompt_messagesHaveRoleAndContent() { + Prompt prompt = client.prompts().get("test-chat-prompt"); + + assertThat(prompt.isChat()) + .as("Expected a chat prompt") + .isTrue(); + + ChatPrompt chatPrompt = prompt.getChat().orElseThrow(); + List messages = chatPrompt.getPrompt(); + + assertThat(messages).isNotEmpty(); + + for (ChatMessageWithPlaceholders msg : messages) { + if (msg.get() instanceof ChatMessage) { + ChatMessage chatMessage = (ChatMessage) msg.get(); + assertThat(chatMessage.getRole()) + .as("role must not be null") + .isNotNull() + .isNotEmpty(); + assertThat(chatMessage.getContent()) + .as("content must not be null") + .isNotNull() + .isNotEmpty(); + } + } + } + + @Test + void fetchTextPrompt_promptIsNonEmpty() { + Prompt prompt = client.prompts().get("test-text-prompt"); + + assertThat(prompt.isText()) + .as("Expected a text prompt") + .isTrue(); + + TextPrompt textPrompt = prompt.getText().orElseThrow(); + + assertThat(textPrompt.getPrompt()) + .as("prompt text must not be null or empty") + .isNotNull() + .isNotEmpty(); + } +} diff --git a/src/test/resources/fixtures/chat_prompt_response.json b/src/test/resources/fixtures/chat_prompt_response.json new file mode 100644 index 0000000..1ba88a3 --- /dev/null +++ b/src/test/resources/fixtures/chat_prompt_response.json @@ -0,0 +1,29 @@ +{ + "id": "a8254424-fdad-49e3-8279-b58cf56834af", + "createdAt": "2026-02-18T14:21:09.711Z", + "updatedAt": "2026-02-18T14:21:09.711Z", + "projectId": "cm19d32ph000bjx8lvbuc94ev", + "createdBy": "cm17uncnj000214d9hu45bx77", + "prompt": [ + { + "role": "system", + "content": "Hello World" + }, + { + "name": "username", + "type": "placeholder" + } + ], + "name": "test-chat-prompt", + "version": 1, + "type": "chat", + "isActive": true, + "config": {}, + "tags": [], + "labels": [ + "production", + "latest" + ], + "commitMessage": null, + "resolutionGraph": null +} \ No newline at end of file diff --git a/src/test/resources/fixtures/text_prompt_response.json b/src/test/resources/fixtures/text_prompt_response.json new file mode 100644 index 0000000..f3d5a72 --- /dev/null +++ b/src/test/resources/fixtures/text_prompt_response.json @@ -0,0 +1,20 @@ +{ + "id": "62985895-210b-47f1-bedf-34ac28ac6db4", + "createdAt": "2026-02-18T14:21:25.156Z", + "updatedAt": "2026-02-18T14:21:25.156Z", + "projectId": "cm19d32ph000bjx8lvbuc94ev", + "createdBy": "cm17uncnj000214d9hu45bx77", + "prompt": "Hello World", + "name": "test-text-prompt", + "version": 1, + "type": "text", + "isActive": true, + "config": {}, + "tags": [], + "labels": [ + "production", + "latest" + ], + "commitMessage": null, + "resolutionGraph": null +} \ No newline at end of file