diff --git a/.stats.yml b/.stats.yml index 47c8d16..35ccd5b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 9 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic-73443ebfebee64b8ec0ebbacd2521d6b6aa900e9526ec97abdcbcff0c0955d9b.yml +configured_endpoints: 17 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic-be055148d227480fcacc9086c37ac8009dcb487731069ada51af35044f65bee4.yml diff --git a/README.md b/README.md index cf01fb7..b8d65ca 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ if (field.isMissing()) { Sometimes, the server response may include additional properties that are not yet available in this library's types. You can access them using the model's `_additionalProperties` method: ```java -JsonValue secret = completion._additionalProperties().get("secret_field"); +JsonValue secret = apiErrorObject._additionalProperties().get("secret_field"); ``` --- diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClient.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClient.kt index 982e844..634e8f0 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClient.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClient.kt @@ -5,6 +5,7 @@ package com.anthropic.client import com.anthropic.services.blocking.BetaService import com.anthropic.services.blocking.CompletionService import com.anthropic.services.blocking.MessageService +import com.anthropic.services.blocking.ModelService interface AnthropicClient { @@ -14,5 +15,7 @@ interface AnthropicClient { fun messages(): MessageService + fun models(): ModelService + fun beta(): BetaService } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsync.kt index 8fc1d3a..bc9af30 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsync.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsync.kt @@ -5,6 +5,7 @@ package com.anthropic.client import com.anthropic.services.async.BetaServiceAsync import com.anthropic.services.async.CompletionServiceAsync import com.anthropic.services.async.MessageServiceAsync +import com.anthropic.services.async.ModelServiceAsync interface AnthropicClientAsync { @@ -14,5 +15,7 @@ interface AnthropicClientAsync { fun messages(): MessageServiceAsync + fun models(): ModelServiceAsync + fun beta(): BetaServiceAsync } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsyncImpl.kt index 5f590f8..99adf09 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsyncImpl.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientAsyncImpl.kt @@ -10,6 +10,8 @@ import com.anthropic.services.async.CompletionServiceAsync import com.anthropic.services.async.CompletionServiceAsyncImpl import com.anthropic.services.async.MessageServiceAsync import com.anthropic.services.async.MessageServiceAsyncImpl +import com.anthropic.services.async.ModelServiceAsync +import com.anthropic.services.async.ModelServiceAsyncImpl class AnthropicClientAsyncImpl constructor( @@ -35,6 +37,10 @@ constructor( MessageServiceAsyncImpl(clientOptionsWithUserAgent) } + private val models: ModelServiceAsync by lazy { + ModelServiceAsyncImpl(clientOptionsWithUserAgent) + } + private val beta: BetaServiceAsync by lazy { BetaServiceAsyncImpl(clientOptionsWithUserAgent) } override fun sync(): AnthropicClient = sync @@ -43,5 +49,7 @@ constructor( override fun messages(): MessageServiceAsync = messages + override fun models(): ModelServiceAsync = models + override fun beta(): BetaServiceAsync = beta } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientImpl.kt index e255db9..7c44418 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientImpl.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/client/AnthropicClientImpl.kt @@ -10,6 +10,8 @@ import com.anthropic.services.blocking.CompletionService import com.anthropic.services.blocking.CompletionServiceImpl import com.anthropic.services.blocking.MessageService import com.anthropic.services.blocking.MessageServiceImpl +import com.anthropic.services.blocking.ModelService +import com.anthropic.services.blocking.ModelServiceImpl class AnthropicClientImpl constructor( @@ -33,6 +35,8 @@ constructor( private val messages: MessageService by lazy { MessageServiceImpl(clientOptionsWithUserAgent) } + private val models: ModelService by lazy { ModelServiceImpl(clientOptionsWithUserAgent) } + private val beta: BetaService by lazy { BetaServiceImpl(clientOptionsWithUserAgent) } override fun async(): AnthropicClientAsync = async @@ -41,5 +45,7 @@ constructor( override fun messages(): MessageService = messages + override fun models(): ModelService = models + override fun beta(): BetaService = beta } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ApiErrorObject.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ApiErrorObject.kt new file mode 100644 index 0000000..3a34056 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ApiErrorObject.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = ApiErrorObject.Builder::class) +@NoAutoDetect +class ApiErrorObject +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): ApiErrorObject = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(apiErrorObject: ApiErrorObject) = apply { + this.type = apiErrorObject.type + this.message = apiErrorObject.message + additionalProperties(apiErrorObject.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): ApiErrorObject = + ApiErrorObject( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val API_ERROR = of("api_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + API_ERROR, + } + + enum class Value { + API_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + API_ERROR -> Value.API_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + API_ERROR -> Known.API_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ApiErrorObject && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ApiErrorObject{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/AuthenticationError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/AuthenticationError.kt new file mode 100644 index 0000000..02a0b5c --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/AuthenticationError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = AuthenticationError.Builder::class) +@NoAutoDetect +class AuthenticationError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): AuthenticationError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(authenticationError: AuthenticationError) = apply { + this.type = authenticationError.type + this.message = authenticationError.message + additionalProperties(authenticationError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): AuthenticationError = + AuthenticationError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val AUTHENTICATION_ERROR = of("authentication_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + AUTHENTICATION_ERROR, + } + + enum class Value { + AUTHENTICATION_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + AUTHENTICATION_ERROR -> Value.AUTHENTICATION_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + AUTHENTICATION_ERROR -> Known.AUTHENTICATION_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is AuthenticationError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "AuthenticationError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/Base64PdfSource.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/Base64PdfSource.kt new file mode 100644 index 0000000..6cc00a8 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/Base64PdfSource.kt @@ -0,0 +1,238 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = Base64PdfSource.Builder::class) +@NoAutoDetect +class Base64PdfSource +private constructor( + private val type: JsonField, + private val mediaType: JsonField, + private val data: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun mediaType(): MediaType = mediaType.getRequired("media_type") + + fun data(): String = data.getRequired("data") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("media_type") @ExcludeMissing fun _mediaType() = mediaType + + @JsonProperty("data") @ExcludeMissing fun _data() = data + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Base64PdfSource = apply { + if (!validated) { + type() + mediaType() + data() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var mediaType: JsonField = JsonMissing.of() + private var data: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(base64PdfSource: Base64PdfSource) = apply { + this.type = base64PdfSource.type + this.mediaType = base64PdfSource.mediaType + this.data = base64PdfSource.data + additionalProperties(base64PdfSource.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun mediaType(mediaType: MediaType) = mediaType(JsonField.of(mediaType)) + + @JsonProperty("media_type") + @ExcludeMissing + fun mediaType(mediaType: JsonField) = apply { this.mediaType = mediaType } + + fun data(data: String) = data(JsonField.of(data)) + + @JsonProperty("data") + @ExcludeMissing + fun data(data: JsonField) = apply { this.data = data } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Base64PdfSource = + Base64PdfSource( + type, + mediaType, + data, + additionalProperties.toImmutable(), + ) + } + + class MediaType + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val APPLICATION_PDF = of("application/pdf") + + @JvmStatic fun of(value: String) = MediaType(JsonField.of(value)) + } + + enum class Known { + APPLICATION_PDF, + } + + enum class Value { + APPLICATION_PDF, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + APPLICATION_PDF -> Value.APPLICATION_PDF + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + APPLICATION_PDF -> Known.APPLICATION_PDF + else -> throw AnthropicInvalidDataException("Unknown MediaType: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MediaType && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val BASE64 = of("base64") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + BASE64, + } + + enum class Value { + BASE64, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + BASE64 -> Value.BASE64 + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + BASE64 -> Known.BASE64 + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Base64PdfSource && type == other.type && mediaType == other.mediaType && data == other.data && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, mediaType, data, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Base64PdfSource{type=$type, mediaType=$mediaType, data=$data, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaBillingError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaBillingError.kt new file mode 100644 index 0000000..792daa4 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaBillingError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = BetaBillingError.Builder::class) +@NoAutoDetect +class BetaBillingError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): BetaBillingError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(betaBillingError: BetaBillingError) = apply { + this.type = betaBillingError.type + this.message = betaBillingError.message + additionalProperties(betaBillingError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): BetaBillingError = + BetaBillingError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val BILLING_ERROR = of("billing_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + BILLING_ERROR, + } + + enum class Value { + BILLING_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + BILLING_ERROR -> Value.BILLING_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + BILLING_ERROR -> Known.BILLING_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BetaBillingError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BetaBillingError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaError.kt index fe03975..2ba2e09 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaError.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaError.kt @@ -24,9 +24,11 @@ class BetaError private constructor( private val betaInvalidRequestError: BetaInvalidRequestError? = null, private val betaAuthenticationError: BetaAuthenticationError? = null, + private val betaBillingError: BetaBillingError? = null, private val betaPermissionError: BetaPermissionError? = null, private val betaNotFoundError: BetaNotFoundError? = null, private val betaRateLimitError: BetaRateLimitError? = null, + private val betaGatewayTimeoutError: BetaGatewayTimeoutError? = null, private val betaApiError: BetaApiError? = null, private val betaOverloadedError: BetaOverloadedError? = null, private val _json: JsonValue? = null, @@ -40,6 +42,8 @@ private constructor( fun betaAuthenticationError(): Optional = Optional.ofNullable(betaAuthenticationError) + fun betaBillingError(): Optional = Optional.ofNullable(betaBillingError) + fun betaPermissionError(): Optional = Optional.ofNullable(betaPermissionError) @@ -47,6 +51,9 @@ private constructor( fun betaRateLimitError(): Optional = Optional.ofNullable(betaRateLimitError) + fun betaGatewayTimeoutError(): Optional = + Optional.ofNullable(betaGatewayTimeoutError) + fun betaApiError(): Optional = Optional.ofNullable(betaApiError) fun betaOverloadedError(): Optional = @@ -56,12 +63,16 @@ private constructor( fun isBetaAuthenticationError(): Boolean = betaAuthenticationError != null + fun isBetaBillingError(): Boolean = betaBillingError != null + fun isBetaPermissionError(): Boolean = betaPermissionError != null fun isBetaNotFoundError(): Boolean = betaNotFoundError != null fun isBetaRateLimitError(): Boolean = betaRateLimitError != null + fun isBetaGatewayTimeoutError(): Boolean = betaGatewayTimeoutError != null + fun isBetaApiError(): Boolean = betaApiError != null fun isBetaOverloadedError(): Boolean = betaOverloadedError != null @@ -72,6 +83,8 @@ private constructor( fun asBetaAuthenticationError(): BetaAuthenticationError = betaAuthenticationError.getOrThrow("betaAuthenticationError") + fun asBetaBillingError(): BetaBillingError = betaBillingError.getOrThrow("betaBillingError") + fun asBetaPermissionError(): BetaPermissionError = betaPermissionError.getOrThrow("betaPermissionError") @@ -80,6 +93,9 @@ private constructor( fun asBetaRateLimitError(): BetaRateLimitError = betaRateLimitError.getOrThrow("betaRateLimitError") + fun asBetaGatewayTimeoutError(): BetaGatewayTimeoutError = + betaGatewayTimeoutError.getOrThrow("betaGatewayTimeoutError") + fun asBetaApiError(): BetaApiError = betaApiError.getOrThrow("betaApiError") fun asBetaOverloadedError(): BetaOverloadedError = @@ -93,9 +109,12 @@ private constructor( visitor.visitBetaInvalidRequestError(betaInvalidRequestError) betaAuthenticationError != null -> visitor.visitBetaAuthenticationError(betaAuthenticationError) + betaBillingError != null -> visitor.visitBetaBillingError(betaBillingError) betaPermissionError != null -> visitor.visitBetaPermissionError(betaPermissionError) betaNotFoundError != null -> visitor.visitBetaNotFoundError(betaNotFoundError) betaRateLimitError != null -> visitor.visitBetaRateLimitError(betaRateLimitError) + betaGatewayTimeoutError != null -> + visitor.visitBetaGatewayTimeoutError(betaGatewayTimeoutError) betaApiError != null -> visitor.visitBetaApiError(betaApiError) betaOverloadedError != null -> visitor.visitBetaOverloadedError(betaOverloadedError) else -> visitor.unknown(_json) @@ -107,9 +126,11 @@ private constructor( if ( betaInvalidRequestError == null && betaAuthenticationError == null && + betaBillingError == null && betaPermissionError == null && betaNotFoundError == null && betaRateLimitError == null && + betaGatewayTimeoutError == null && betaApiError == null && betaOverloadedError == null ) { @@ -117,9 +138,11 @@ private constructor( } betaInvalidRequestError?.validate() betaAuthenticationError?.validate() + betaBillingError?.validate() betaPermissionError?.validate() betaNotFoundError?.validate() betaRateLimitError?.validate() + betaGatewayTimeoutError?.validate() betaApiError?.validate() betaOverloadedError?.validate() validated = true @@ -131,10 +154,10 @@ private constructor( return true } - return /* spotless:off */ other is BetaError && betaInvalidRequestError == other.betaInvalidRequestError && betaAuthenticationError == other.betaAuthenticationError && betaPermissionError == other.betaPermissionError && betaNotFoundError == other.betaNotFoundError && betaRateLimitError == other.betaRateLimitError && betaApiError == other.betaApiError && betaOverloadedError == other.betaOverloadedError /* spotless:on */ + return /* spotless:off */ other is BetaError && betaInvalidRequestError == other.betaInvalidRequestError && betaAuthenticationError == other.betaAuthenticationError && betaBillingError == other.betaBillingError && betaPermissionError == other.betaPermissionError && betaNotFoundError == other.betaNotFoundError && betaRateLimitError == other.betaRateLimitError && betaGatewayTimeoutError == other.betaGatewayTimeoutError && betaApiError == other.betaApiError && betaOverloadedError == other.betaOverloadedError /* spotless:on */ } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(betaInvalidRequestError, betaAuthenticationError, betaPermissionError, betaNotFoundError, betaRateLimitError, betaApiError, betaOverloadedError) /* spotless:on */ + override fun hashCode(): Int = /* spotless:off */ Objects.hash(betaInvalidRequestError, betaAuthenticationError, betaBillingError, betaPermissionError, betaNotFoundError, betaRateLimitError, betaGatewayTimeoutError, betaApiError, betaOverloadedError) /* spotless:on */ override fun toString(): String = when { @@ -142,9 +165,12 @@ private constructor( "BetaError{betaInvalidRequestError=$betaInvalidRequestError}" betaAuthenticationError != null -> "BetaError{betaAuthenticationError=$betaAuthenticationError}" + betaBillingError != null -> "BetaError{betaBillingError=$betaBillingError}" betaPermissionError != null -> "BetaError{betaPermissionError=$betaPermissionError}" betaNotFoundError != null -> "BetaError{betaNotFoundError=$betaNotFoundError}" betaRateLimitError != null -> "BetaError{betaRateLimitError=$betaRateLimitError}" + betaGatewayTimeoutError != null -> + "BetaError{betaGatewayTimeoutError=$betaGatewayTimeoutError}" betaApiError != null -> "BetaError{betaApiError=$betaApiError}" betaOverloadedError != null -> "BetaError{betaOverloadedError=$betaOverloadedError}" _json != null -> "BetaError{_unknown=$_json}" @@ -161,6 +187,10 @@ private constructor( fun ofBetaAuthenticationError(betaAuthenticationError: BetaAuthenticationError) = BetaError(betaAuthenticationError = betaAuthenticationError) + @JvmStatic + fun ofBetaBillingError(betaBillingError: BetaBillingError) = + BetaError(betaBillingError = betaBillingError) + @JvmStatic fun ofBetaPermissionError(betaPermissionError: BetaPermissionError) = BetaError(betaPermissionError = betaPermissionError) @@ -173,6 +203,10 @@ private constructor( fun ofBetaRateLimitError(betaRateLimitError: BetaRateLimitError) = BetaError(betaRateLimitError = betaRateLimitError) + @JvmStatic + fun ofBetaGatewayTimeoutError(betaGatewayTimeoutError: BetaGatewayTimeoutError) = + BetaError(betaGatewayTimeoutError = betaGatewayTimeoutError) + @JvmStatic fun ofBetaApiError(betaApiError: BetaApiError) = BetaError(betaApiError = betaApiError) @@ -187,12 +221,16 @@ private constructor( fun visitBetaAuthenticationError(betaAuthenticationError: BetaAuthenticationError): T + fun visitBetaBillingError(betaBillingError: BetaBillingError): T + fun visitBetaPermissionError(betaPermissionError: BetaPermissionError): T fun visitBetaNotFoundError(betaNotFoundError: BetaNotFoundError): T fun visitBetaRateLimitError(betaRateLimitError: BetaRateLimitError): T + fun visitBetaGatewayTimeoutError(betaGatewayTimeoutError: BetaGatewayTimeoutError): T + fun visitBetaApiError(betaApiError: BetaApiError): T fun visitBetaOverloadedError(betaOverloadedError: BetaOverloadedError): T @@ -225,6 +263,12 @@ private constructor( return BetaError(betaAuthenticationError = it, _json = json) } } + "billing_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return BetaError(betaBillingError = it, _json = json) + } + } "permission_error" -> { tryDeserialize(node, jacksonTypeRef()) { it.validate() } ?.let { @@ -243,6 +287,14 @@ private constructor( return BetaError(betaRateLimitError = it, _json = json) } } + "timeout_error" -> { + tryDeserialize(node, jacksonTypeRef()) { + it.validate() + } + ?.let { + return BetaError(betaGatewayTimeoutError = it, _json = json) + } + } "api_error" -> { tryDeserialize(node, jacksonTypeRef()) { it.validate() } ?.let { @@ -273,10 +325,13 @@ private constructor( generator.writeObject(value.betaInvalidRequestError) value.betaAuthenticationError != null -> generator.writeObject(value.betaAuthenticationError) + value.betaBillingError != null -> generator.writeObject(value.betaBillingError) value.betaPermissionError != null -> generator.writeObject(value.betaPermissionError) value.betaNotFoundError != null -> generator.writeObject(value.betaNotFoundError) value.betaRateLimitError != null -> generator.writeObject(value.betaRateLimitError) + value.betaGatewayTimeoutError != null -> + generator.writeObject(value.betaGatewayTimeoutError) value.betaApiError != null -> generator.writeObject(value.betaApiError) value.betaOverloadedError != null -> generator.writeObject(value.betaOverloadedError) diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaGatewayTimeoutError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaGatewayTimeoutError.kt new file mode 100644 index 0000000..11de7bf --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaGatewayTimeoutError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = BetaGatewayTimeoutError.Builder::class) +@NoAutoDetect +class BetaGatewayTimeoutError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): BetaGatewayTimeoutError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(betaGatewayTimeoutError: BetaGatewayTimeoutError) = apply { + this.type = betaGatewayTimeoutError.type + this.message = betaGatewayTimeoutError.message + additionalProperties(betaGatewayTimeoutError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): BetaGatewayTimeoutError = + BetaGatewayTimeoutError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TIMEOUT_ERROR = of("timeout_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + TIMEOUT_ERROR, + } + + enum class Value { + TIMEOUT_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + TIMEOUT_ERROR -> Value.TIMEOUT_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + TIMEOUT_ERROR -> Known.TIMEOUT_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BetaGatewayTimeoutError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BetaGatewayTimeoutError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaMessageBatchListParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaMessageBatchListParams.kt index e4d8f5f..44cc0b1 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaMessageBatchListParams.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaMessageBatchListParams.kt @@ -91,7 +91,7 @@ constructor( /** * Number of items to return per page. * - * Defaults to `20`. Ranges from `1` to `100`. + * Defaults to `20`. Ranges from `1` to `1000`. */ fun limit(limit: Long) = apply { this.limit = limit } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelInfo.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelInfo.kt new file mode 100644 index 0000000..b25996c --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelInfo.kt @@ -0,0 +1,245 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.time.OffsetDateTime +import java.util.Objects + +@JsonDeserialize(builder = BetaModelInfo.Builder::class) +@NoAutoDetect +class BetaModelInfo +private constructor( + private val type: JsonField, + private val id: JsonField, + private val displayName: JsonField, + private val createdAt: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + /** + * Object type. + * + * For Models, this is always `"model"`. + */ + fun type(): Type = type.getRequired("type") + + /** Unique model identifier. */ + fun id(): String = id.getRequired("id") + + /** A human-readable name for the model. */ + fun displayName(): String = displayName.getRequired("display_name") + + /** + * RFC 3339 datetime string representing the time at which the model was released. May be set to + * an epoch value if the release date is unknown. + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * Object type. + * + * For Models, this is always `"model"`. + */ + @JsonProperty("type") @ExcludeMissing fun _type() = type + + /** Unique model identifier. */ + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** A human-readable name for the model. */ + @JsonProperty("display_name") @ExcludeMissing fun _displayName() = displayName + + /** + * RFC 3339 datetime string representing the time at which the model was released. May be set to + * an epoch value if the release date is unknown. + */ + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): BetaModelInfo = apply { + if (!validated) { + type() + id() + displayName() + createdAt() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var id: JsonField = JsonMissing.of() + private var displayName: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(betaModelInfo: BetaModelInfo) = apply { + this.type = betaModelInfo.type + this.id = betaModelInfo.id + this.displayName = betaModelInfo.displayName + this.createdAt = betaModelInfo.createdAt + additionalProperties(betaModelInfo.additionalProperties) + } + + /** + * Object type. + * + * For Models, this is always `"model"`. + */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Object type. + * + * For Models, this is always `"model"`. + */ + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + /** Unique model identifier. */ + fun id(id: String) = id(JsonField.of(id)) + + /** Unique model identifier. */ + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** A human-readable name for the model. */ + fun displayName(displayName: String) = displayName(JsonField.of(displayName)) + + /** A human-readable name for the model. */ + @JsonProperty("display_name") + @ExcludeMissing + fun displayName(displayName: JsonField) = apply { this.displayName = displayName } + + /** + * RFC 3339 datetime string representing the time at which the model was released. May be + * set to an epoch value if the release date is unknown. + */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * RFC 3339 datetime string representing the time at which the model was released. May be + * set to an epoch value if the release date is unknown. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): BetaModelInfo = + BetaModelInfo( + type, + id, + displayName, + createdAt, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val MODEL = of("model") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + MODEL, + } + + enum class Value { + MODEL, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + MODEL -> Value.MODEL + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + MODEL -> Known.MODEL + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BetaModelInfo && type == other.type && id == other.id && displayName == other.displayName && createdAt == other.createdAt && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, id, displayName, createdAt, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BetaModelInfo{type=$type, id=$id, displayName=$displayName, createdAt=$createdAt, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListPage.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListPage.kt new file mode 100644 index 0000000..ebf5dc0 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListPage.kt @@ -0,0 +1,230 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.services.blocking.beta.ModelService +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class BetaModelListPage +private constructor( + private val modelsService: ModelService, + private val params: BetaModelListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun hasMore(): Optional = response().hasMore() + + fun firstId(): Optional = response().firstId() + + fun lastId(): Optional = response().lastId() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BetaModelListPage && modelsService == other.modelsService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(modelsService, params, response) /* spotless:on */ + + override fun toString() = + "BetaModelListPage{modelsService=$modelsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + if (data().isEmpty()) { + return false + } + + return lastId().isPresent + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + BetaModelListParams.builder() + .from(params) + .apply { lastId().ifPresent { this.afterId(it) } } + .build() + ) + } + + fun getNextPage(): Optional { + return getNextPageParams().map { modelsService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(modelsService: ModelService, params: BetaModelListParams, response: Response) = + BetaModelListPage( + modelsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val hasMore: JsonField, + private val firstId: JsonField, + private val lastId: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun hasMore(): Optional = Optional.ofNullable(hasMore.getNullable("has_more")) + + fun firstId(): Optional = Optional.ofNullable(firstId.getNullable("first_id")) + + fun lastId(): Optional = Optional.ofNullable(lastId.getNullable("last_id")) + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("has_more") + fun _hasMore(): Optional> = Optional.ofNullable(hasMore) + + @JsonProperty("first_id") + fun _firstId(): Optional> = Optional.ofNullable(firstId) + + @JsonProperty("last_id") + fun _lastId(): Optional> = Optional.ofNullable(lastId) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + hasMore() + firstId() + lastId() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && data == other.data && hasMore == other.hasMore && firstId == other.firstId && lastId == other.lastId && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, hasMore, firstId, lastId, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{data=$data, hasMore=$hasMore, firstId=$firstId, lastId=$lastId, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var hasMore: JsonField = JsonMissing.of() + private var firstId: JsonField = JsonMissing.of() + private var lastId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.hasMore = page.hasMore + this.firstId = page.firstId + this.lastId = page.lastId + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun hasMore(hasMore: Boolean) = hasMore(JsonField.of(hasMore)) + + @JsonProperty("has_more") + fun hasMore(hasMore: JsonField) = apply { this.hasMore = hasMore } + + fun firstId(firstId: String) = firstId(JsonField.of(firstId)) + + @JsonProperty("first_id") + fun firstId(firstId: JsonField) = apply { this.firstId = firstId } + + fun lastId(lastId: String) = lastId(JsonField.of(lastId)) + + @JsonProperty("last_id") + fun lastId(lastId: JsonField) = apply { this.lastId = lastId } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + hasMore, + firstId, + lastId, + additionalProperties.toImmutable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: BetaModelListPage, + ) : Iterable { + + override fun iterator(): Iterator = iterator { + var page = firstPage + var index = 0 + while (true) { + while (index < page.data().size) { + yield(page.data()[index++]) + } + page = page.getNextPage().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListPageAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListPageAsync.kt new file mode 100644 index 0000000..6ed49e9 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListPageAsync.kt @@ -0,0 +1,240 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.services.async.beta.ModelServiceAsync +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class BetaModelListPageAsync +private constructor( + private val modelsService: ModelServiceAsync, + private val params: BetaModelListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun hasMore(): Optional = response().hasMore() + + fun firstId(): Optional = response().firstId() + + fun lastId(): Optional = response().lastId() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BetaModelListPageAsync && modelsService == other.modelsService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(modelsService, params, response) /* spotless:on */ + + override fun toString() = + "BetaModelListPageAsync{modelsService=$modelsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + if (data().isEmpty()) { + return false + } + + return lastId().isPresent + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + BetaModelListParams.builder() + .from(params) + .apply { lastId().ifPresent { this.afterId(it) } } + .build() + ) + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { modelsService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(modelsService: ModelServiceAsync, params: BetaModelListParams, response: Response) = + BetaModelListPageAsync( + modelsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val hasMore: JsonField, + private val firstId: JsonField, + private val lastId: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun hasMore(): Optional = Optional.ofNullable(hasMore.getNullable("has_more")) + + fun firstId(): Optional = Optional.ofNullable(firstId.getNullable("first_id")) + + fun lastId(): Optional = Optional.ofNullable(lastId.getNullable("last_id")) + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("has_more") + fun _hasMore(): Optional> = Optional.ofNullable(hasMore) + + @JsonProperty("first_id") + fun _firstId(): Optional> = Optional.ofNullable(firstId) + + @JsonProperty("last_id") + fun _lastId(): Optional> = Optional.ofNullable(lastId) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + hasMore() + firstId() + lastId() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && data == other.data && hasMore == other.hasMore && firstId == other.firstId && lastId == other.lastId && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, hasMore, firstId, lastId, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{data=$data, hasMore=$hasMore, firstId=$firstId, lastId=$lastId, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var hasMore: JsonField = JsonMissing.of() + private var firstId: JsonField = JsonMissing.of() + private var lastId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.hasMore = page.hasMore + this.firstId = page.firstId + this.lastId = page.lastId + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun hasMore(hasMore: Boolean) = hasMore(JsonField.of(hasMore)) + + @JsonProperty("has_more") + fun hasMore(hasMore: JsonField) = apply { this.hasMore = hasMore } + + fun firstId(firstId: String) = firstId(JsonField.of(firstId)) + + @JsonProperty("first_id") + fun firstId(firstId: JsonField) = apply { this.firstId = firstId } + + fun lastId(lastId: String) = lastId(JsonField.of(lastId)) + + @JsonProperty("last_id") + fun lastId(lastId: JsonField) = apply { this.lastId = lastId } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + hasMore, + firstId, + lastId, + additionalProperties.toImmutable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: BetaModelListPageAsync, + ) { + + fun forEach(action: Predicate, executor: Executor): CompletableFuture { + fun CompletableFuture>.forEach( + action: (BetaModelInfo) -> Boolean, + executor: Executor + ): CompletableFuture = + thenComposeAsync( + { page -> + page + .filter { it.data().all(action) } + .map { it.getNextPage().forEach(action, executor) } + .orElseGet { CompletableFuture.completedFuture(null) } + }, + executor + ) + return CompletableFuture.completedFuture(Optional.of(firstPage)) + .forEach(action::test, executor) + } + + fun toList(executor: Executor): CompletableFuture> { + val values = mutableListOf() + return forEach(values::add, executor).thenApply { values } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListParams.kt new file mode 100644 index 0000000..2f0a9c8 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelListParams.kt @@ -0,0 +1,206 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import java.util.Objects +import java.util.Optional + +class BetaModelListParams +constructor( + private val afterId: String?, + private val beforeId: String?, + private val limit: Long?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) { + + fun afterId(): Optional = Optional.ofNullable(afterId) + + fun beforeId(): Optional = Optional.ofNullable(beforeId) + + fun limit(): Optional = Optional.ofNullable(limit) + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic + internal fun getQueryParams(): QueryParams { + val queryParams = QueryParams.builder() + this.afterId?.let { queryParams.put("after_id", listOf(it.toString())) } + this.beforeId?.let { queryParams.put("before_id", listOf(it.toString())) } + this.limit?.let { queryParams.put("limit", listOf(it.toString())) } + queryParams.putAll(additionalQueryParams) + return queryParams.build() + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var afterId: String? = null + private var beforeId: String? = null + private var limit: Long? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(betaModelListParams: BetaModelListParams) = apply { + afterId = betaModelListParams.afterId + beforeId = betaModelListParams.beforeId + limit = betaModelListParams.limit + additionalHeaders = betaModelListParams.additionalHeaders.toBuilder() + additionalQueryParams = betaModelListParams.additionalQueryParams.toBuilder() + } + + /** + * ID of the object to use as a cursor for pagination. When provided, returns the page of + * results immediately after this object. + */ + fun afterId(afterId: String) = apply { this.afterId = afterId } + + /** + * ID of the object to use as a cursor for pagination. When provided, returns the page of + * results immediately before this object. + */ + fun beforeId(beforeId: String) = apply { this.beforeId = beforeId } + + /** + * Number of items to return per page. + * + * Defaults to `20`. Ranges from `1` to `1000`. + */ + fun limit(limit: Long) = apply { this.limit = limit } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun build(): BetaModelListParams = + BetaModelListParams( + afterId, + beforeId, + limit, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BetaModelListParams && afterId == other.afterId && beforeId == other.beforeId && limit == other.limit && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(afterId, beforeId, limit, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "BetaModelListParams{afterId=$afterId, beforeId=$beforeId, limit=$limit, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelRetrieveParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelRetrieveParams.kt new file mode 100644 index 0000000..5af746f --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaModelRetrieveParams.kt @@ -0,0 +1,176 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import java.util.Objects + +class BetaModelRetrieveParams +constructor( + private val modelId: String, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) { + + fun modelId(): String = modelId + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic internal fun getQueryParams(): QueryParams = additionalQueryParams + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> modelId + else -> "" + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var modelId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(betaModelRetrieveParams: BetaModelRetrieveParams) = apply { + modelId = betaModelRetrieveParams.modelId + additionalHeaders = betaModelRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = betaModelRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Model identifier or alias. */ + fun modelId(modelId: String) = apply { this.modelId = modelId } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun build(): BetaModelRetrieveParams = + BetaModelRetrieveParams( + checkNotNull(modelId) { "`modelId` is required but was not set" }, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BetaModelRetrieveParams && modelId == other.modelId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(modelId, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "BetaModelRetrieveParams{modelId=$modelId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaRawContentBlockDeltaEvent.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaRawContentBlockDeltaEvent.kt index d270e30..cf23a8c 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaRawContentBlockDeltaEvent.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaRawContentBlockDeltaEvent.kt @@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.util.Objects import java.util.Optional -import kotlin.jvm.optionals.getOrNull @JsonDeserialize(builder = BetaRawContentBlockDeltaEvent.Builder::class) @NoAutoDetect @@ -217,22 +216,15 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Delta { val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text_delta" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Delta(betaTextDelta = it, _json = json) - } + + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return Delta(betaTextDelta = it, _json = json) } - "input_json_delta" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Delta(betaInputJsonDelta = it, _json = json) - } + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return Delta(betaInputJsonDelta = it, _json = json) } - } return Delta(_json = json) } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BillingError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BillingError.kt new file mode 100644 index 0000000..5bc870b --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/BillingError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = BillingError.Builder::class) +@NoAutoDetect +class BillingError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): BillingError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(billingError: BillingError) = apply { + this.type = billingError.type + this.message = billingError.message + additionalProperties(billingError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): BillingError = + BillingError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val BILLING_ERROR = of("billing_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + BILLING_ERROR, + } + + enum class Value { + BILLING_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + BILLING_ERROR -> Value.BILLING_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + BILLING_ERROR -> Known.BILLING_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is BillingError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "BillingError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaCacheControlEphemeral.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/CacheControlEphemeral.kt similarity index 80% rename from anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaCacheControlEphemeral.kt rename to anthropic-java-core/src/main/kotlin/com/anthropic/models/CacheControlEphemeral.kt index 6190d17..6cbf597 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaCacheControlEphemeral.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/CacheControlEphemeral.kt @@ -17,9 +17,9 @@ import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects -@JsonDeserialize(builder = PromptCachingBetaCacheControlEphemeral.Builder::class) +@JsonDeserialize(builder = CacheControlEphemeral.Builder::class) @NoAutoDetect -class PromptCachingBetaCacheControlEphemeral +class CacheControlEphemeral private constructor( private val type: JsonField, private val additionalProperties: Map, @@ -35,7 +35,7 @@ private constructor( @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - fun validate(): PromptCachingBetaCacheControlEphemeral = apply { + fun validate(): CacheControlEphemeral = apply { if (!validated) { type() validated = true @@ -55,11 +55,9 @@ private constructor( private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from( - promptCachingBetaCacheControlEphemeral: PromptCachingBetaCacheControlEphemeral - ) = apply { - this.type = promptCachingBetaCacheControlEphemeral.type - additionalProperties(promptCachingBetaCacheControlEphemeral.additionalProperties) + internal fun from(cacheControlEphemeral: CacheControlEphemeral) = apply { + this.type = cacheControlEphemeral.type + additionalProperties(cacheControlEphemeral.additionalProperties) } fun type(type: Type) = type(JsonField.of(type)) @@ -82,8 +80,8 @@ private constructor( this.additionalProperties.putAll(additionalProperties) } - fun build(): PromptCachingBetaCacheControlEphemeral = - PromptCachingBetaCacheControlEphemeral(type, additionalProperties.toImmutable()) + fun build(): CacheControlEphemeral = + CacheControlEphemeral(type, additionalProperties.toImmutable()) } class Type @@ -142,7 +140,7 @@ private constructor( return true } - return /* spotless:off */ other is PromptCachingBetaCacheControlEphemeral && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is CacheControlEphemeral && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ @@ -152,5 +150,5 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "PromptCachingBetaCacheControlEphemeral{type=$type, additionalProperties=$additionalProperties}" + "CacheControlEphemeral{type=$type, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ContentBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ContentBlockParam.kt index 636b78c..11ed30a 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ContentBlockParam.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ContentBlockParam.kt @@ -26,6 +26,7 @@ private constructor( private val imageBlockParam: ImageBlockParam? = null, private val toolUseBlockParam: ToolUseBlockParam? = null, private val toolResultBlockParam: ToolResultBlockParam? = null, + private val documentBlockParam: DocumentBlockParam? = null, private val _json: JsonValue? = null, ) { @@ -40,6 +41,8 @@ private constructor( fun toolResultBlockParam(): Optional = Optional.ofNullable(toolResultBlockParam) + fun documentBlockParam(): Optional = Optional.ofNullable(documentBlockParam) + fun isTextBlockParam(): Boolean = textBlockParam != null fun isImageBlockParam(): Boolean = imageBlockParam != null @@ -48,6 +51,8 @@ private constructor( fun isToolResultBlockParam(): Boolean = toolResultBlockParam != null + fun isDocumentBlockParam(): Boolean = documentBlockParam != null + fun asTextBlockParam(): TextBlockParam = textBlockParam.getOrThrow("textBlockParam") fun asImageBlockParam(): ImageBlockParam = imageBlockParam.getOrThrow("imageBlockParam") @@ -57,6 +62,9 @@ private constructor( fun asToolResultBlockParam(): ToolResultBlockParam = toolResultBlockParam.getOrThrow("toolResultBlockParam") + fun asDocumentBlockParam(): DocumentBlockParam = + documentBlockParam.getOrThrow("documentBlockParam") + fun _json(): Optional = Optional.ofNullable(_json) fun accept(visitor: Visitor): T { @@ -65,6 +73,7 @@ private constructor( imageBlockParam != null -> visitor.visitImageBlockParam(imageBlockParam) toolUseBlockParam != null -> visitor.visitToolUseBlockParam(toolUseBlockParam) toolResultBlockParam != null -> visitor.visitToolResultBlockParam(toolResultBlockParam) + documentBlockParam != null -> visitor.visitDocumentBlockParam(documentBlockParam) else -> visitor.unknown(_json) } } @@ -75,7 +84,8 @@ private constructor( textBlockParam == null && imageBlockParam == null && toolUseBlockParam == null && - toolResultBlockParam == null + toolResultBlockParam == null && + documentBlockParam == null ) { throw AnthropicInvalidDataException("Unknown ContentBlockParam: $_json") } @@ -83,6 +93,7 @@ private constructor( imageBlockParam?.validate() toolUseBlockParam?.validate() toolResultBlockParam?.validate() + documentBlockParam?.validate() validated = true } } @@ -92,10 +103,10 @@ private constructor( return true } - return /* spotless:off */ other is ContentBlockParam && textBlockParam == other.textBlockParam && imageBlockParam == other.imageBlockParam && toolUseBlockParam == other.toolUseBlockParam && toolResultBlockParam == other.toolResultBlockParam /* spotless:on */ + return /* spotless:off */ other is ContentBlockParam && textBlockParam == other.textBlockParam && imageBlockParam == other.imageBlockParam && toolUseBlockParam == other.toolUseBlockParam && toolResultBlockParam == other.toolResultBlockParam && documentBlockParam == other.documentBlockParam /* spotless:on */ } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(textBlockParam, imageBlockParam, toolUseBlockParam, toolResultBlockParam) /* spotless:on */ + override fun hashCode(): Int = /* spotless:off */ Objects.hash(textBlockParam, imageBlockParam, toolUseBlockParam, toolResultBlockParam, documentBlockParam) /* spotless:on */ override fun toString(): String = when { @@ -104,6 +115,8 @@ private constructor( toolUseBlockParam != null -> "ContentBlockParam{toolUseBlockParam=$toolUseBlockParam}" toolResultBlockParam != null -> "ContentBlockParam{toolResultBlockParam=$toolResultBlockParam}" + documentBlockParam != null -> + "ContentBlockParam{documentBlockParam=$documentBlockParam}" _json != null -> "ContentBlockParam{_unknown=$_json}" else -> throw IllegalStateException("Invalid ContentBlockParam") } @@ -125,6 +138,10 @@ private constructor( @JvmStatic fun ofToolResultBlockParam(toolResultBlockParam: ToolResultBlockParam) = ContentBlockParam(toolResultBlockParam = toolResultBlockParam) + + @JvmStatic + fun ofDocumentBlockParam(documentBlockParam: DocumentBlockParam) = + ContentBlockParam(documentBlockParam = documentBlockParam) } interface Visitor { @@ -137,6 +154,8 @@ private constructor( fun visitToolResultBlockParam(toolResultBlockParam: ToolResultBlockParam): T + fun visitDocumentBlockParam(documentBlockParam: DocumentBlockParam): T + fun unknown(json: JsonValue?): T { throw AnthropicInvalidDataException("Unknown ContentBlockParam: $json") } @@ -173,6 +192,12 @@ private constructor( return ContentBlockParam(toolResultBlockParam = it, _json = json) } } + "document" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ContentBlockParam(documentBlockParam = it, _json = json) + } + } } return ContentBlockParam(_json = json) @@ -192,6 +217,7 @@ private constructor( value.toolUseBlockParam != null -> generator.writeObject(value.toolUseBlockParam) value.toolResultBlockParam != null -> generator.writeObject(value.toolResultBlockParam) + value.documentBlockParam != null -> generator.writeObject(value.documentBlockParam) value._json != null -> generator.writeObject(value._json) else -> throw IllegalStateException("Invalid ContentBlockParam") } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaTextBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/DocumentBlockParam.kt similarity index 66% rename from anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaTextBlockParam.kt rename to anthropic-java-core/src/main/kotlin/com/anthropic/models/DocumentBlockParam.kt index 59567d2..0ca7d7e 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaTextBlockParam.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/DocumentBlockParam.kt @@ -18,40 +18,40 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects import java.util.Optional -@JsonDeserialize(builder = PromptCachingBetaTextBlockParam.Builder::class) +@JsonDeserialize(builder = DocumentBlockParam.Builder::class) @NoAutoDetect -class PromptCachingBetaTextBlockParam +class DocumentBlockParam private constructor( - private val cacheControl: JsonField, + private val cacheControl: JsonField, private val type: JsonField, - private val text: JsonField, + private val source: JsonField, private val additionalProperties: Map, ) { private var validated: Boolean = false - fun cacheControl(): Optional = + fun cacheControl(): Optional = Optional.ofNullable(cacheControl.getNullable("cache_control")) fun type(): Type = type.getRequired("type") - fun text(): String = text.getRequired("text") + fun source(): Base64PdfSource = source.getRequired("source") @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl @JsonProperty("type") @ExcludeMissing fun _type() = type - @JsonProperty("text") @ExcludeMissing fun _text() = text + @JsonProperty("source") @ExcludeMissing fun _source() = source @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - fun validate(): PromptCachingBetaTextBlockParam = apply { + fun validate(): DocumentBlockParam = apply { if (!validated) { cacheControl().map { it.validate() } type() - text() + source().validate() validated = true } } @@ -65,27 +65,25 @@ private constructor( class Builder { - private var cacheControl: JsonField = - JsonMissing.of() + private var cacheControl: JsonField = JsonMissing.of() private var type: JsonField = JsonMissing.of() - private var text: JsonField = JsonMissing.of() + private var source: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(promptCachingBetaTextBlockParam: PromptCachingBetaTextBlockParam) = - apply { - this.cacheControl = promptCachingBetaTextBlockParam.cacheControl - this.type = promptCachingBetaTextBlockParam.type - this.text = promptCachingBetaTextBlockParam.text - additionalProperties(promptCachingBetaTextBlockParam.additionalProperties) - } + internal fun from(documentBlockParam: DocumentBlockParam) = apply { + this.cacheControl = documentBlockParam.cacheControl + this.type = documentBlockParam.type + this.source = documentBlockParam.source + additionalProperties(documentBlockParam.additionalProperties) + } - fun cacheControl(cacheControl: PromptCachingBetaCacheControlEphemeral) = + fun cacheControl(cacheControl: CacheControlEphemeral) = cacheControl(JsonField.of(cacheControl)) @JsonProperty("cache_control") @ExcludeMissing - fun cacheControl(cacheControl: JsonField) = apply { + fun cacheControl(cacheControl: JsonField) = apply { this.cacheControl = cacheControl } @@ -95,11 +93,11 @@ private constructor( @ExcludeMissing fun type(type: JsonField) = apply { this.type = type } - fun text(text: String) = text(JsonField.of(text)) + fun source(source: Base64PdfSource) = source(JsonField.of(source)) - @JsonProperty("text") + @JsonProperty("source") @ExcludeMissing - fun text(text: JsonField) = apply { this.text = text } + fun source(source: JsonField) = apply { this.source = source } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() @@ -115,11 +113,11 @@ private constructor( this.additionalProperties.putAll(additionalProperties) } - fun build(): PromptCachingBetaTextBlockParam = - PromptCachingBetaTextBlockParam( + fun build(): DocumentBlockParam = + DocumentBlockParam( cacheControl, type, - text, + source, additionalProperties.toImmutable(), ) } @@ -134,29 +132,29 @@ private constructor( companion object { - @JvmField val TEXT = of("text") + @JvmField val DOCUMENT = of("document") @JvmStatic fun of(value: String) = Type(JsonField.of(value)) } enum class Known { - TEXT, + DOCUMENT, } enum class Value { - TEXT, + DOCUMENT, _UNKNOWN, } fun value(): Value = when (this) { - TEXT -> Value.TEXT + DOCUMENT -> Value.DOCUMENT else -> Value._UNKNOWN } fun known(): Known = when (this) { - TEXT -> Known.TEXT + DOCUMENT -> Known.DOCUMENT else -> throw AnthropicInvalidDataException("Unknown Type: $value") } @@ -180,15 +178,15 @@ private constructor( return true } - return /* spotless:off */ other is PromptCachingBetaTextBlockParam && cacheControl == other.cacheControl && type == other.type && text == other.text && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is DocumentBlockParam && cacheControl == other.cacheControl && type == other.type && source == other.source && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cacheControl, type, text, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(cacheControl, type, source, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "PromptCachingBetaTextBlockParam{cacheControl=$cacheControl, type=$type, text=$text, additionalProperties=$additionalProperties}" + "DocumentBlockParam{cacheControl=$cacheControl, type=$type, source=$source, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ErrorObject.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ErrorObject.kt new file mode 100644 index 0000000..6cbb523 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ErrorObject.kt @@ -0,0 +1,324 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.BaseDeserializer +import com.anthropic.core.BaseSerializer +import com.anthropic.core.JsonValue +import com.anthropic.core.getOrThrow +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +@JsonDeserialize(using = ErrorObject.Deserializer::class) +@JsonSerialize(using = ErrorObject.Serializer::class) +class ErrorObject +private constructor( + private val invalidRequestError: InvalidRequestError? = null, + private val authenticationError: AuthenticationError? = null, + private val billingError: BillingError? = null, + private val permissionError: PermissionError? = null, + private val notFoundError: NotFoundError? = null, + private val rateLimitError: RateLimitError? = null, + private val gatewayTimeoutError: GatewayTimeoutError? = null, + private val apiErrorObject: ApiErrorObject? = null, + private val overloadedError: OverloadedError? = null, + private val _json: JsonValue? = null, +) { + + private var validated: Boolean = false + + fun invalidRequestError(): Optional = + Optional.ofNullable(invalidRequestError) + + fun authenticationError(): Optional = + Optional.ofNullable(authenticationError) + + fun billingError(): Optional = Optional.ofNullable(billingError) + + fun permissionError(): Optional = Optional.ofNullable(permissionError) + + fun notFoundError(): Optional = Optional.ofNullable(notFoundError) + + fun rateLimitError(): Optional = Optional.ofNullable(rateLimitError) + + fun gatewayTimeoutError(): Optional = + Optional.ofNullable(gatewayTimeoutError) + + fun apiErrorObject(): Optional = Optional.ofNullable(apiErrorObject) + + fun overloadedError(): Optional = Optional.ofNullable(overloadedError) + + fun isInvalidRequestError(): Boolean = invalidRequestError != null + + fun isAuthenticationError(): Boolean = authenticationError != null + + fun isBillingError(): Boolean = billingError != null + + fun isPermissionError(): Boolean = permissionError != null + + fun isNotFoundError(): Boolean = notFoundError != null + + fun isRateLimitError(): Boolean = rateLimitError != null + + fun isGatewayTimeoutError(): Boolean = gatewayTimeoutError != null + + fun isApiErrorObject(): Boolean = apiErrorObject != null + + fun isOverloadedError(): Boolean = overloadedError != null + + fun asInvalidRequestError(): InvalidRequestError = + invalidRequestError.getOrThrow("invalidRequestError") + + fun asAuthenticationError(): AuthenticationError = + authenticationError.getOrThrow("authenticationError") + + fun asBillingError(): BillingError = billingError.getOrThrow("billingError") + + fun asPermissionError(): PermissionError = permissionError.getOrThrow("permissionError") + + fun asNotFoundError(): NotFoundError = notFoundError.getOrThrow("notFoundError") + + fun asRateLimitError(): RateLimitError = rateLimitError.getOrThrow("rateLimitError") + + fun asGatewayTimeoutError(): GatewayTimeoutError = + gatewayTimeoutError.getOrThrow("gatewayTimeoutError") + + fun asApiErrorObject(): ApiErrorObject = apiErrorObject.getOrThrow("apiErrorObject") + + fun asOverloadedError(): OverloadedError = overloadedError.getOrThrow("overloadedError") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + invalidRequestError != null -> visitor.visitInvalidRequestError(invalidRequestError) + authenticationError != null -> visitor.visitAuthenticationError(authenticationError) + billingError != null -> visitor.visitBillingError(billingError) + permissionError != null -> visitor.visitPermissionError(permissionError) + notFoundError != null -> visitor.visitNotFoundError(notFoundError) + rateLimitError != null -> visitor.visitRateLimitError(rateLimitError) + gatewayTimeoutError != null -> visitor.visitGatewayTimeoutError(gatewayTimeoutError) + apiErrorObject != null -> visitor.visitApiErrorObject(apiErrorObject) + overloadedError != null -> visitor.visitOverloadedError(overloadedError) + else -> visitor.unknown(_json) + } + } + + fun validate(): ErrorObject = apply { + if (!validated) { + if ( + invalidRequestError == null && + authenticationError == null && + billingError == null && + permissionError == null && + notFoundError == null && + rateLimitError == null && + gatewayTimeoutError == null && + apiErrorObject == null && + overloadedError == null + ) { + throw AnthropicInvalidDataException("Unknown ErrorObject: $_json") + } + invalidRequestError?.validate() + authenticationError?.validate() + billingError?.validate() + permissionError?.validate() + notFoundError?.validate() + rateLimitError?.validate() + gatewayTimeoutError?.validate() + apiErrorObject?.validate() + overloadedError?.validate() + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ErrorObject && invalidRequestError == other.invalidRequestError && authenticationError == other.authenticationError && billingError == other.billingError && permissionError == other.permissionError && notFoundError == other.notFoundError && rateLimitError == other.rateLimitError && gatewayTimeoutError == other.gatewayTimeoutError && apiErrorObject == other.apiErrorObject && overloadedError == other.overloadedError /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(invalidRequestError, authenticationError, billingError, permissionError, notFoundError, rateLimitError, gatewayTimeoutError, apiErrorObject, overloadedError) /* spotless:on */ + + override fun toString(): String = + when { + invalidRequestError != null -> "ErrorObject{invalidRequestError=$invalidRequestError}" + authenticationError != null -> "ErrorObject{authenticationError=$authenticationError}" + billingError != null -> "ErrorObject{billingError=$billingError}" + permissionError != null -> "ErrorObject{permissionError=$permissionError}" + notFoundError != null -> "ErrorObject{notFoundError=$notFoundError}" + rateLimitError != null -> "ErrorObject{rateLimitError=$rateLimitError}" + gatewayTimeoutError != null -> "ErrorObject{gatewayTimeoutError=$gatewayTimeoutError}" + apiErrorObject != null -> "ErrorObject{apiErrorObject=$apiErrorObject}" + overloadedError != null -> "ErrorObject{overloadedError=$overloadedError}" + _json != null -> "ErrorObject{_unknown=$_json}" + else -> throw IllegalStateException("Invalid ErrorObject") + } + + companion object { + + @JvmStatic + fun ofInvalidRequestError(invalidRequestError: InvalidRequestError) = + ErrorObject(invalidRequestError = invalidRequestError) + + @JvmStatic + fun ofAuthenticationError(authenticationError: AuthenticationError) = + ErrorObject(authenticationError = authenticationError) + + @JvmStatic + fun ofBillingError(billingError: BillingError) = ErrorObject(billingError = billingError) + + @JvmStatic + fun ofPermissionError(permissionError: PermissionError) = + ErrorObject(permissionError = permissionError) + + @JvmStatic + fun ofNotFoundError(notFoundError: NotFoundError) = + ErrorObject(notFoundError = notFoundError) + + @JvmStatic + fun ofRateLimitError(rateLimitError: RateLimitError) = + ErrorObject(rateLimitError = rateLimitError) + + @JvmStatic + fun ofGatewayTimeoutError(gatewayTimeoutError: GatewayTimeoutError) = + ErrorObject(gatewayTimeoutError = gatewayTimeoutError) + + @JvmStatic + fun ofApiErrorObject(apiErrorObject: ApiErrorObject) = + ErrorObject(apiErrorObject = apiErrorObject) + + @JvmStatic + fun ofOverloadedError(overloadedError: OverloadedError) = + ErrorObject(overloadedError = overloadedError) + } + + interface Visitor { + + fun visitInvalidRequestError(invalidRequestError: InvalidRequestError): T + + fun visitAuthenticationError(authenticationError: AuthenticationError): T + + fun visitBillingError(billingError: BillingError): T + + fun visitPermissionError(permissionError: PermissionError): T + + fun visitNotFoundError(notFoundError: NotFoundError): T + + fun visitRateLimitError(rateLimitError: RateLimitError): T + + fun visitGatewayTimeoutError(gatewayTimeoutError: GatewayTimeoutError): T + + fun visitApiErrorObject(apiErrorObject: ApiErrorObject): T + + fun visitOverloadedError(overloadedError: OverloadedError): T + + fun unknown(json: JsonValue?): T { + throw AnthropicInvalidDataException("Unknown ErrorObject: $json") + } + } + + class Deserializer : BaseDeserializer(ErrorObject::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): ErrorObject { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "invalid_request_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(invalidRequestError = it, _json = json) + } + } + "authentication_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(authenticationError = it, _json = json) + } + } + "billing_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(billingError = it, _json = json) + } + } + "permission_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(permissionError = it, _json = json) + } + } + "not_found_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(notFoundError = it, _json = json) + } + } + "rate_limit_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(rateLimitError = it, _json = json) + } + } + "timeout_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(gatewayTimeoutError = it, _json = json) + } + } + "api_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(apiErrorObject = it, _json = json) + } + } + "overloaded_error" -> { + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return ErrorObject(overloadedError = it, _json = json) + } + } + } + + return ErrorObject(_json = json) + } + } + + class Serializer : BaseSerializer(ErrorObject::class) { + + override fun serialize( + value: ErrorObject, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.invalidRequestError != null -> + generator.writeObject(value.invalidRequestError) + value.authenticationError != null -> + generator.writeObject(value.authenticationError) + value.billingError != null -> generator.writeObject(value.billingError) + value.permissionError != null -> generator.writeObject(value.permissionError) + value.notFoundError != null -> generator.writeObject(value.notFoundError) + value.rateLimitError != null -> generator.writeObject(value.rateLimitError) + value.gatewayTimeoutError != null -> + generator.writeObject(value.gatewayTimeoutError) + value.apiErrorObject != null -> generator.writeObject(value.apiErrorObject) + value.overloadedError != null -> generator.writeObject(value.overloadedError) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid ErrorObject") + } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ErrorResponse.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ErrorResponse.kt new file mode 100644 index 0000000..f327eb2 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ErrorResponse.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = ErrorResponse.Builder::class) +@NoAutoDetect +class ErrorResponse +private constructor( + private val type: JsonField, + private val error: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun error(): ErrorObject = error.getRequired("error") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("error") @ExcludeMissing fun _error() = error + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): ErrorResponse = apply { + if (!validated) { + type() + error() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var error: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(errorResponse: ErrorResponse) = apply { + this.type = errorResponse.type + this.error = errorResponse.error + additionalProperties(errorResponse.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun error(error: ErrorObject) = error(JsonField.of(error)) + + @JsonProperty("error") + @ExcludeMissing + fun error(error: JsonField) = apply { this.error = error } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): ErrorResponse = + ErrorResponse( + type, + error, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ERROR = of("error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + ERROR, + } + + enum class Value { + ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + ERROR -> Value.ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + ERROR -> Known.ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ErrorResponse && type == other.type && error == other.error && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, error, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "ErrorResponse{type=$type, error=$error, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/GatewayTimeoutError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/GatewayTimeoutError.kt new file mode 100644 index 0000000..1714b47 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/GatewayTimeoutError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = GatewayTimeoutError.Builder::class) +@NoAutoDetect +class GatewayTimeoutError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): GatewayTimeoutError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(gatewayTimeoutError: GatewayTimeoutError) = apply { + this.type = gatewayTimeoutError.type + this.message = gatewayTimeoutError.message + additionalProperties(gatewayTimeoutError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): GatewayTimeoutError = + GatewayTimeoutError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val TIMEOUT_ERROR = of("timeout_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + TIMEOUT_ERROR, + } + + enum class Value { + TIMEOUT_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + TIMEOUT_ERROR -> Value.TIMEOUT_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + TIMEOUT_ERROR -> Known.TIMEOUT_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is GatewayTimeoutError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "GatewayTimeoutError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ImageBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ImageBlockParam.kt index c3fa5ff..f47e279 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ImageBlockParam.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ImageBlockParam.kt @@ -16,11 +16,13 @@ import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects +import java.util.Optional @JsonDeserialize(builder = ImageBlockParam.Builder::class) @NoAutoDetect class ImageBlockParam private constructor( + private val cacheControl: JsonField, private val type: JsonField, private val source: JsonField, private val additionalProperties: Map, @@ -28,10 +30,15 @@ private constructor( private var validated: Boolean = false + fun cacheControl(): Optional = + Optional.ofNullable(cacheControl.getNullable("cache_control")) + fun type(): Type = type.getRequired("type") fun source(): Source = source.getRequired("source") + @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl + @JsonProperty("type") @ExcludeMissing fun _type() = type @JsonProperty("source") @ExcludeMissing fun _source() = source @@ -42,6 +49,7 @@ private constructor( fun validate(): ImageBlockParam = apply { if (!validated) { + cacheControl().map { it.validate() } type() source().validate() validated = true @@ -57,17 +65,28 @@ private constructor( class Builder { + private var cacheControl: JsonField = JsonMissing.of() private var type: JsonField = JsonMissing.of() private var source: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(imageBlockParam: ImageBlockParam) = apply { + this.cacheControl = imageBlockParam.cacheControl this.type = imageBlockParam.type this.source = imageBlockParam.source additionalProperties(imageBlockParam.additionalProperties) } + fun cacheControl(cacheControl: CacheControlEphemeral) = + cacheControl(JsonField.of(cacheControl)) + + @JsonProperty("cache_control") + @ExcludeMissing + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + fun type(type: Type) = type(JsonField.of(type)) @JsonProperty("type") @@ -96,6 +115,7 @@ private constructor( fun build(): ImageBlockParam = ImageBlockParam( + cacheControl, type, source, additionalProperties.toImmutable(), @@ -396,15 +416,15 @@ private constructor( return true } - return /* spotless:off */ other is ImageBlockParam && type == other.type && source == other.source && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is ImageBlockParam && cacheControl == other.cacheControl && type == other.type && source == other.source && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, source, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(cacheControl, type, source, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "ImageBlockParam{type=$type, source=$source, additionalProperties=$additionalProperties}" + "ImageBlockParam{cacheControl=$cacheControl, type=$type, source=$source, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/InvalidRequestError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/InvalidRequestError.kt new file mode 100644 index 0000000..9469ca0 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/InvalidRequestError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = InvalidRequestError.Builder::class) +@NoAutoDetect +class InvalidRequestError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): InvalidRequestError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(invalidRequestError: InvalidRequestError) = apply { + this.type = invalidRequestError.type + this.message = invalidRequestError.message + additionalProperties(invalidRequestError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): InvalidRequestError = + InvalidRequestError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val INVALID_REQUEST_ERROR = of("invalid_request_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + INVALID_REQUEST_ERROR, + } + + enum class Value { + INVALID_REQUEST_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + INVALID_REQUEST_ERROR -> Value.INVALID_REQUEST_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + INVALID_REQUEST_ERROR -> Known.INVALID_REQUEST_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is InvalidRequestError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InvalidRequestError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatch.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatch.kt new file mode 100644 index 0000000..f1ed22a --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatch.kt @@ -0,0 +1,554 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.time.OffsetDateTime +import java.util.Objects +import java.util.Optional + +@JsonDeserialize(builder = MessageBatch.Builder::class) +@NoAutoDetect +class MessageBatch +private constructor( + private val id: JsonField, + private val type: JsonField, + private val processingStatus: JsonField, + private val requestCounts: JsonField, + private val endedAt: JsonField, + private val createdAt: JsonField, + private val expiresAt: JsonField, + private val archivedAt: JsonField, + private val cancelInitiatedAt: JsonField, + private val resultsUrl: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + /** + * Unique object identifier. + * + * The format and length of IDs may change over time. + */ + fun id(): String = id.getRequired("id") + + /** + * Object type. + * + * For Message Batches, this is always `"message_batch"`. + */ + fun type(): Type = type.getRequired("type") + + /** Processing status of the Message Batch. */ + fun processingStatus(): ProcessingStatus = processingStatus.getRequired("processing_status") + + /** + * Tallies requests within the Message Batch, categorized by their status. + * + * Requests start as `processing` and move to one of the other statuses only once processing of + * the entire batch ends. The sum of all values always matches the total number of requests in + * the batch. + */ + fun requestCounts(): MessageBatchRequestCounts = requestCounts.getRequired("request_counts") + + /** + * RFC 3339 datetime string representing the time at which processing for the Message Batch + * ended. Specified only once processing ends. + * + * Processing ends when every request in a Message Batch has either succeeded, errored, + * canceled, or expired. + */ + fun endedAt(): Optional = Optional.ofNullable(endedAt.getNullable("ended_at")) + + /** RFC 3339 datetime string representing the time at which the Message Batch was created. */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * RFC 3339 datetime string representing the time at which the Message Batch will expire and end + * processing, which is 24 hours after creation. + */ + fun expiresAt(): OffsetDateTime = expiresAt.getRequired("expires_at") + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was archived and + * its results became unavailable. + */ + fun archivedAt(): Optional = + Optional.ofNullable(archivedAt.getNullable("archived_at")) + + /** + * RFC 3339 datetime string representing the time at which cancellation was initiated for the + * Message Batch. Specified only if cancellation was initiated. + */ + fun cancelInitiatedAt(): Optional = + Optional.ofNullable(cancelInitiatedAt.getNullable("cancel_initiated_at")) + + /** + * URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only + * once processing ends. + * + * Results in the file are not guaranteed to be in the same order as requests. Use the + * `custom_id` field to match results to requests. + */ + fun resultsUrl(): Optional = Optional.ofNullable(resultsUrl.getNullable("results_url")) + + /** + * Unique object identifier. + * + * The format and length of IDs may change over time. + */ + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** + * Object type. + * + * For Message Batches, this is always `"message_batch"`. + */ + @JsonProperty("type") @ExcludeMissing fun _type() = type + + /** Processing status of the Message Batch. */ + @JsonProperty("processing_status") @ExcludeMissing fun _processingStatus() = processingStatus + + /** + * Tallies requests within the Message Batch, categorized by their status. + * + * Requests start as `processing` and move to one of the other statuses only once processing of + * the entire batch ends. The sum of all values always matches the total number of requests in + * the batch. + */ + @JsonProperty("request_counts") @ExcludeMissing fun _requestCounts() = requestCounts + + /** + * RFC 3339 datetime string representing the time at which processing for the Message Batch + * ended. Specified only once processing ends. + * + * Processing ends when every request in a Message Batch has either succeeded, errored, + * canceled, or expired. + */ + @JsonProperty("ended_at") @ExcludeMissing fun _endedAt() = endedAt + + /** RFC 3339 datetime string representing the time at which the Message Batch was created. */ + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt + + /** + * RFC 3339 datetime string representing the time at which the Message Batch will expire and end + * processing, which is 24 hours after creation. + */ + @JsonProperty("expires_at") @ExcludeMissing fun _expiresAt() = expiresAt + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was archived and + * its results became unavailable. + */ + @JsonProperty("archived_at") @ExcludeMissing fun _archivedAt() = archivedAt + + /** + * RFC 3339 datetime string representing the time at which cancellation was initiated for the + * Message Batch. Specified only if cancellation was initiated. + */ + @JsonProperty("cancel_initiated_at") + @ExcludeMissing + fun _cancelInitiatedAt() = cancelInitiatedAt + + /** + * URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only + * once processing ends. + * + * Results in the file are not guaranteed to be in the same order as requests. Use the + * `custom_id` field to match results to requests. + */ + @JsonProperty("results_url") @ExcludeMissing fun _resultsUrl() = resultsUrl + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): MessageBatch = apply { + if (!validated) { + id() + type() + processingStatus() + requestCounts().validate() + endedAt() + createdAt() + expiresAt() + archivedAt() + cancelInitiatedAt() + resultsUrl() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var type: JsonField = JsonMissing.of() + private var processingStatus: JsonField = JsonMissing.of() + private var requestCounts: JsonField = JsonMissing.of() + private var endedAt: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var expiresAt: JsonField = JsonMissing.of() + private var archivedAt: JsonField = JsonMissing.of() + private var cancelInitiatedAt: JsonField = JsonMissing.of() + private var resultsUrl: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatch: MessageBatch) = apply { + this.id = messageBatch.id + this.type = messageBatch.type + this.processingStatus = messageBatch.processingStatus + this.requestCounts = messageBatch.requestCounts + this.endedAt = messageBatch.endedAt + this.createdAt = messageBatch.createdAt + this.expiresAt = messageBatch.expiresAt + this.archivedAt = messageBatch.archivedAt + this.cancelInitiatedAt = messageBatch.cancelInitiatedAt + this.resultsUrl = messageBatch.resultsUrl + additionalProperties(messageBatch.additionalProperties) + } + + /** + * Unique object identifier. + * + * The format and length of IDs may change over time. + */ + fun id(id: String) = id(JsonField.of(id)) + + /** + * Unique object identifier. + * + * The format and length of IDs may change over time. + */ + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** + * Object type. + * + * For Message Batches, this is always `"message_batch"`. + */ + fun type(type: Type) = type(JsonField.of(type)) + + /** + * Object type. + * + * For Message Batches, this is always `"message_batch"`. + */ + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + /** Processing status of the Message Batch. */ + fun processingStatus(processingStatus: ProcessingStatus) = + processingStatus(JsonField.of(processingStatus)) + + /** Processing status of the Message Batch. */ + @JsonProperty("processing_status") + @ExcludeMissing + fun processingStatus(processingStatus: JsonField) = apply { + this.processingStatus = processingStatus + } + + /** + * Tallies requests within the Message Batch, categorized by their status. + * + * Requests start as `processing` and move to one of the other statuses only once processing + * of the entire batch ends. The sum of all values always matches the total number of + * requests in the batch. + */ + fun requestCounts(requestCounts: MessageBatchRequestCounts) = + requestCounts(JsonField.of(requestCounts)) + + /** + * Tallies requests within the Message Batch, categorized by their status. + * + * Requests start as `processing` and move to one of the other statuses only once processing + * of the entire batch ends. The sum of all values always matches the total number of + * requests in the batch. + */ + @JsonProperty("request_counts") + @ExcludeMissing + fun requestCounts(requestCounts: JsonField) = apply { + this.requestCounts = requestCounts + } + + /** + * RFC 3339 datetime string representing the time at which processing for the Message Batch + * ended. Specified only once processing ends. + * + * Processing ends when every request in a Message Batch has either succeeded, errored, + * canceled, or expired. + */ + fun endedAt(endedAt: OffsetDateTime) = endedAt(JsonField.of(endedAt)) + + /** + * RFC 3339 datetime string representing the time at which processing for the Message Batch + * ended. Specified only once processing ends. + * + * Processing ends when every request in a Message Batch has either succeeded, errored, + * canceled, or expired. + */ + @JsonProperty("ended_at") + @ExcludeMissing + fun endedAt(endedAt: JsonField) = apply { this.endedAt = endedAt } + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was created. + */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was created. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** + * RFC 3339 datetime string representing the time at which the Message Batch will expire and + * end processing, which is 24 hours after creation. + */ + fun expiresAt(expiresAt: OffsetDateTime) = expiresAt(JsonField.of(expiresAt)) + + /** + * RFC 3339 datetime string representing the time at which the Message Batch will expire and + * end processing, which is 24 hours after creation. + */ + @JsonProperty("expires_at") + @ExcludeMissing + fun expiresAt(expiresAt: JsonField) = apply { this.expiresAt = expiresAt } + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was archived + * and its results became unavailable. + */ + fun archivedAt(archivedAt: OffsetDateTime) = archivedAt(JsonField.of(archivedAt)) + + /** + * RFC 3339 datetime string representing the time at which the Message Batch was archived + * and its results became unavailable. + */ + @JsonProperty("archived_at") + @ExcludeMissing + fun archivedAt(archivedAt: JsonField) = apply { + this.archivedAt = archivedAt + } + + /** + * RFC 3339 datetime string representing the time at which cancellation was initiated for + * the Message Batch. Specified only if cancellation was initiated. + */ + fun cancelInitiatedAt(cancelInitiatedAt: OffsetDateTime) = + cancelInitiatedAt(JsonField.of(cancelInitiatedAt)) + + /** + * RFC 3339 datetime string representing the time at which cancellation was initiated for + * the Message Batch. Specified only if cancellation was initiated. + */ + @JsonProperty("cancel_initiated_at") + @ExcludeMissing + fun cancelInitiatedAt(cancelInitiatedAt: JsonField) = apply { + this.cancelInitiatedAt = cancelInitiatedAt + } + + /** + * URL to a `.jsonl` file containing the results of the Message Batch requests. Specified + * only once processing ends. + * + * Results in the file are not guaranteed to be in the same order as requests. Use the + * `custom_id` field to match results to requests. + */ + fun resultsUrl(resultsUrl: String) = resultsUrl(JsonField.of(resultsUrl)) + + /** + * URL to a `.jsonl` file containing the results of the Message Batch requests. Specified + * only once processing ends. + * + * Results in the file are not guaranteed to be in the same order as requests. Use the + * `custom_id` field to match results to requests. + */ + @JsonProperty("results_url") + @ExcludeMissing + fun resultsUrl(resultsUrl: JsonField) = apply { this.resultsUrl = resultsUrl } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageBatch = + MessageBatch( + id, + type, + processingStatus, + requestCounts, + endedAt, + createdAt, + expiresAt, + archivedAt, + cancelInitiatedAt, + resultsUrl, + additionalProperties.toImmutable(), + ) + } + + class ProcessingStatus + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val IN_PROGRESS = of("in_progress") + + @JvmField val CANCELING = of("canceling") + + @JvmField val ENDED = of("ended") + + @JvmStatic fun of(value: String) = ProcessingStatus(JsonField.of(value)) + } + + enum class Known { + IN_PROGRESS, + CANCELING, + ENDED, + } + + enum class Value { + IN_PROGRESS, + CANCELING, + ENDED, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + IN_PROGRESS -> Value.IN_PROGRESS + CANCELING -> Value.CANCELING + ENDED -> Value.ENDED + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + IN_PROGRESS -> Known.IN_PROGRESS + CANCELING -> Known.CANCELING + ENDED -> Known.ENDED + else -> throw AnthropicInvalidDataException("Unknown ProcessingStatus: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ProcessingStatus && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val MESSAGE_BATCH = of("message_batch") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + MESSAGE_BATCH, + } + + enum class Value { + MESSAGE_BATCH, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + MESSAGE_BATCH -> Value.MESSAGE_BATCH + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + MESSAGE_BATCH -> Known.MESSAGE_BATCH + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatch && id == other.id && type == other.type && processingStatus == other.processingStatus && requestCounts == other.requestCounts && endedAt == other.endedAt && createdAt == other.createdAt && expiresAt == other.expiresAt && archivedAt == other.archivedAt && cancelInitiatedAt == other.cancelInitiatedAt && resultsUrl == other.resultsUrl && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(id, type, processingStatus, requestCounts, endedAt, createdAt, expiresAt, archivedAt, cancelInitiatedAt, resultsUrl, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageBatch{id=$id, type=$type, processingStatus=$processingStatus, requestCounts=$requestCounts, endedAt=$endedAt, createdAt=$createdAt, expiresAt=$expiresAt, archivedAt=$archivedAt, cancelInitiatedAt=$cancelInitiatedAt, resultsUrl=$resultsUrl, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCancelParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCancelParams.kt new file mode 100644 index 0000000..76100ec --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCancelParams.kt @@ -0,0 +1,213 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import com.anthropic.core.toImmutable +import java.util.Objects +import java.util.Optional + +class MessageBatchCancelParams +constructor( + private val messageBatchId: String, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) { + + fun messageBatchId(): String = messageBatchId + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + @JvmSynthetic + internal fun getBody(): Optional> { + return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + } + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic internal fun getQueryParams(): QueryParams = additionalQueryParams + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> messageBatchId + else -> "" + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var messageBatchId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchCancelParams: MessageBatchCancelParams) = apply { + messageBatchId = messageBatchCancelParams.messageBatchId + additionalHeaders = messageBatchCancelParams.additionalHeaders.toBuilder() + additionalQueryParams = messageBatchCancelParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + messageBatchCancelParams.additionalBodyProperties.toMutableMap() + } + + /** ID of the Message Batch. */ + fun messageBatchId(messageBatchId: String) = apply { this.messageBatchId = messageBatchId } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + fun build(): MessageBatchCancelParams = + MessageBatchCancelParams( + checkNotNull(messageBatchId) { "`messageBatchId` is required but was not set" }, + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchCancelParams && messageBatchId == other.messageBatchId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(messageBatchId, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + + override fun toString() = + "MessageBatchCancelParams{messageBatchId=$messageBatchId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCanceledResult.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCanceledResult.kt new file mode 100644 index 0000000..0a9eb34 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCanceledResult.kt @@ -0,0 +1,154 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = MessageBatchCanceledResult.Builder::class) +@NoAutoDetect +class MessageBatchCanceledResult +private constructor( + private val type: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): MessageBatchCanceledResult = apply { + if (!validated) { + type() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchCanceledResult: MessageBatchCanceledResult) = apply { + this.type = messageBatchCanceledResult.type + additionalProperties(messageBatchCanceledResult.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageBatchCanceledResult = + MessageBatchCanceledResult(type, additionalProperties.toImmutable()) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val CANCELED = of("canceled") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + CANCELED, + } + + enum class Value { + CANCELED, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + CANCELED -> Value.CANCELED + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + CANCELED -> Known.CANCELED + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchCanceledResult && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageBatchCanceledResult{type=$type, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCreateParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCreateParams.kt new file mode 100644 index 0000000..8682ef1 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchCreateParams.kt @@ -0,0 +1,1155 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.BaseDeserializer +import com.anthropic.core.BaseSerializer +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.getOrThrow +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.util.Objects +import java.util.Optional + +class MessageBatchCreateParams +constructor( + private val requests: List, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, + private val additionalBodyProperties: Map, +) { + + fun requests(): List = requests + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + @JvmSynthetic + internal fun getBody(): MessageBatchCreateBody { + return MessageBatchCreateBody(requests, additionalBodyProperties) + } + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic internal fun getQueryParams(): QueryParams = additionalQueryParams + + @JsonDeserialize(builder = MessageBatchCreateBody.Builder::class) + @NoAutoDetect + class MessageBatchCreateBody + internal constructor( + private val requests: List?, + private val additionalProperties: Map, + ) { + + /** + * List of requests for prompt completion. Each is an individual request to create a + * Message. + */ + @JsonProperty("requests") fun requests(): List? = requests + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var requests: List? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchCreateBody: MessageBatchCreateBody) = apply { + this.requests = messageBatchCreateBody.requests + additionalProperties(messageBatchCreateBody.additionalProperties) + } + + /** + * List of requests for prompt completion. Each is an individual request to create a + * Message. + */ + @JsonProperty("requests") + fun requests(requests: List) = apply { this.requests = requests } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageBatchCreateBody = + MessageBatchCreateBody( + checkNotNull(requests) { "`requests` is required but was not set" } + .toImmutable(), + additionalProperties.toImmutable() + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchCreateBody && requests == other.requests && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(requests, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageBatchCreateBody{requests=$requests, additionalProperties=$additionalProperties}" + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var requests: MutableList = mutableListOf() + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchCreateParams: MessageBatchCreateParams) = apply { + requests = messageBatchCreateParams.requests.toMutableList() + additionalHeaders = messageBatchCreateParams.additionalHeaders.toBuilder() + additionalQueryParams = messageBatchCreateParams.additionalQueryParams.toBuilder() + additionalBodyProperties = + messageBatchCreateParams.additionalBodyProperties.toMutableMap() + } + + /** + * List of requests for prompt completion. Each is an individual request to create a + * Message. + */ + fun requests(requests: List) = apply { + this.requests.clear() + this.requests.addAll(requests) + } + + /** + * List of requests for prompt completion. Each is an individual request to create a + * Message. + */ + fun addRequest(request: Request) = apply { this.requests.add(request) } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + putAllAdditionalBodyProperties(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun removeAdditionalBodyProperty(key: String) = apply { + additionalBodyProperties.remove(key) + } + + fun removeAllAdditionalBodyProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalBodyProperty) + } + + fun build(): MessageBatchCreateParams = + MessageBatchCreateParams( + requests.toImmutable(), + additionalHeaders.build(), + additionalQueryParams.build(), + additionalBodyProperties.toImmutable(), + ) + } + + @JsonDeserialize(builder = Request.Builder::class) + @NoAutoDetect + class Request + private constructor( + private val customId: String?, + private val params: Params?, + private val additionalProperties: Map, + ) { + + /** + * Developer-provided ID created for each request in a Message Batch. Useful for matching + * results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + @JsonProperty("custom_id") fun customId(): String? = customId + + /** + * Messages API creation parameters for the individual request. + * + * See the [Messages API reference](/en/api/messages) for full documentation on available + * parameters. + */ + @JsonProperty("params") fun params(): Params? = params + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var customId: String? = null + private var params: Params? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(request: Request) = apply { + this.customId = request.customId + this.params = request.params + additionalProperties(request.additionalProperties) + } + + /** + * Developer-provided ID created for each request in a Message Batch. Useful for + * matching results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + @JsonProperty("custom_id") + fun customId(customId: String) = apply { this.customId = customId } + + /** + * Messages API creation parameters for the individual request. + * + * See the [Messages API reference](/en/api/messages) for full documentation on + * available parameters. + */ + @JsonProperty("params") fun params(params: Params) = apply { this.params = params } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Request = + Request( + checkNotNull(customId) { "`customId` is required but was not set" }, + checkNotNull(params) { "`params` is required but was not set" }, + additionalProperties.toImmutable(), + ) + } + + /** + * Messages API creation parameters for the individual request. + * + * See the [Messages API reference](/en/api/messages) for full documentation on available + * parameters. + */ + @JsonDeserialize(builder = Params.Builder::class) + @NoAutoDetect + class Params + private constructor( + private val model: Model?, + private val messages: List?, + private val maxTokens: Long?, + private val metadata: Metadata?, + private val stopSequences: List?, + private val stream: Boolean?, + private val system: System?, + private val temperature: Double?, + private val toolChoice: ToolChoice?, + private val tools: List?, + private val topK: Long?, + private val topP: Double?, + private val additionalProperties: Map, + ) { + + /** + * The model that will complete your prompt.\n\nSee + * [models](https://docs.anthropic.com/en/docs/models-overview) for additional details + * and options. + */ + @JsonProperty("model") fun model(): Model? = model + + /** + * Input messages. + * + * Our models are trained to operate on alternating `user` and `assistant` + * conversational turns. When creating a new `Message`, you specify the prior + * conversational turns with the `messages` parameter, and the model then generates the + * next `Message` in the conversation. Consecutive `user` or `assistant` turns in your + * request will be combined into a single turn. + * + * Each input message must be an object with a `role` and `content`. You can specify a + * single `user`-role message, or you can include multiple `user` and `assistant` + * messages. + * + * If the final message uses the `assistant` role, the response content will continue + * immediately from the content in that message. This can be used to constrain part of + * the model's response. + * + * Example with a single `user` message: + * ```json + * [{ "role": "user", "content": "Hello, Claude" }] + * ``` + * + * Example with multiple conversational turns: + * ```json + * [ + * { "role": "user", "content": "Hello there." }, + * { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + * { "role": "user", "content": "Can you explain LLMs in plain English?" } + * ] + * ``` + * + * Example with a partially-filled response from Claude: + * ```json + * [ + * { + * "role": "user", + * "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + * }, + * { "role": "assistant", "content": "The best answer is (" } + * ] + * ``` + * + * Each input message `content` may be either a single `string` or an array of content + * blocks, where each block has a specific `type`. Using a `string` for `content` is + * shorthand for an array of one content block of type `"text"`. The following input + * messages are equivalent: + * ```json + * { "role": "user", "content": "Hello, Claude" } + * ``` + * ```json + * { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + * ``` + * + * Starting with Claude 3 models, you can also send image content blocks: + * ```json + * { + * "role": "user", + * "content": [ + * { + * "type": "image", + * "source": { + * "type": "base64", + * "media_type": "image/jpeg", + * "data": "/9j/4AAQSkZJRg..." + * } + * }, + * { "type": "text", "text": "What is in this image?" } + * ] + * } + * ``` + * + * We currently support the `base64` source type for images, and the `image/jpeg`, + * `image/png`, `image/gif`, and `image/webp` media types. + * + * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for more + * input examples. + * + * Note that if you want to include a + * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use the + * top-level `system` parameter — there is no `"system"` role for input messages in the + * Messages API. + */ + @JsonProperty("messages") fun messages(): List? = messages + + /** + * The maximum number of tokens to generate before stopping. + * + * Note that our models may stop _before_ reaching this maximum. This parameter only + * specifies the absolute maximum number of tokens to generate. + * + * Different models have different maximum values for this parameter. See + * [models](https://docs.anthropic.com/en/docs/models-overview) for details. + */ + @JsonProperty("max_tokens") fun maxTokens(): Long? = maxTokens + + /** An object describing metadata about the request. */ + @JsonProperty("metadata") fun metadata(): Metadata? = metadata + + /** + * Custom text sequences that will cause the model to stop generating. + * + * Our models will normally stop when they have naturally completed their turn, which + * will result in a response `stop_reason` of `"end_turn"`. + * + * If you want the model to stop generating when it encounters custom strings of text, + * you can use the `stop_sequences` parameter. If the model encounters one of the custom + * sequences, the response `stop_reason` value will be `"stop_sequence"` and the + * response `stop_sequence` value will contain the matched stop sequence. + */ + @JsonProperty("stop_sequences") fun stopSequences(): List? = stopSequences + + /** + * Whether to incrementally stream the response using server-sent events. + * + * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for details. + */ + @JsonProperty("stream") fun stream(): Boolean? = stream + + /** + * System prompt. + * + * A system prompt is a way of providing context and instructions to Claude, such as + * specifying a particular goal or role. See our + * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts). + */ + @JsonProperty("system") fun system(): System? = system + + /** + * Amount of randomness injected into the response. + * + * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for + * analytical / multiple choice, and closer to `1.0` for creative and generative tasks. + * + * Note that even with `temperature` of `0.0`, the results will not be fully + * deterministic. + */ + @JsonProperty("temperature") fun temperature(): Double? = temperature + + /** + * How the model should use the provided tools. The model can use a specific tool, any + * available tool, or decide by itself. + */ + @JsonProperty("tool_choice") fun toolChoice(): ToolChoice? = toolChoice + + /** + * Definitions of tools that the model may use. + * + * If you include `tools` in your API request, the model may return `tool_use` content + * blocks that represent the model's use of those tools. You can then run those tools + * using the tool input generated by the model and then optionally return results back + * to the model using `tool_result` content blocks. + * + * Each tool definition includes: + * - `name`: Name of the tool. + * - `description`: Optional, but strongly-recommended description of the tool. + * - `input_schema`: [JSON schema](https://json-schema.org/) for the tool `input` shape + * that the model will produce in `tool_use` output content blocks. + * + * For example, if you defined `tools` as: + * ```json + * [ + * { + * "name": "get_stock_price", + * "description": "Get the current stock price for a given ticker symbol.", + * "input_schema": { + * "type": "object", + * "properties": { + * "ticker": { + * "type": "string", + * "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." + * } + * }, + * "required": ["ticker"] + * } + * } + * ] + * ``` + * + * And then asked the model "What's the S&P 500 at today?", the model might produce + * `tool_use` content blocks in the response like this: + * ```json + * [ + * { + * "type": "tool_use", + * "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + * "name": "get_stock_price", + * "input": { "ticker": "^GSPC" } + * } + * ] + * ``` + * + * You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an + * input, and return the following back to the model in a subsequent `user` message: + * ```json + * [ + * { + * "type": "tool_result", + * "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + * "content": "259.75 USD" + * } + * ] + * ``` + * + * Tools can be used for workflows that include running client-side tools and functions, + * or more generally whenever you want the model to produce a particular JSON structure + * of output. + * + * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details. + */ + @JsonProperty("tools") fun tools(): List? = tools + + /** + * Only sample from the top K options for each subsequent token. + * + * Used to remove "long tail" low probability responses. + * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). + * + * Recommended for advanced use cases only. You usually only need to use `temperature`. + */ + @JsonProperty("top_k") fun topK(): Long? = topK + + /** + * Use nucleus sampling. + * + * In nucleus sampling, we compute the cumulative distribution over all the options for + * each subsequent token in decreasing probability order and cut it off once it reaches + * a particular probability specified by `top_p`. You should either alter `temperature` + * or `top_p`, but not both. + * + * Recommended for advanced use cases only. You usually only need to use `temperature`. + */ + @JsonProperty("top_p") fun topP(): Double? = topP + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var model: Model? = null + private var messages: List? = null + private var maxTokens: Long? = null + private var metadata: Metadata? = null + private var stopSequences: List? = null + private var stream: Boolean? = null + private var system: System? = null + private var temperature: Double? = null + private var toolChoice: ToolChoice? = null + private var tools: List? = null + private var topK: Long? = null + private var topP: Double? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(params: Params) = apply { + this.model = params.model + this.messages = params.messages + this.maxTokens = params.maxTokens + this.metadata = params.metadata + this.stopSequences = params.stopSequences + this.stream = params.stream + this.system = params.system + this.temperature = params.temperature + this.toolChoice = params.toolChoice + this.tools = params.tools + this.topK = params.topK + this.topP = params.topP + additionalProperties(params.additionalProperties) + } + + /** + * The model that will complete your prompt.\n\nSee + * [models](https://docs.anthropic.com/en/docs/models-overview) for additional + * details and options. + */ + @JsonProperty("model") fun model(model: Model) = apply { this.model = model } + + /** + * Input messages. + * + * Our models are trained to operate on alternating `user` and `assistant` + * conversational turns. When creating a new `Message`, you specify the prior + * conversational turns with the `messages` parameter, and the model then generates + * the next `Message` in the conversation. Consecutive `user` or `assistant` turns + * in your request will be combined into a single turn. + * + * Each input message must be an object with a `role` and `content`. You can specify + * a single `user`-role message, or you can include multiple `user` and `assistant` + * messages. + * + * If the final message uses the `assistant` role, the response content will + * continue immediately from the content in that message. This can be used to + * constrain part of the model's response. + * + * Example with a single `user` message: + * ```json + * [{ "role": "user", "content": "Hello, Claude" }] + * ``` + * + * Example with multiple conversational turns: + * ```json + * [ + * { "role": "user", "content": "Hello there." }, + * { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + * { "role": "user", "content": "Can you explain LLMs in plain English?" } + * ] + * ``` + * + * Example with a partially-filled response from Claude: + * ```json + * [ + * { + * "role": "user", + * "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + * }, + * { "role": "assistant", "content": "The best answer is (" } + * ] + * ``` + * + * Each input message `content` may be either a single `string` or an array of + * content blocks, where each block has a specific `type`. Using a `string` for + * `content` is shorthand for an array of one content block of type `"text"`. The + * following input messages are equivalent: + * ```json + * { "role": "user", "content": "Hello, Claude" } + * ``` + * ```json + * { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + * ``` + * + * Starting with Claude 3 models, you can also send image content blocks: + * ```json + * { + * "role": "user", + * "content": [ + * { + * "type": "image", + * "source": { + * "type": "base64", + * "media_type": "image/jpeg", + * "data": "/9j/4AAQSkZJRg..." + * } + * }, + * { "type": "text", "text": "What is in this image?" } + * ] + * } + * ``` + * + * We currently support the `base64` source type for images, and the `image/jpeg`, + * `image/png`, `image/gif`, and `image/webp` media types. + * + * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for + * more input examples. + * + * Note that if you want to include a + * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use + * the top-level `system` parameter — there is no `"system"` role for input messages + * in the Messages API. + */ + @JsonProperty("messages") + fun messages(messages: List) = apply { this.messages = messages } + + /** + * The maximum number of tokens to generate before stopping. + * + * Note that our models may stop _before_ reaching this maximum. This parameter only + * specifies the absolute maximum number of tokens to generate. + * + * Different models have different maximum values for this parameter. See + * [models](https://docs.anthropic.com/en/docs/models-overview) for details. + */ + @JsonProperty("max_tokens") + fun maxTokens(maxTokens: Long) = apply { this.maxTokens = maxTokens } + + /** An object describing metadata about the request. */ + @JsonProperty("metadata") + fun metadata(metadata: Metadata) = apply { this.metadata = metadata } + + /** + * Custom text sequences that will cause the model to stop generating. + * + * Our models will normally stop when they have naturally completed their turn, + * which will result in a response `stop_reason` of `"end_turn"`. + * + * If you want the model to stop generating when it encounters custom strings of + * text, you can use the `stop_sequences` parameter. If the model encounters one of + * the custom sequences, the response `stop_reason` value will be `"stop_sequence"` + * and the response `stop_sequence` value will contain the matched stop sequence. + */ + @JsonProperty("stop_sequences") + fun stopSequences(stopSequences: List) = apply { + this.stopSequences = stopSequences + } + + /** + * Whether to incrementally stream the response using server-sent events. + * + * See [streaming](https://docs.anthropic.com/en/api/messages-streaming) for + * details. + */ + @JsonProperty("stream") fun stream(stream: Boolean) = apply { this.stream = stream } + + /** + * System prompt. + * + * A system prompt is a way of providing context and instructions to Claude, such as + * specifying a particular goal or role. See our + * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts). + */ + @JsonProperty("system") fun system(system: System) = apply { this.system = system } + + /** + * Amount of randomness injected into the response. + * + * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` + * for analytical / multiple choice, and closer to `1.0` for creative and generative + * tasks. + * + * Note that even with `temperature` of `0.0`, the results will not be fully + * deterministic. + */ + @JsonProperty("temperature") + fun temperature(temperature: Double) = apply { this.temperature = temperature } + + /** + * How the model should use the provided tools. The model can use a specific tool, + * any available tool, or decide by itself. + */ + @JsonProperty("tool_choice") + fun toolChoice(toolChoice: ToolChoice) = apply { this.toolChoice = toolChoice } + + /** + * Definitions of tools that the model may use. + * + * If you include `tools` in your API request, the model may return `tool_use` + * content blocks that represent the model's use of those tools. You can then run + * those tools using the tool input generated by the model and then optionally + * return results back to the model using `tool_result` content blocks. + * + * Each tool definition includes: + * - `name`: Name of the tool. + * - `description`: Optional, but strongly-recommended description of the tool. + * - `input_schema`: [JSON schema](https://json-schema.org/) for the tool `input` + * shape that the model will produce in `tool_use` output content blocks. + * + * For example, if you defined `tools` as: + * ```json + * [ + * { + * "name": "get_stock_price", + * "description": "Get the current stock price for a given ticker symbol.", + * "input_schema": { + * "type": "object", + * "properties": { + * "ticker": { + * "type": "string", + * "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." + * } + * }, + * "required": ["ticker"] + * } + * } + * ] + * ``` + * + * And then asked the model "What's the S&P 500 at today?", the model might produce + * `tool_use` content blocks in the response like this: + * ```json + * [ + * { + * "type": "tool_use", + * "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + * "name": "get_stock_price", + * "input": { "ticker": "^GSPC" } + * } + * ] + * ``` + * + * You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an + * input, and return the following back to the model in a subsequent `user` message: + * ```json + * [ + * { + * "type": "tool_result", + * "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + * "content": "259.75 USD" + * } + * ] + * ``` + * + * Tools can be used for workflows that include running client-side tools and + * functions, or more generally whenever you want the model to produce a particular + * JSON structure of output. + * + * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details. + */ + @JsonProperty("tools") fun tools(tools: List) = apply { this.tools = tools } + + /** + * Only sample from the top K options for each subsequent token. + * + * Used to remove "long tail" low probability responses. + * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). + * + * Recommended for advanced use cases only. You usually only need to use + * `temperature`. + */ + @JsonProperty("top_k") fun topK(topK: Long) = apply { this.topK = topK } + + /** + * Use nucleus sampling. + * + * In nucleus sampling, we compute the cumulative distribution over all the options + * for each subsequent token in decreasing probability order and cut it off once it + * reaches a particular probability specified by `top_p`. You should either alter + * `temperature` or `top_p`, but not both. + * + * Recommended for advanced use cases only. You usually only need to use + * `temperature`. + */ + @JsonProperty("top_p") fun topP(topP: Double) = apply { this.topP = topP } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Params = + Params( + checkNotNull(model) { "`model` is required but was not set" }, + checkNotNull(messages) { "`messages` is required but was not set" } + .toImmutable(), + checkNotNull(maxTokens) { "`maxTokens` is required but was not set" }, + metadata, + stopSequences?.toImmutable(), + stream, + system, + temperature, + toolChoice, + tools?.toImmutable(), + topK, + topP, + additionalProperties.toImmutable(), + ) + } + + @JsonDeserialize(using = System.Deserializer::class) + @JsonSerialize(using = System.Serializer::class) + class System + private constructor( + private val string: String? = null, + private val textBlockParams: List? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun string(): Optional = Optional.ofNullable(string) + + fun textBlockParams(): Optional> = + Optional.ofNullable(textBlockParams) + + fun isString(): Boolean = string != null + + fun isTextBlockParams(): Boolean = textBlockParams != null + + fun asString(): String = string.getOrThrow("string") + + fun asTextBlockParams(): List = + textBlockParams.getOrThrow("textBlockParams") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + string != null -> visitor.visitString(string) + textBlockParams != null -> visitor.visitTextBlockParams(textBlockParams) + else -> visitor.unknown(_json) + } + } + + fun validate(): System = apply { + if (!validated) { + if (string == null && textBlockParams == null) { + throw AnthropicInvalidDataException("Unknown System: $_json") + } + textBlockParams?.forEach { it.validate() } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is System && string == other.string && textBlockParams == other.textBlockParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, textBlockParams) /* spotless:on */ + + override fun toString(): String = + when { + string != null -> "System{string=$string}" + textBlockParams != null -> "System{textBlockParams=$textBlockParams}" + _json != null -> "System{_unknown=$_json}" + else -> throw IllegalStateException("Invalid System") + } + + companion object { + + @JvmStatic fun ofString(string: String) = System(string = string) + + @JvmStatic + fun ofTextBlockParams(textBlockParams: List) = + System(textBlockParams = textBlockParams) + } + + interface Visitor { + + fun visitString(string: String): T + + fun visitTextBlockParams(textBlockParams: List): T + + fun unknown(json: JsonValue?): T { + throw AnthropicInvalidDataException("Unknown System: $json") + } + } + + class Deserializer : BaseDeserializer(System::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): System { + val json = JsonValue.fromJsonNode(node) + + tryDeserialize(node, jacksonTypeRef())?.let { + return System(string = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef>()) { + it.forEach { it.validate() } + } + ?.let { + return System(textBlockParams = it, _json = json) + } + + return System(_json = json) + } + } + + class Serializer : BaseSerializer(System::class) { + + override fun serialize( + value: System, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.textBlockParams != null -> + generator.writeObject(value.textBlockParams) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid System") + } + } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Params && model == other.model && messages == other.messages && maxTokens == other.maxTokens && metadata == other.metadata && stopSequences == other.stopSequences && stream == other.stream && system == other.system && temperature == other.temperature && toolChoice == other.toolChoice && tools == other.tools && topK == other.topK && topP == other.topP && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(model, messages, maxTokens, metadata, stopSequences, stream, system, temperature, toolChoice, tools, topK, topP, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Params{model=$model, messages=$messages, maxTokens=$maxTokens, metadata=$metadata, stopSequences=$stopSequences, stream=$stream, system=$system, temperature=$temperature, toolChoice=$toolChoice, tools=$tools, topK=$topK, topP=$topP, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Request && customId == other.customId && params == other.params && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(customId, params, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "Request{customId=$customId, params=$params, additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchCreateParams && requests == other.requests && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(requests, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + + override fun toString() = + "MessageBatchCreateParams{requests=$requests, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchErroredResult.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchErroredResult.kt new file mode 100644 index 0000000..406a683 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchErroredResult.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = MessageBatchErroredResult.Builder::class) +@NoAutoDetect +class MessageBatchErroredResult +private constructor( + private val type: JsonField, + private val error: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun error(): ErrorResponse = error.getRequired("error") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("error") @ExcludeMissing fun _error() = error + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): MessageBatchErroredResult = apply { + if (!validated) { + type() + error().validate() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var error: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchErroredResult: MessageBatchErroredResult) = apply { + this.type = messageBatchErroredResult.type + this.error = messageBatchErroredResult.error + additionalProperties(messageBatchErroredResult.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun error(error: ErrorResponse) = error(JsonField.of(error)) + + @JsonProperty("error") + @ExcludeMissing + fun error(error: JsonField) = apply { this.error = error } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageBatchErroredResult = + MessageBatchErroredResult( + type, + error, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val ERRORED = of("errored") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + ERRORED, + } + + enum class Value { + ERRORED, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + ERRORED -> Value.ERRORED + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + ERRORED -> Known.ERRORED + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchErroredResult && type == other.type && error == other.error && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, error, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageBatchErroredResult{type=$type, error=$error, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchExpiredResult.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchExpiredResult.kt new file mode 100644 index 0000000..5a2d224 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchExpiredResult.kt @@ -0,0 +1,154 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = MessageBatchExpiredResult.Builder::class) +@NoAutoDetect +class MessageBatchExpiredResult +private constructor( + private val type: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): MessageBatchExpiredResult = apply { + if (!validated) { + type() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchExpiredResult: MessageBatchExpiredResult) = apply { + this.type = messageBatchExpiredResult.type + additionalProperties(messageBatchExpiredResult.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageBatchExpiredResult = + MessageBatchExpiredResult(type, additionalProperties.toImmutable()) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val EXPIRED = of("expired") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + EXPIRED, + } + + enum class Value { + EXPIRED, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + EXPIRED -> Value.EXPIRED + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + EXPIRED -> Known.EXPIRED + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchExpiredResult && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageBatchExpiredResult{type=$type, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchIndividualResponse.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchIndividualResponse.kt new file mode 100644 index 0000000..32bcf33 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchIndividualResponse.kt @@ -0,0 +1,168 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = MessageBatchIndividualResponse.Builder::class) +@NoAutoDetect +class MessageBatchIndividualResponse +private constructor( + private val customId: JsonField, + private val result: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + /** + * Developer-provided ID created for each request in a Message Batch. Useful for matching + * results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + fun customId(): String = customId.getRequired("custom_id") + + /** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if processing + * failed, or the reason why processing was not attempted, such as cancellation or expiration. + */ + fun result(): MessageBatchResult = result.getRequired("result") + + /** + * Developer-provided ID created for each request in a Message Batch. Useful for matching + * results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + @JsonProperty("custom_id") @ExcludeMissing fun _customId() = customId + + /** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if processing + * failed, or the reason why processing was not attempted, such as cancellation or expiration. + */ + @JsonProperty("result") @ExcludeMissing fun _result() = result + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): MessageBatchIndividualResponse = apply { + if (!validated) { + customId() + result() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var customId: JsonField = JsonMissing.of() + private var result: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchIndividualResponse: MessageBatchIndividualResponse) = apply { + this.customId = messageBatchIndividualResponse.customId + this.result = messageBatchIndividualResponse.result + additionalProperties(messageBatchIndividualResponse.additionalProperties) + } + + /** + * Developer-provided ID created for each request in a Message Batch. Useful for matching + * results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + fun customId(customId: String) = customId(JsonField.of(customId)) + + /** + * Developer-provided ID created for each request in a Message Batch. Useful for matching + * results to requests, as results may be given out of request order. + * + * Must be unique for each request within the Message Batch. + */ + @JsonProperty("custom_id") + @ExcludeMissing + fun customId(customId: JsonField) = apply { this.customId = customId } + + /** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if processing + * failed, or the reason why processing was not attempted, such as cancellation or + * expiration. + */ + fun result(result: MessageBatchResult) = result(JsonField.of(result)) + + /** + * Processing result for this request. + * + * Contains a Message output if processing was successful, an error response if processing + * failed, or the reason why processing was not attempted, such as cancellation or + * expiration. + */ + @JsonProperty("result") + @ExcludeMissing + fun result(result: JsonField) = apply { this.result = result } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageBatchIndividualResponse = + MessageBatchIndividualResponse( + customId, + result, + additionalProperties.toImmutable(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchIndividualResponse && customId == other.customId && result == other.result && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(customId, result, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageBatchIndividualResponse{customId=$customId, result=$result, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListPage.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListPage.kt new file mode 100644 index 0000000..175761a --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListPage.kt @@ -0,0 +1,230 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.services.blocking.messages.BatchService +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class MessageBatchListPage +private constructor( + private val batchesService: BatchService, + private val params: MessageBatchListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun hasMore(): Optional = response().hasMore() + + fun firstId(): Optional = response().firstId() + + fun lastId(): Optional = response().lastId() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchListPage && batchesService == other.batchesService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(batchesService, params, response) /* spotless:on */ + + override fun toString() = + "MessageBatchListPage{batchesService=$batchesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + if (data().isEmpty()) { + return false + } + + return lastId().isPresent + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + MessageBatchListParams.builder() + .from(params) + .apply { lastId().ifPresent { this.afterId(it) } } + .build() + ) + } + + fun getNextPage(): Optional { + return getNextPageParams().map { batchesService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(batchesService: BatchService, params: MessageBatchListParams, response: Response) = + MessageBatchListPage( + batchesService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val hasMore: JsonField, + private val firstId: JsonField, + private val lastId: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun hasMore(): Optional = Optional.ofNullable(hasMore.getNullable("has_more")) + + fun firstId(): Optional = Optional.ofNullable(firstId.getNullable("first_id")) + + fun lastId(): Optional = Optional.ofNullable(lastId.getNullable("last_id")) + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("has_more") + fun _hasMore(): Optional> = Optional.ofNullable(hasMore) + + @JsonProperty("first_id") + fun _firstId(): Optional> = Optional.ofNullable(firstId) + + @JsonProperty("last_id") + fun _lastId(): Optional> = Optional.ofNullable(lastId) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + hasMore() + firstId() + lastId() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && data == other.data && hasMore == other.hasMore && firstId == other.firstId && lastId == other.lastId && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, hasMore, firstId, lastId, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{data=$data, hasMore=$hasMore, firstId=$firstId, lastId=$lastId, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var hasMore: JsonField = JsonMissing.of() + private var firstId: JsonField = JsonMissing.of() + private var lastId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.hasMore = page.hasMore + this.firstId = page.firstId + this.lastId = page.lastId + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun hasMore(hasMore: Boolean) = hasMore(JsonField.of(hasMore)) + + @JsonProperty("has_more") + fun hasMore(hasMore: JsonField) = apply { this.hasMore = hasMore } + + fun firstId(firstId: String) = firstId(JsonField.of(firstId)) + + @JsonProperty("first_id") + fun firstId(firstId: JsonField) = apply { this.firstId = firstId } + + fun lastId(lastId: String) = lastId(JsonField.of(lastId)) + + @JsonProperty("last_id") + fun lastId(lastId: JsonField) = apply { this.lastId = lastId } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + hasMore, + firstId, + lastId, + additionalProperties.toImmutable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: MessageBatchListPage, + ) : Iterable { + + override fun iterator(): Iterator = iterator { + var page = firstPage + var index = 0 + while (true) { + while (index < page.data().size) { + yield(page.data()[index++]) + } + page = page.getNextPage().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListPageAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListPageAsync.kt new file mode 100644 index 0000000..a34f375 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListPageAsync.kt @@ -0,0 +1,244 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.services.async.messages.BatchServiceAsync +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class MessageBatchListPageAsync +private constructor( + private val batchesService: BatchServiceAsync, + private val params: MessageBatchListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun hasMore(): Optional = response().hasMore() + + fun firstId(): Optional = response().firstId() + + fun lastId(): Optional = response().lastId() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchListPageAsync && batchesService == other.batchesService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(batchesService, params, response) /* spotless:on */ + + override fun toString() = + "MessageBatchListPageAsync{batchesService=$batchesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + if (data().isEmpty()) { + return false + } + + return lastId().isPresent + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + MessageBatchListParams.builder() + .from(params) + .apply { lastId().ifPresent { this.afterId(it) } } + .build() + ) + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { batchesService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + batchesService: BatchServiceAsync, + params: MessageBatchListParams, + response: Response + ) = + MessageBatchListPageAsync( + batchesService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val hasMore: JsonField, + private val firstId: JsonField, + private val lastId: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun hasMore(): Optional = Optional.ofNullable(hasMore.getNullable("has_more")) + + fun firstId(): Optional = Optional.ofNullable(firstId.getNullable("first_id")) + + fun lastId(): Optional = Optional.ofNullable(lastId.getNullable("last_id")) + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("has_more") + fun _hasMore(): Optional> = Optional.ofNullable(hasMore) + + @JsonProperty("first_id") + fun _firstId(): Optional> = Optional.ofNullable(firstId) + + @JsonProperty("last_id") + fun _lastId(): Optional> = Optional.ofNullable(lastId) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + hasMore() + firstId() + lastId() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && data == other.data && hasMore == other.hasMore && firstId == other.firstId && lastId == other.lastId && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, hasMore, firstId, lastId, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{data=$data, hasMore=$hasMore, firstId=$firstId, lastId=$lastId, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var hasMore: JsonField = JsonMissing.of() + private var firstId: JsonField = JsonMissing.of() + private var lastId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.hasMore = page.hasMore + this.firstId = page.firstId + this.lastId = page.lastId + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun hasMore(hasMore: Boolean) = hasMore(JsonField.of(hasMore)) + + @JsonProperty("has_more") + fun hasMore(hasMore: JsonField) = apply { this.hasMore = hasMore } + + fun firstId(firstId: String) = firstId(JsonField.of(firstId)) + + @JsonProperty("first_id") + fun firstId(firstId: JsonField) = apply { this.firstId = firstId } + + fun lastId(lastId: String) = lastId(JsonField.of(lastId)) + + @JsonProperty("last_id") + fun lastId(lastId: JsonField) = apply { this.lastId = lastId } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + hasMore, + firstId, + lastId, + additionalProperties.toImmutable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: MessageBatchListPageAsync, + ) { + + fun forEach(action: Predicate, executor: Executor): CompletableFuture { + fun CompletableFuture>.forEach( + action: (MessageBatch) -> Boolean, + executor: Executor + ): CompletableFuture = + thenComposeAsync( + { page -> + page + .filter { it.data().all(action) } + .map { it.getNextPage().forEach(action, executor) } + .orElseGet { CompletableFuture.completedFuture(null) } + }, + executor + ) + return CompletableFuture.completedFuture(Optional.of(firstPage)) + .forEach(action::test, executor) + } + + fun toList(executor: Executor): CompletableFuture> { + val values = mutableListOf() + return forEach(values::add, executor).thenApply { values } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListParams.kt new file mode 100644 index 0000000..9dd74d2 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchListParams.kt @@ -0,0 +1,206 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import java.util.Objects +import java.util.Optional + +class MessageBatchListParams +constructor( + private val afterId: String?, + private val beforeId: String?, + private val limit: Long?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) { + + fun afterId(): Optional = Optional.ofNullable(afterId) + + fun beforeId(): Optional = Optional.ofNullable(beforeId) + + fun limit(): Optional = Optional.ofNullable(limit) + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic + internal fun getQueryParams(): QueryParams { + val queryParams = QueryParams.builder() + this.afterId?.let { queryParams.put("after_id", listOf(it.toString())) } + this.beforeId?.let { queryParams.put("before_id", listOf(it.toString())) } + this.limit?.let { queryParams.put("limit", listOf(it.toString())) } + queryParams.putAll(additionalQueryParams) + return queryParams.build() + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var afterId: String? = null + private var beforeId: String? = null + private var limit: Long? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(messageBatchListParams: MessageBatchListParams) = apply { + afterId = messageBatchListParams.afterId + beforeId = messageBatchListParams.beforeId + limit = messageBatchListParams.limit + additionalHeaders = messageBatchListParams.additionalHeaders.toBuilder() + additionalQueryParams = messageBatchListParams.additionalQueryParams.toBuilder() + } + + /** + * ID of the object to use as a cursor for pagination. When provided, returns the page of + * results immediately after this object. + */ + fun afterId(afterId: String) = apply { this.afterId = afterId } + + /** + * ID of the object to use as a cursor for pagination. When provided, returns the page of + * results immediately before this object. + */ + fun beforeId(beforeId: String) = apply { this.beforeId = beforeId } + + /** + * Number of items to return per page. + * + * Defaults to `20`. Ranges from `1` to `1000`. + */ + fun limit(limit: Long) = apply { this.limit = limit } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun build(): MessageBatchListParams = + MessageBatchListParams( + afterId, + beforeId, + limit, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchListParams && afterId == other.afterId && beforeId == other.beforeId && limit == other.limit && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(afterId, beforeId, limit, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "MessageBatchListParams{afterId=$afterId, beforeId=$beforeId, limit=$limit, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchRequestCounts.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchRequestCounts.kt new file mode 100644 index 0000000..6a96309 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchRequestCounts.kt @@ -0,0 +1,247 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = MessageBatchRequestCounts.Builder::class) +@NoAutoDetect +class MessageBatchRequestCounts +private constructor( + private val processing: JsonField, + private val succeeded: JsonField, + private val errored: JsonField, + private val canceled: JsonField, + private val expired: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + /** Number of requests in the Message Batch that are processing. */ + fun processing(): Long = processing.getRequired("processing") + + /** + * Number of requests in the Message Batch that have completed successfully. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun succeeded(): Long = succeeded.getRequired("succeeded") + + /** + * Number of requests in the Message Batch that encountered an error. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun errored(): Long = errored.getRequired("errored") + + /** + * Number of requests in the Message Batch that have been canceled. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun canceled(): Long = canceled.getRequired("canceled") + + /** + * Number of requests in the Message Batch that have expired. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun expired(): Long = expired.getRequired("expired") + + /** Number of requests in the Message Batch that are processing. */ + @JsonProperty("processing") @ExcludeMissing fun _processing() = processing + + /** + * Number of requests in the Message Batch that have completed successfully. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("succeeded") @ExcludeMissing fun _succeeded() = succeeded + + /** + * Number of requests in the Message Batch that encountered an error. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("errored") @ExcludeMissing fun _errored() = errored + + /** + * Number of requests in the Message Batch that have been canceled. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("canceled") @ExcludeMissing fun _canceled() = canceled + + /** + * Number of requests in the Message Batch that have expired. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("expired") @ExcludeMissing fun _expired() = expired + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): MessageBatchRequestCounts = apply { + if (!validated) { + processing() + succeeded() + errored() + canceled() + expired() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var processing: JsonField = JsonMissing.of() + private var succeeded: JsonField = JsonMissing.of() + private var errored: JsonField = JsonMissing.of() + private var canceled: JsonField = JsonMissing.of() + private var expired: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageBatchRequestCounts: MessageBatchRequestCounts) = apply { + this.processing = messageBatchRequestCounts.processing + this.succeeded = messageBatchRequestCounts.succeeded + this.errored = messageBatchRequestCounts.errored + this.canceled = messageBatchRequestCounts.canceled + this.expired = messageBatchRequestCounts.expired + additionalProperties(messageBatchRequestCounts.additionalProperties) + } + + /** Number of requests in the Message Batch that are processing. */ + fun processing(processing: Long) = processing(JsonField.of(processing)) + + /** Number of requests in the Message Batch that are processing. */ + @JsonProperty("processing") + @ExcludeMissing + fun processing(processing: JsonField) = apply { this.processing = processing } + + /** + * Number of requests in the Message Batch that have completed successfully. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun succeeded(succeeded: Long) = succeeded(JsonField.of(succeeded)) + + /** + * Number of requests in the Message Batch that have completed successfully. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("succeeded") + @ExcludeMissing + fun succeeded(succeeded: JsonField) = apply { this.succeeded = succeeded } + + /** + * Number of requests in the Message Batch that encountered an error. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun errored(errored: Long) = errored(JsonField.of(errored)) + + /** + * Number of requests in the Message Batch that encountered an error. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("errored") + @ExcludeMissing + fun errored(errored: JsonField) = apply { this.errored = errored } + + /** + * Number of requests in the Message Batch that have been canceled. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun canceled(canceled: Long) = canceled(JsonField.of(canceled)) + + /** + * Number of requests in the Message Batch that have been canceled. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("canceled") + @ExcludeMissing + fun canceled(canceled: JsonField) = apply { this.canceled = canceled } + + /** + * Number of requests in the Message Batch that have expired. + * + * This is zero until processing of the entire Message Batch has ended. + */ + fun expired(expired: Long) = expired(JsonField.of(expired)) + + /** + * Number of requests in the Message Batch that have expired. + * + * This is zero until processing of the entire Message Batch has ended. + */ + @JsonProperty("expired") + @ExcludeMissing + fun expired(expired: JsonField) = apply { this.expired = expired } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageBatchRequestCounts = + MessageBatchRequestCounts( + processing, + succeeded, + errored, + canceled, + expired, + additionalProperties.toImmutable(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchRequestCounts && processing == other.processing && succeeded == other.succeeded && errored == other.errored && canceled == other.canceled && expired == other.expired && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(processing, succeeded, errored, canceled, expired, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageBatchRequestCounts{processing=$processing, succeeded=$succeeded, errored=$errored, canceled=$canceled, expired=$expired, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchResult.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchResult.kt new file mode 100644 index 0000000..e9c9a84 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchResult.kt @@ -0,0 +1,232 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.BaseDeserializer +import com.anthropic.core.BaseSerializer +import com.anthropic.core.JsonValue +import com.anthropic.core.getOrThrow +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +@JsonDeserialize(using = MessageBatchResult.Deserializer::class) +@JsonSerialize(using = MessageBatchResult.Serializer::class) +class MessageBatchResult +private constructor( + private val messageBatchSucceededResult: MessageBatchSucceededResult? = null, + private val messageBatchErroredResult: MessageBatchErroredResult? = null, + private val messageBatchCanceledResult: MessageBatchCanceledResult? = null, + private val messageBatchExpiredResult: MessageBatchExpiredResult? = null, + private val _json: JsonValue? = null, +) { + + private var validated: Boolean = false + + fun messageBatchSucceededResult(): Optional = + Optional.ofNullable(messageBatchSucceededResult) + + fun messageBatchErroredResult(): Optional = + Optional.ofNullable(messageBatchErroredResult) + + fun messageBatchCanceledResult(): Optional = + Optional.ofNullable(messageBatchCanceledResult) + + fun messageBatchExpiredResult(): Optional = + Optional.ofNullable(messageBatchExpiredResult) + + fun isMessageBatchSucceededResult(): Boolean = messageBatchSucceededResult != null + + fun isMessageBatchErroredResult(): Boolean = messageBatchErroredResult != null + + fun isMessageBatchCanceledResult(): Boolean = messageBatchCanceledResult != null + + fun isMessageBatchExpiredResult(): Boolean = messageBatchExpiredResult != null + + fun asMessageBatchSucceededResult(): MessageBatchSucceededResult = + messageBatchSucceededResult.getOrThrow("messageBatchSucceededResult") + + fun asMessageBatchErroredResult(): MessageBatchErroredResult = + messageBatchErroredResult.getOrThrow("messageBatchErroredResult") + + fun asMessageBatchCanceledResult(): MessageBatchCanceledResult = + messageBatchCanceledResult.getOrThrow("messageBatchCanceledResult") + + fun asMessageBatchExpiredResult(): MessageBatchExpiredResult = + messageBatchExpiredResult.getOrThrow("messageBatchExpiredResult") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + messageBatchSucceededResult != null -> + visitor.visitMessageBatchSucceededResult(messageBatchSucceededResult) + messageBatchErroredResult != null -> + visitor.visitMessageBatchErroredResult(messageBatchErroredResult) + messageBatchCanceledResult != null -> + visitor.visitMessageBatchCanceledResult(messageBatchCanceledResult) + messageBatchExpiredResult != null -> + visitor.visitMessageBatchExpiredResult(messageBatchExpiredResult) + else -> visitor.unknown(_json) + } + } + + fun validate(): MessageBatchResult = apply { + if (!validated) { + if ( + messageBatchSucceededResult == null && + messageBatchErroredResult == null && + messageBatchCanceledResult == null && + messageBatchExpiredResult == null + ) { + throw AnthropicInvalidDataException("Unknown MessageBatchResult: $_json") + } + messageBatchSucceededResult?.validate() + messageBatchErroredResult?.validate() + messageBatchCanceledResult?.validate() + messageBatchExpiredResult?.validate() + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchResult && messageBatchSucceededResult == other.messageBatchSucceededResult && messageBatchErroredResult == other.messageBatchErroredResult && messageBatchCanceledResult == other.messageBatchCanceledResult && messageBatchExpiredResult == other.messageBatchExpiredResult /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(messageBatchSucceededResult, messageBatchErroredResult, messageBatchCanceledResult, messageBatchExpiredResult) /* spotless:on */ + + override fun toString(): String = + when { + messageBatchSucceededResult != null -> + "MessageBatchResult{messageBatchSucceededResult=$messageBatchSucceededResult}" + messageBatchErroredResult != null -> + "MessageBatchResult{messageBatchErroredResult=$messageBatchErroredResult}" + messageBatchCanceledResult != null -> + "MessageBatchResult{messageBatchCanceledResult=$messageBatchCanceledResult}" + messageBatchExpiredResult != null -> + "MessageBatchResult{messageBatchExpiredResult=$messageBatchExpiredResult}" + _json != null -> "MessageBatchResult{_unknown=$_json}" + else -> throw IllegalStateException("Invalid MessageBatchResult") + } + + companion object { + + @JvmStatic + fun ofMessageBatchSucceededResult( + messageBatchSucceededResult: MessageBatchSucceededResult + ) = MessageBatchResult(messageBatchSucceededResult = messageBatchSucceededResult) + + @JvmStatic + fun ofMessageBatchErroredResult(messageBatchErroredResult: MessageBatchErroredResult) = + MessageBatchResult(messageBatchErroredResult = messageBatchErroredResult) + + @JvmStatic + fun ofMessageBatchCanceledResult(messageBatchCanceledResult: MessageBatchCanceledResult) = + MessageBatchResult(messageBatchCanceledResult = messageBatchCanceledResult) + + @JvmStatic + fun ofMessageBatchExpiredResult(messageBatchExpiredResult: MessageBatchExpiredResult) = + MessageBatchResult(messageBatchExpiredResult = messageBatchExpiredResult) + } + + interface Visitor { + + fun visitMessageBatchSucceededResult( + messageBatchSucceededResult: MessageBatchSucceededResult + ): T + + fun visitMessageBatchErroredResult(messageBatchErroredResult: MessageBatchErroredResult): T + + fun visitMessageBatchCanceledResult( + messageBatchCanceledResult: MessageBatchCanceledResult + ): T + + fun visitMessageBatchExpiredResult(messageBatchExpiredResult: MessageBatchExpiredResult): T + + fun unknown(json: JsonValue?): T { + throw AnthropicInvalidDataException("Unknown MessageBatchResult: $json") + } + } + + class Deserializer : BaseDeserializer(MessageBatchResult::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): MessageBatchResult { + val json = JsonValue.fromJsonNode(node) + val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() + + when (type) { + "succeeded" -> { + tryDeserialize(node, jacksonTypeRef()) { + it.validate() + } + ?.let { + return MessageBatchResult( + messageBatchSucceededResult = it, + _json = json + ) + } + } + "errored" -> { + tryDeserialize(node, jacksonTypeRef()) { + it.validate() + } + ?.let { + return MessageBatchResult(messageBatchErroredResult = it, _json = json) + } + } + "canceled" -> { + tryDeserialize(node, jacksonTypeRef()) { + it.validate() + } + ?.let { + return MessageBatchResult(messageBatchCanceledResult = it, _json = json) + } + } + "expired" -> { + tryDeserialize(node, jacksonTypeRef()) { + it.validate() + } + ?.let { + return MessageBatchResult(messageBatchExpiredResult = it, _json = json) + } + } + } + + return MessageBatchResult(_json = json) + } + } + + class Serializer : BaseSerializer(MessageBatchResult::class) { + + override fun serialize( + value: MessageBatchResult, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.messageBatchSucceededResult != null -> + generator.writeObject(value.messageBatchSucceededResult) + value.messageBatchErroredResult != null -> + generator.writeObject(value.messageBatchErroredResult) + value.messageBatchCanceledResult != null -> + generator.writeObject(value.messageBatchCanceledResult) + value.messageBatchExpiredResult != null -> + generator.writeObject(value.messageBatchExpiredResult) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid MessageBatchResult") + } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchRetrieveParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchRetrieveParams.kt new file mode 100644 index 0000000..eaf401f --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchRetrieveParams.kt @@ -0,0 +1,176 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import java.util.Objects + +class MessageBatchRetrieveParams +constructor( + private val messageBatchId: String, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) { + + fun messageBatchId(): String = messageBatchId + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic internal fun getQueryParams(): QueryParams = additionalQueryParams + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> messageBatchId + else -> "" + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var messageBatchId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(messageBatchRetrieveParams: MessageBatchRetrieveParams) = apply { + messageBatchId = messageBatchRetrieveParams.messageBatchId + additionalHeaders = messageBatchRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = messageBatchRetrieveParams.additionalQueryParams.toBuilder() + } + + /** ID of the Message Batch. */ + fun messageBatchId(messageBatchId: String) = apply { this.messageBatchId = messageBatchId } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun build(): MessageBatchRetrieveParams = + MessageBatchRetrieveParams( + checkNotNull(messageBatchId) { "`messageBatchId` is required but was not set" }, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageBatchRetrieveParams && messageBatchId == other.messageBatchId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(messageBatchId, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "MessageBatchRetrieveParams{messageBatchId=$messageBatchId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStartEvent.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchSucceededResult.kt similarity index 70% rename from anthropic-java-core/src/main/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStartEvent.kt rename to anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchSucceededResult.kt index 0b42dfc..bdbf0a1 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStartEvent.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageBatchSucceededResult.kt @@ -17,12 +17,12 @@ import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects -@JsonDeserialize(builder = RawPromptCachingBetaMessageStartEvent.Builder::class) +@JsonDeserialize(builder = MessageBatchSucceededResult.Builder::class) @NoAutoDetect -class RawPromptCachingBetaMessageStartEvent +class MessageBatchSucceededResult private constructor( private val type: JsonField, - private val message: JsonField, + private val message: JsonField, private val additionalProperties: Map, ) { @@ -30,7 +30,7 @@ private constructor( fun type(): Type = type.getRequired("type") - fun message(): PromptCachingBetaMessage = message.getRequired("message") + fun message(): Message = message.getRequired("message") @JsonProperty("type") @ExcludeMissing fun _type() = type @@ -40,7 +40,7 @@ private constructor( @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - fun validate(): RawPromptCachingBetaMessageStartEvent = apply { + fun validate(): MessageBatchSucceededResult = apply { if (!validated) { type() message().validate() @@ -58,16 +58,14 @@ private constructor( class Builder { private var type: JsonField = JsonMissing.of() - private var message: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from( - rawPromptCachingBetaMessageStartEvent: RawPromptCachingBetaMessageStartEvent - ) = apply { - this.type = rawPromptCachingBetaMessageStartEvent.type - this.message = rawPromptCachingBetaMessageStartEvent.message - additionalProperties(rawPromptCachingBetaMessageStartEvent.additionalProperties) + internal fun from(messageBatchSucceededResult: MessageBatchSucceededResult) = apply { + this.type = messageBatchSucceededResult.type + this.message = messageBatchSucceededResult.message + additionalProperties(messageBatchSucceededResult.additionalProperties) } fun type(type: Type) = type(JsonField.of(type)) @@ -76,11 +74,11 @@ private constructor( @ExcludeMissing fun type(type: JsonField) = apply { this.type = type } - fun message(message: PromptCachingBetaMessage) = message(JsonField.of(message)) + fun message(message: Message) = message(JsonField.of(message)) @JsonProperty("message") @ExcludeMissing - fun message(message: JsonField) = apply { this.message = message } + fun message(message: JsonField) = apply { this.message = message } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() @@ -96,8 +94,8 @@ private constructor( this.additionalProperties.putAll(additionalProperties) } - fun build(): RawPromptCachingBetaMessageStartEvent = - RawPromptCachingBetaMessageStartEvent( + fun build(): MessageBatchSucceededResult = + MessageBatchSucceededResult( type, message, additionalProperties.toImmutable(), @@ -114,29 +112,29 @@ private constructor( companion object { - @JvmField val MESSAGE_START = of("message_start") + @JvmField val SUCCEEDED = of("succeeded") @JvmStatic fun of(value: String) = Type(JsonField.of(value)) } enum class Known { - MESSAGE_START, + SUCCEEDED, } enum class Value { - MESSAGE_START, + SUCCEEDED, _UNKNOWN, } fun value(): Value = when (this) { - MESSAGE_START -> Value.MESSAGE_START + SUCCEEDED -> Value.SUCCEEDED else -> Value._UNKNOWN } fun known(): Known = when (this) { - MESSAGE_START -> Known.MESSAGE_START + SUCCEEDED -> Known.SUCCEEDED else -> throw AnthropicInvalidDataException("Unknown Type: $value") } @@ -160,7 +158,7 @@ private constructor( return true } - return /* spotless:off */ other is RawPromptCachingBetaMessageStartEvent && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is MessageBatchSucceededResult && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ @@ -170,5 +168,5 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "RawPromptCachingBetaMessageStartEvent{type=$type, message=$message, additionalProperties=$additionalProperties}" + "MessageBatchSucceededResult{type=$type, message=$message, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaPromptCachingMessageCreateParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageCountTokensParams.kt similarity index 66% rename from anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaPromptCachingMessageCreateParams.kt rename to anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageCountTokensParams.kt index 9631f0f..82cb7a6 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/BetaPromptCachingMessageCreateParams.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageCountTokensParams.kt @@ -25,48 +25,27 @@ import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.util.Objects import java.util.Optional -class BetaPromptCachingMessageCreateParams +class MessageCountTokensParams constructor( - private val maxTokens: Long, - private val messages: List, + private val messages: List, private val model: Model, - private val metadata: Metadata?, - private val stopSequences: List?, private val system: System?, - private val temperature: Double?, private val toolChoice: ToolChoice?, - private val tools: List?, - private val topK: Long?, - private val topP: Double?, - private val betas: List?, + private val tools: List?, private val additionalHeaders: Headers, private val additionalQueryParams: QueryParams, private val additionalBodyProperties: Map, ) { - fun maxTokens(): Long = maxTokens - - fun messages(): List = messages + fun messages(): List = messages fun model(): Model = model - fun metadata(): Optional = Optional.ofNullable(metadata) - - fun stopSequences(): Optional> = Optional.ofNullable(stopSequences) - fun system(): Optional = Optional.ofNullable(system) - fun temperature(): Optional = Optional.ofNullable(temperature) - fun toolChoice(): Optional = Optional.ofNullable(toolChoice) - fun tools(): Optional> = Optional.ofNullable(tools) - - fun topK(): Optional = Optional.ofNullable(topK) - - fun topP(): Optional = Optional.ofNullable(topP) - - fun betas(): Optional> = Optional.ofNullable(betas) + fun tools(): Optional> = Optional.ofNullable(tools) fun _additionalHeaders(): Headers = additionalHeaders @@ -75,62 +54,33 @@ constructor( fun _additionalBodyProperties(): Map = additionalBodyProperties @JvmSynthetic - internal fun getBody(): BetaPromptCachingMessageCreateBody { - return BetaPromptCachingMessageCreateBody( - maxTokens, + internal fun getBody(): MessageCountTokensBody { + return MessageCountTokensBody( messages, model, - metadata, - stopSequences, system, - temperature, toolChoice, tools, - topK, - topP, additionalBodyProperties, ) } - @JvmSynthetic - internal fun getHeaders(): Headers { - val headers = Headers.builder() - this.betas?.let { headers.put("anthropic-beta", it.map(Any::toString)) } - headers.putAll(additionalHeaders) - return headers.build() - } + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders @JvmSynthetic internal fun getQueryParams(): QueryParams = additionalQueryParams - @JsonDeserialize(builder = BetaPromptCachingMessageCreateBody.Builder::class) + @JsonDeserialize(builder = MessageCountTokensBody.Builder::class) @NoAutoDetect - class BetaPromptCachingMessageCreateBody + class MessageCountTokensBody internal constructor( - private val maxTokens: Long?, - private val messages: List?, + private val messages: List?, private val model: Model?, - private val metadata: Metadata?, - private val stopSequences: List?, private val system: System?, - private val temperature: Double?, private val toolChoice: ToolChoice?, - private val tools: List?, - private val topK: Long?, - private val topP: Double?, + private val tools: List?, private val additionalProperties: Map, ) { - /** - * The maximum number of tokens to generate before stopping. - * - * Note that our models may stop _before_ reaching this maximum. This parameter only - * specifies the absolute maximum number of tokens to generate. - * - * Different models have different maximum values for this parameter. See - * [models](https://docs.anthropic.com/en/docs/models-overview) for details. - */ - @JsonProperty("max_tokens") fun maxTokens(): Long? = maxTokens - /** * Input messages. * @@ -212,7 +162,7 @@ constructor( * top-level `system` parameter — there is no `"system"` role for input messages in the * Messages API. */ - @JsonProperty("messages") fun messages(): List? = messages + @JsonProperty("messages") fun messages(): List? = messages /** * The model that will complete your prompt.\n\nSee @@ -221,22 +171,6 @@ constructor( */ @JsonProperty("model") fun model(): Model? = model - /** An object describing metadata about the request. */ - @JsonProperty("metadata") fun metadata(): Metadata? = metadata - - /** - * Custom text sequences that will cause the model to stop generating. - * - * Our models will normally stop when they have naturally completed their turn, which will - * result in a response `stop_reason` of `"end_turn"`. - * - * If you want the model to stop generating when it encounters custom strings of text, you - * can use the `stop_sequences` parameter. If the model encounters one of the custom - * sequences, the response `stop_reason` value will be `"stop_sequence"` and the response - * `stop_sequence` value will contain the matched stop sequence. - */ - @JsonProperty("stop_sequences") fun stopSequences(): List? = stopSequences - /** * System prompt. * @@ -246,16 +180,6 @@ constructor( */ @JsonProperty("system") fun system(): System? = system - /** - * Amount of randomness injected into the response. - * - * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for - * analytical / multiple choice, and closer to `1.0` for creative and generative tasks. - * - * Note that even with `temperature` of `0.0`, the results will not be fully deterministic. - */ - @JsonProperty("temperature") fun temperature(): Double? = temperature - /** * How the model should use the provided tools. The model can use a specific tool, any * available tool, or decide by itself. @@ -327,29 +251,7 @@ constructor( * * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details. */ - @JsonProperty("tools") fun tools(): List? = tools - - /** - * Only sample from the top K options for each subsequent token. - * - * Used to remove "long tail" low probability responses. - * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). - * - * Recommended for advanced use cases only. You usually only need to use `temperature`. - */ - @JsonProperty("top_k") fun topK(): Long? = topK - - /** - * Use nucleus sampling. - * - * In nucleus sampling, we compute the cumulative distribution over all the options for each - * subsequent token in decreasing probability order and cut it off once it reaches a - * particular probability specified by `top_p`. You should either alter `temperature` or - * `top_p`, but not both. - * - * Recommended for advanced use cases only. You usually only need to use `temperature`. - */ - @JsonProperty("top_p") fun topP(): Double? = topP + @JsonProperty("tools") fun tools(): List? = tools @JsonAnyGetter @ExcludeMissing @@ -364,49 +266,23 @@ constructor( class Builder { - private var maxTokens: Long? = null - private var messages: List? = null + private var messages: List? = null private var model: Model? = null - private var metadata: Metadata? = null - private var stopSequences: List? = null private var system: System? = null - private var temperature: Double? = null private var toolChoice: ToolChoice? = null - private var tools: List? = null - private var topK: Long? = null - private var topP: Double? = null + private var tools: List? = null private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from( - betaPromptCachingMessageCreateBody: BetaPromptCachingMessageCreateBody - ) = apply { - this.maxTokens = betaPromptCachingMessageCreateBody.maxTokens - this.messages = betaPromptCachingMessageCreateBody.messages - this.model = betaPromptCachingMessageCreateBody.model - this.metadata = betaPromptCachingMessageCreateBody.metadata - this.stopSequences = betaPromptCachingMessageCreateBody.stopSequences - this.system = betaPromptCachingMessageCreateBody.system - this.temperature = betaPromptCachingMessageCreateBody.temperature - this.toolChoice = betaPromptCachingMessageCreateBody.toolChoice - this.tools = betaPromptCachingMessageCreateBody.tools - this.topK = betaPromptCachingMessageCreateBody.topK - this.topP = betaPromptCachingMessageCreateBody.topP - additionalProperties(betaPromptCachingMessageCreateBody.additionalProperties) + internal fun from(messageCountTokensBody: MessageCountTokensBody) = apply { + this.messages = messageCountTokensBody.messages + this.model = messageCountTokensBody.model + this.system = messageCountTokensBody.system + this.toolChoice = messageCountTokensBody.toolChoice + this.tools = messageCountTokensBody.tools + additionalProperties(messageCountTokensBody.additionalProperties) } - /** - * The maximum number of tokens to generate before stopping. - * - * Note that our models may stop _before_ reaching this maximum. This parameter only - * specifies the absolute maximum number of tokens to generate. - * - * Different models have different maximum values for this parameter. See - * [models](https://docs.anthropic.com/en/docs/models-overview) for details. - */ - @JsonProperty("max_tokens") - fun maxTokens(maxTokens: Long) = apply { this.maxTokens = maxTokens } - /** * Input messages. * @@ -490,9 +366,7 @@ constructor( * Messages API. */ @JsonProperty("messages") - fun messages(messages: List) = apply { - this.messages = messages - } + fun messages(messages: List) = apply { this.messages = messages } /** * The model that will complete your prompt.\n\nSee @@ -501,26 +375,6 @@ constructor( */ @JsonProperty("model") fun model(model: Model) = apply { this.model = model } - /** An object describing metadata about the request. */ - @JsonProperty("metadata") - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } - - /** - * Custom text sequences that will cause the model to stop generating. - * - * Our models will normally stop when they have naturally completed their turn, which - * will result in a response `stop_reason` of `"end_turn"`. - * - * If you want the model to stop generating when it encounters custom strings of text, - * you can use the `stop_sequences` parameter. If the model encounters one of the custom - * sequences, the response `stop_reason` value will be `"stop_sequence"` and the - * response `stop_sequence` value will contain the matched stop sequence. - */ - @JsonProperty("stop_sequences") - fun stopSequences(stopSequences: List) = apply { - this.stopSequences = stopSequences - } - /** * System prompt. * @@ -530,18 +384,6 @@ constructor( */ @JsonProperty("system") fun system(system: System) = apply { this.system = system } - /** - * Amount of randomness injected into the response. - * - * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for - * analytical / multiple choice, and closer to `1.0` for creative and generative tasks. - * - * Note that even with `temperature` of `0.0`, the results will not be fully - * deterministic. - */ - @JsonProperty("temperature") - fun temperature(temperature: Double) = apply { this.temperature = temperature } - /** * How the model should use the provided tools. The model can use a specific tool, any * available tool, or decide by itself. @@ -614,30 +456,7 @@ constructor( * * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details. */ - @JsonProperty("tools") - fun tools(tools: List) = apply { this.tools = tools } - - /** - * Only sample from the top K options for each subsequent token. - * - * Used to remove "long tail" low probability responses. - * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). - * - * Recommended for advanced use cases only. You usually only need to use `temperature`. - */ - @JsonProperty("top_k") fun topK(topK: Long) = apply { this.topK = topK } - - /** - * Use nucleus sampling. - * - * In nucleus sampling, we compute the cumulative distribution over all the options for - * each subsequent token in decreasing probability order and cut it off once it reaches - * a particular probability specified by `top_p`. You should either alter `temperature` - * or `top_p`, but not both. - * - * Recommended for advanced use cases only. You usually only need to use `temperature`. - */ - @JsonProperty("top_p") fun topP(topP: Double) = apply { this.topP = topP } + @JsonProperty("tools") fun tools(tools: List) = apply { this.tools = tools } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() @@ -653,20 +472,14 @@ constructor( this.additionalProperties.putAll(additionalProperties) } - fun build(): BetaPromptCachingMessageCreateBody = - BetaPromptCachingMessageCreateBody( - checkNotNull(maxTokens) { "`maxTokens` is required but was not set" }, + fun build(): MessageCountTokensBody = + MessageCountTokensBody( checkNotNull(messages) { "`messages` is required but was not set" } .toImmutable(), checkNotNull(model) { "`model` is required but was not set" }, - metadata, - stopSequences?.toImmutable(), system, - temperature, toolChoice, tools?.toImmutable(), - topK, - topP, additionalProperties.toImmutable(), ) } @@ -676,17 +489,17 @@ constructor( return true } - return /* spotless:off */ other is BetaPromptCachingMessageCreateBody && maxTokens == other.maxTokens && messages == other.messages && model == other.model && metadata == other.metadata && stopSequences == other.stopSequences && system == other.system && temperature == other.temperature && toolChoice == other.toolChoice && tools == other.tools && topK == other.topK && topP == other.topP && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is MessageCountTokensBody && messages == other.messages && model == other.model && system == other.system && toolChoice == other.toolChoice && tools == other.tools && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(maxTokens, messages, model, metadata, stopSequences, system, temperature, toolChoice, tools, topK, topP, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(messages, model, system, toolChoice, tools, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "BetaPromptCachingMessageCreateBody{maxTokens=$maxTokens, messages=$messages, model=$model, metadata=$metadata, stopSequences=$stopSequences, system=$system, temperature=$temperature, toolChoice=$toolChoice, tools=$tools, topK=$topK, topP=$topP, additionalProperties=$additionalProperties}" + "MessageCountTokensBody{messages=$messages, model=$model, system=$system, toolChoice=$toolChoice, tools=$tools, additionalProperties=$additionalProperties}" } fun toBuilder() = Builder().from(this) @@ -699,57 +512,113 @@ constructor( @NoAutoDetect class Builder { - private var maxTokens: Long? = null - private var messages: MutableList = mutableListOf() + private var messages: MutableList = mutableListOf() private var model: Model? = null - private var metadata: Metadata? = null - private var stopSequences: MutableList = mutableListOf() private var system: System? = null - private var temperature: Double? = null private var toolChoice: ToolChoice? = null - private var tools: MutableList = mutableListOf() - private var topK: Long? = null - private var topP: Double? = null - private var betas: MutableList = mutableListOf() + private var tools: MutableList = mutableListOf() private var additionalHeaders: Headers.Builder = Headers.builder() private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() private var additionalBodyProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from( - betaPromptCachingMessageCreateParams: BetaPromptCachingMessageCreateParams - ) = apply { - maxTokens = betaPromptCachingMessageCreateParams.maxTokens - messages = betaPromptCachingMessageCreateParams.messages.toMutableList() - model = betaPromptCachingMessageCreateParams.model - metadata = betaPromptCachingMessageCreateParams.metadata - stopSequences = - betaPromptCachingMessageCreateParams.stopSequences?.toMutableList() - ?: mutableListOf() - system = betaPromptCachingMessageCreateParams.system - temperature = betaPromptCachingMessageCreateParams.temperature - toolChoice = betaPromptCachingMessageCreateParams.toolChoice - tools = betaPromptCachingMessageCreateParams.tools?.toMutableList() ?: mutableListOf() - topK = betaPromptCachingMessageCreateParams.topK - topP = betaPromptCachingMessageCreateParams.topP - betas = betaPromptCachingMessageCreateParams.betas?.toMutableList() ?: mutableListOf() - additionalHeaders = betaPromptCachingMessageCreateParams.additionalHeaders.toBuilder() - additionalQueryParams = - betaPromptCachingMessageCreateParams.additionalQueryParams.toBuilder() + internal fun from(messageCountTokensParams: MessageCountTokensParams) = apply { + messages = messageCountTokensParams.messages.toMutableList() + model = messageCountTokensParams.model + system = messageCountTokensParams.system + toolChoice = messageCountTokensParams.toolChoice + tools = messageCountTokensParams.tools?.toMutableList() ?: mutableListOf() + additionalHeaders = messageCountTokensParams.additionalHeaders.toBuilder() + additionalQueryParams = messageCountTokensParams.additionalQueryParams.toBuilder() additionalBodyProperties = - betaPromptCachingMessageCreateParams.additionalBodyProperties.toMutableMap() + messageCountTokensParams.additionalBodyProperties.toMutableMap() } /** - * The maximum number of tokens to generate before stopping. + * Input messages. + * + * Our models are trained to operate on alternating `user` and `assistant` conversational + * turns. When creating a new `Message`, you specify the prior conversational turns with the + * `messages` parameter, and the model then generates the next `Message` in the + * conversation. Consecutive `user` or `assistant` turns in your request will be combined + * into a single turn. + * + * Each input message must be an object with a `role` and `content`. You can specify a + * single `user`-role message, or you can include multiple `user` and `assistant` messages. * - * Note that our models may stop _before_ reaching this maximum. This parameter only - * specifies the absolute maximum number of tokens to generate. + * If the final message uses the `assistant` role, the response content will continue + * immediately from the content in that message. This can be used to constrain part of the + * model's response. + * + * Example with a single `user` message: + * ```json + * [{ "role": "user", "content": "Hello, Claude" }] + * ``` * - * Different models have different maximum values for this parameter. See - * [models](https://docs.anthropic.com/en/docs/models-overview) for details. + * Example with multiple conversational turns: + * ```json + * [ + * { "role": "user", "content": "Hello there." }, + * { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + * { "role": "user", "content": "Can you explain LLMs in plain English?" } + * ] + * ``` + * + * Example with a partially-filled response from Claude: + * ```json + * [ + * { + * "role": "user", + * "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + * }, + * { "role": "assistant", "content": "The best answer is (" } + * ] + * ``` + * + * Each input message `content` may be either a single `string` or an array of content + * blocks, where each block has a specific `type`. Using a `string` for `content` is + * shorthand for an array of one content block of type `"text"`. The following input + * messages are equivalent: + * ```json + * { "role": "user", "content": "Hello, Claude" } + * ``` + * ```json + * { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + * ``` + * + * Starting with Claude 3 models, you can also send image content blocks: + * ```json + * { + * "role": "user", + * "content": [ + * { + * "type": "image", + * "source": { + * "type": "base64", + * "media_type": "image/jpeg", + * "data": "/9j/4AAQSkZJRg..." + * } + * }, + * { "type": "text", "text": "What is in this image?" } + * ] + * } + * ``` + * + * We currently support the `base64` source type for images, and the `image/jpeg`, + * `image/png`, `image/gif`, and `image/webp` media types. + * + * See [examples](https://docs.anthropic.com/en/api/messages-examples#vision) for more input + * examples. + * + * Note that if you want to include a + * [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use the + * top-level `system` parameter — there is no `"system"` role for input messages in the + * Messages API. */ - fun maxTokens(maxTokens: Long) = apply { this.maxTokens = maxTokens } + fun messages(messages: List) = apply { + this.messages.clear() + this.messages.addAll(messages) + } /** * Input messages. @@ -832,10 +701,7 @@ constructor( * top-level `system` parameter — there is no `"system"` role for input messages in the * Messages API. */ - fun messages(messages: List) = apply { - this.messages.clear() - this.messages.addAll(messages) - } + fun addMessage(message: MessageParam) = apply { this.messages.add(message) } /** * Input messages. @@ -918,9 +784,7 @@ constructor( * top-level `system` parameter — there is no `"system"` role for input messages in the * Messages API. */ - fun addMessage(message: PromptCachingBetaMessageParam) = apply { - this.messages.add(message) - } + fun addMessage(message: Message) = addMessage(message.toParam()) /** * The model that will complete your prompt.\n\nSee @@ -936,38 +800,6 @@ constructor( */ fun model(value: String) = apply { this.model = Model.of(value) } - /** An object describing metadata about the request. */ - fun metadata(metadata: Metadata) = apply { this.metadata = metadata } - - /** - * Custom text sequences that will cause the model to stop generating. - * - * Our models will normally stop when they have naturally completed their turn, which will - * result in a response `stop_reason` of `"end_turn"`. - * - * If you want the model to stop generating when it encounters custom strings of text, you - * can use the `stop_sequences` parameter. If the model encounters one of the custom - * sequences, the response `stop_reason` value will be `"stop_sequence"` and the response - * `stop_sequence` value will contain the matched stop sequence. - */ - fun stopSequences(stopSequences: List) = apply { - this.stopSequences.clear() - this.stopSequences.addAll(stopSequences) - } - - /** - * Custom text sequences that will cause the model to stop generating. - * - * Our models will normally stop when they have naturally completed their turn, which will - * result in a response `stop_reason` of `"end_turn"`. - * - * If you want the model to stop generating when it encounters custom strings of text, you - * can use the `stop_sequences` parameter. If the model encounters one of the custom - * sequences, the response `stop_reason` value will be `"stop_sequence"` and the response - * `stop_sequence` value will contain the matched stop sequence. - */ - fun addStopSequence(stopSequence: String) = apply { this.stopSequences.add(stopSequence) } - /** * System prompt. * @@ -993,23 +825,10 @@ constructor( * specifying a particular goal or role. See our * [guide to system prompts](https://docs.anthropic.com/en/docs/system-prompts). */ - fun systemOfPromptCachingBetaTextBlockParams( - promptCachingBetaTextBlockParams: List - ) = apply { - this.system = - System.ofPromptCachingBetaTextBlockParams(promptCachingBetaTextBlockParams) + fun systemOfTextBlockParams(textBlockParams: List) = apply { + this.system = System.ofTextBlockParams(textBlockParams) } - /** - * Amount of randomness injected into the response. - * - * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for - * analytical / multiple choice, and closer to `1.0` for creative and generative tasks. - * - * Note that even with `temperature` of `0.0`, the results will not be fully deterministic. - */ - fun temperature(temperature: Double) = apply { this.temperature = temperature } - /** * How the model should use the provided tools. The model can use a specific tool, any * available tool, or decide by itself. @@ -1105,7 +924,7 @@ constructor( * * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details. */ - fun tools(tools: List) = apply { + fun tools(tools: List) = apply { this.tools.clear() this.tools.addAll(tools) } @@ -1175,38 +994,7 @@ constructor( * * See our [guide](https://docs.anthropic.com/en/docs/tool-use) for more details. */ - fun addTool(tool: PromptCachingBetaTool) = apply { this.tools.add(tool) } - - /** - * Only sample from the top K options for each subsequent token. - * - * Used to remove "long tail" low probability responses. - * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). - * - * Recommended for advanced use cases only. You usually only need to use `temperature`. - */ - fun topK(topK: Long) = apply { this.topK = topK } - - /** - * Use nucleus sampling. - * - * In nucleus sampling, we compute the cumulative distribution over all the options for each - * subsequent token in decreasing probability order and cut it off once it reaches a - * particular probability specified by `top_p`. You should either alter `temperature` or - * `top_p`, but not both. - * - * Recommended for advanced use cases only. You usually only need to use `temperature`. - */ - fun topP(topP: Double) = apply { this.topP = topP } - - /** Optional header to specify the beta version(s) you want to use. */ - fun betas(betas: List) = apply { - this.betas.clear() - this.betas.addAll(betas) - } - - /** Optional header to specify the beta version(s) you want to use. */ - fun addBeta(beta: AnthropicBeta) = apply { this.betas.add(beta) } + fun addTool(tool: Tool) = apply { this.tools.add(tool) } fun additionalHeaders(additionalHeaders: Headers) = apply { this.additionalHeaders.clear() @@ -1328,20 +1116,13 @@ constructor( keys.forEach(::removeAdditionalBodyProperty) } - fun build(): BetaPromptCachingMessageCreateParams = - BetaPromptCachingMessageCreateParams( - checkNotNull(maxTokens) { "`maxTokens` is required but was not set" }, + fun build(): MessageCountTokensParams = + MessageCountTokensParams( messages.toImmutable(), checkNotNull(model) { "`model` is required but was not set" }, - metadata, - stopSequences.toImmutable().ifEmpty { null }, system, - temperature, toolChoice, tools.toImmutable().ifEmpty { null }, - topK, - topP, - betas.toImmutable().ifEmpty { null }, additionalHeaders.build(), additionalQueryParams.build(), additionalBodyProperties.toImmutable(), @@ -1353,7 +1134,7 @@ constructor( class System private constructor( private val string: String? = null, - private val promptCachingBetaTextBlockParams: List? = null, + private val textBlockParams: List? = null, private val _json: JsonValue? = null, ) { @@ -1361,35 +1142,33 @@ constructor( fun string(): Optional = Optional.ofNullable(string) - fun promptCachingBetaTextBlockParams(): Optional> = - Optional.ofNullable(promptCachingBetaTextBlockParams) + fun textBlockParams(): Optional> = Optional.ofNullable(textBlockParams) fun isString(): Boolean = string != null - fun isPromptCachingBetaTextBlockParams(): Boolean = promptCachingBetaTextBlockParams != null + fun isTextBlockParams(): Boolean = textBlockParams != null fun asString(): String = string.getOrThrow("string") - fun asPromptCachingBetaTextBlockParams(): List = - promptCachingBetaTextBlockParams.getOrThrow("promptCachingBetaTextBlockParams") + fun asTextBlockParams(): List = + textBlockParams.getOrThrow("textBlockParams") fun _json(): Optional = Optional.ofNullable(_json) fun accept(visitor: Visitor): T { return when { string != null -> visitor.visitString(string) - promptCachingBetaTextBlockParams != null -> - visitor.visitPromptCachingBetaTextBlockParams(promptCachingBetaTextBlockParams) + textBlockParams != null -> visitor.visitTextBlockParams(textBlockParams) else -> visitor.unknown(_json) } } fun validate(): System = apply { if (!validated) { - if (string == null && promptCachingBetaTextBlockParams == null) { + if (string == null && textBlockParams == null) { throw AnthropicInvalidDataException("Unknown System: $_json") } - promptCachingBetaTextBlockParams?.forEach { it.validate() } + textBlockParams?.forEach { it.validate() } validated = true } } @@ -1399,16 +1178,15 @@ constructor( return true } - return /* spotless:off */ other is System && string == other.string && promptCachingBetaTextBlockParams == other.promptCachingBetaTextBlockParams /* spotless:on */ + return /* spotless:off */ other is System && string == other.string && textBlockParams == other.textBlockParams /* spotless:on */ } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, promptCachingBetaTextBlockParams) /* spotless:on */ + override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, textBlockParams) /* spotless:on */ override fun toString(): String = when { string != null -> "System{string=$string}" - promptCachingBetaTextBlockParams != null -> - "System{promptCachingBetaTextBlockParams=$promptCachingBetaTextBlockParams}" + textBlockParams != null -> "System{textBlockParams=$textBlockParams}" _json != null -> "System{_unknown=$_json}" else -> throw IllegalStateException("Invalid System") } @@ -1418,18 +1196,15 @@ constructor( @JvmStatic fun ofString(string: String) = System(string = string) @JvmStatic - fun ofPromptCachingBetaTextBlockParams( - promptCachingBetaTextBlockParams: List - ) = System(promptCachingBetaTextBlockParams = promptCachingBetaTextBlockParams) + fun ofTextBlockParams(textBlockParams: List) = + System(textBlockParams = textBlockParams) } interface Visitor { fun visitString(string: String): T - fun visitPromptCachingBetaTextBlockParams( - promptCachingBetaTextBlockParams: List - ): T + fun visitTextBlockParams(textBlockParams: List): T fun unknown(json: JsonValue?): T { throw AnthropicInvalidDataException("Unknown System: $json") @@ -1444,11 +1219,11 @@ constructor( tryDeserialize(node, jacksonTypeRef())?.let { return System(string = it, _json = json) } - tryDeserialize(node, jacksonTypeRef>()) { + tryDeserialize(node, jacksonTypeRef>()) { it.forEach { it.validate() } } ?.let { - return System(promptCachingBetaTextBlockParams = it, _json = json) + return System(textBlockParams = it, _json = json) } return System(_json = json) @@ -1464,8 +1239,7 @@ constructor( ) { when { value.string != null -> generator.writeObject(value.string) - value.promptCachingBetaTextBlockParams != null -> - generator.writeObject(value.promptCachingBetaTextBlockParams) + value.textBlockParams != null -> generator.writeObject(value.textBlockParams) value._json != null -> generator.writeObject(value._json) else -> throw IllegalStateException("Invalid System") } @@ -1478,11 +1252,11 @@ constructor( return true } - return /* spotless:off */ other is BetaPromptCachingMessageCreateParams && maxTokens == other.maxTokens && messages == other.messages && model == other.model && metadata == other.metadata && stopSequences == other.stopSequences && system == other.system && temperature == other.temperature && toolChoice == other.toolChoice && tools == other.tools && topK == other.topK && topP == other.topP && betas == other.betas && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ + return /* spotless:off */ other is MessageCountTokensParams && messages == other.messages && model == other.model && system == other.system && toolChoice == other.toolChoice && tools == other.tools && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams && additionalBodyProperties == other.additionalBodyProperties /* spotless:on */ } - override fun hashCode(): Int = /* spotless:off */ Objects.hash(maxTokens, messages, model, metadata, stopSequences, system, temperature, toolChoice, tools, topK, topP, betas, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ + override fun hashCode(): Int = /* spotless:off */ Objects.hash(messages, model, system, toolChoice, tools, additionalHeaders, additionalQueryParams, additionalBodyProperties) /* spotless:on */ override fun toString() = - "BetaPromptCachingMessageCreateParams{maxTokens=$maxTokens, messages=$messages, model=$model, metadata=$metadata, stopSequences=$stopSequences, system=$system, temperature=$temperature, toolChoice=$toolChoice, tools=$tools, topK=$topK, topP=$topP, betas=$betas, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" + "MessageCountTokensParams{messages=$messages, model=$model, system=$system, toolChoice=$toolChoice, tools=$tools, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams, additionalBodyProperties=$additionalBodyProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageTokensCount.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageTokensCount.kt new file mode 100644 index 0000000..52dcc50 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/MessageTokensCount.kt @@ -0,0 +1,114 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = MessageTokensCount.Builder::class) +@NoAutoDetect +class MessageTokensCount +private constructor( + private val inputTokens: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + /** + * The total number of tokens across the provided list of messages, system prompt, and tools. + */ + fun inputTokens(): Long = inputTokens.getRequired("input_tokens") + + /** + * The total number of tokens across the provided list of messages, system prompt, and tools. + */ + @JsonProperty("input_tokens") @ExcludeMissing fun _inputTokens() = inputTokens + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): MessageTokensCount = apply { + if (!validated) { + inputTokens() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var inputTokens: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(messageTokensCount: MessageTokensCount) = apply { + this.inputTokens = messageTokensCount.inputTokens + additionalProperties(messageTokensCount.additionalProperties) + } + + /** + * The total number of tokens across the provided list of messages, system prompt, and + * tools. + */ + fun inputTokens(inputTokens: Long) = inputTokens(JsonField.of(inputTokens)) + + /** + * The total number of tokens across the provided list of messages, system prompt, and + * tools. + */ + @JsonProperty("input_tokens") + @ExcludeMissing + fun inputTokens(inputTokens: JsonField) = apply { this.inputTokens = inputTokens } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): MessageTokensCount = + MessageTokensCount(inputTokens, additionalProperties.toImmutable()) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is MessageTokensCount && inputTokens == other.inputTokens && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(inputTokens, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "MessageTokensCount{inputTokens=$inputTokens, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaToolUseBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelInfo.kt similarity index 52% rename from anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaToolUseBlockParam.kt rename to anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelInfo.kt index 12ca5af..7c0015b 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaToolUseBlockParam.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelInfo.kt @@ -15,52 +15,70 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.time.OffsetDateTime import java.util.Objects -import java.util.Optional -@JsonDeserialize(builder = PromptCachingBetaToolUseBlockParam.Builder::class) +@JsonDeserialize(builder = ModelInfo.Builder::class) @NoAutoDetect -class PromptCachingBetaToolUseBlockParam +class ModelInfo private constructor( - private val cacheControl: JsonField, private val type: JsonField, private val id: JsonField, - private val name: JsonField, - private val input: JsonValue, + private val displayName: JsonField, + private val createdAt: JsonField, private val additionalProperties: Map, ) { private var validated: Boolean = false - fun cacheControl(): Optional = - Optional.ofNullable(cacheControl.getNullable("cache_control")) - + /** + * Object type. + * + * For Models, this is always `"model"`. + */ fun type(): Type = type.getRequired("type") + /** Unique model identifier. */ fun id(): String = id.getRequired("id") - fun name(): String = name.getRequired("name") + /** A human-readable name for the model. */ + fun displayName(): String = displayName.getRequired("display_name") - @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl + /** + * RFC 3339 datetime string representing the time at which the model was released. May be set to + * an epoch value if the release date is unknown. + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + /** + * Object type. + * + * For Models, this is always `"model"`. + */ @JsonProperty("type") @ExcludeMissing fun _type() = type + /** Unique model identifier. */ @JsonProperty("id") @ExcludeMissing fun _id() = id - @JsonProperty("name") @ExcludeMissing fun _name() = name + /** A human-readable name for the model. */ + @JsonProperty("display_name") @ExcludeMissing fun _displayName() = displayName - @JsonProperty("input") @ExcludeMissing fun _input() = input + /** + * RFC 3339 datetime string representing the time at which the model was released. May be set to + * an epoch value if the release date is unknown. + */ + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties - fun validate(): PromptCachingBetaToolUseBlockParam = apply { + fun validate(): ModelInfo = apply { if (!validated) { - cacheControl().map { it.validate() } type() id() - name() + displayName() + createdAt() validated = true } } @@ -74,53 +92,64 @@ private constructor( class Builder { - private var cacheControl: JsonField = - JsonMissing.of() private var type: JsonField = JsonMissing.of() private var id: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var input: JsonValue = JsonMissing.of() + private var displayName: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic - internal fun from(promptCachingBetaToolUseBlockParam: PromptCachingBetaToolUseBlockParam) = - apply { - this.cacheControl = promptCachingBetaToolUseBlockParam.cacheControl - this.type = promptCachingBetaToolUseBlockParam.type - this.id = promptCachingBetaToolUseBlockParam.id - this.name = promptCachingBetaToolUseBlockParam.name - this.input = promptCachingBetaToolUseBlockParam.input - additionalProperties(promptCachingBetaToolUseBlockParam.additionalProperties) - } - - fun cacheControl(cacheControl: PromptCachingBetaCacheControlEphemeral) = - cacheControl(JsonField.of(cacheControl)) - - @JsonProperty("cache_control") - @ExcludeMissing - fun cacheControl(cacheControl: JsonField) = apply { - this.cacheControl = cacheControl + internal fun from(modelInfo: ModelInfo) = apply { + this.type = modelInfo.type + this.id = modelInfo.id + this.displayName = modelInfo.displayName + this.createdAt = modelInfo.createdAt + additionalProperties(modelInfo.additionalProperties) } + /** + * Object type. + * + * For Models, this is always `"model"`. + */ fun type(type: Type) = type(JsonField.of(type)) + /** + * Object type. + * + * For Models, this is always `"model"`. + */ @JsonProperty("type") @ExcludeMissing fun type(type: JsonField) = apply { this.type = type } + /** Unique model identifier. */ fun id(id: String) = id(JsonField.of(id)) + /** Unique model identifier. */ @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } - fun name(name: String) = name(JsonField.of(name)) + /** A human-readable name for the model. */ + fun displayName(displayName: String) = displayName(JsonField.of(displayName)) - @JsonProperty("name") + /** A human-readable name for the model. */ + @JsonProperty("display_name") @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - @JsonProperty("input") + fun displayName(displayName: JsonField) = apply { this.displayName = displayName } + + /** + * RFC 3339 datetime string representing the time at which the model was released. May be + * set to an epoch value if the release date is unknown. + */ + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * RFC 3339 datetime string representing the time at which the model was released. May be + * set to an epoch value if the release date is unknown. + */ + @JsonProperty("created_at") @ExcludeMissing - fun input(input: JsonValue) = apply { this.input = input } + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() @@ -136,13 +165,12 @@ private constructor( this.additionalProperties.putAll(additionalProperties) } - fun build(): PromptCachingBetaToolUseBlockParam = - PromptCachingBetaToolUseBlockParam( - cacheControl, + fun build(): ModelInfo = + ModelInfo( type, id, - name, - input, + displayName, + createdAt, additionalProperties.toImmutable(), ) } @@ -157,29 +185,29 @@ private constructor( companion object { - @JvmField val TOOL_USE = of("tool_use") + @JvmField val MODEL = of("model") @JvmStatic fun of(value: String) = Type(JsonField.of(value)) } enum class Known { - TOOL_USE, + MODEL, } enum class Value { - TOOL_USE, + MODEL, _UNKNOWN, } fun value(): Value = when (this) { - TOOL_USE -> Value.TOOL_USE + MODEL -> Value.MODEL else -> Value._UNKNOWN } fun known(): Known = when (this) { - TOOL_USE -> Known.TOOL_USE + MODEL -> Known.MODEL else -> throw AnthropicInvalidDataException("Unknown Type: $value") } @@ -203,15 +231,15 @@ private constructor( return true } - return /* spotless:off */ other is PromptCachingBetaToolUseBlockParam && cacheControl == other.cacheControl && type == other.type && id == other.id && name == other.name && input == other.input && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is ModelInfo && type == other.type && id == other.id && displayName == other.displayName && createdAt == other.createdAt && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cacheControl, type, id, name, input, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(type, id, displayName, createdAt, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "PromptCachingBetaToolUseBlockParam{cacheControl=$cacheControl, type=$type, id=$id, name=$name, input=$input, additionalProperties=$additionalProperties}" + "ModelInfo{type=$type, id=$id, displayName=$displayName, createdAt=$createdAt, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListPage.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListPage.kt new file mode 100644 index 0000000..c6200d9 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListPage.kt @@ -0,0 +1,230 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.services.blocking.ModelService +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class ModelListPage +private constructor( + private val modelsService: ModelService, + private val params: ModelListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun hasMore(): Optional = response().hasMore() + + fun firstId(): Optional = response().firstId() + + fun lastId(): Optional = response().lastId() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ModelListPage && modelsService == other.modelsService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(modelsService, params, response) /* spotless:on */ + + override fun toString() = + "ModelListPage{modelsService=$modelsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + if (data().isEmpty()) { + return false + } + + return lastId().isPresent + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + ModelListParams.builder() + .from(params) + .apply { lastId().ifPresent { this.afterId(it) } } + .build() + ) + } + + fun getNextPage(): Optional { + return getNextPageParams().map { modelsService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(modelsService: ModelService, params: ModelListParams, response: Response) = + ModelListPage( + modelsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val hasMore: JsonField, + private val firstId: JsonField, + private val lastId: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun hasMore(): Optional = Optional.ofNullable(hasMore.getNullable("has_more")) + + fun firstId(): Optional = Optional.ofNullable(firstId.getNullable("first_id")) + + fun lastId(): Optional = Optional.ofNullable(lastId.getNullable("last_id")) + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("has_more") + fun _hasMore(): Optional> = Optional.ofNullable(hasMore) + + @JsonProperty("first_id") + fun _firstId(): Optional> = Optional.ofNullable(firstId) + + @JsonProperty("last_id") + fun _lastId(): Optional> = Optional.ofNullable(lastId) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + hasMore() + firstId() + lastId() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && data == other.data && hasMore == other.hasMore && firstId == other.firstId && lastId == other.lastId && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, hasMore, firstId, lastId, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{data=$data, hasMore=$hasMore, firstId=$firstId, lastId=$lastId, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var hasMore: JsonField = JsonMissing.of() + private var firstId: JsonField = JsonMissing.of() + private var lastId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.hasMore = page.hasMore + this.firstId = page.firstId + this.lastId = page.lastId + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun hasMore(hasMore: Boolean) = hasMore(JsonField.of(hasMore)) + + @JsonProperty("has_more") + fun hasMore(hasMore: JsonField) = apply { this.hasMore = hasMore } + + fun firstId(firstId: String) = firstId(JsonField.of(firstId)) + + @JsonProperty("first_id") + fun firstId(firstId: JsonField) = apply { this.firstId = firstId } + + fun lastId(lastId: String) = lastId(JsonField.of(lastId)) + + @JsonProperty("last_id") + fun lastId(lastId: JsonField) = apply { this.lastId = lastId } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + hasMore, + firstId, + lastId, + additionalProperties.toImmutable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: ModelListPage, + ) : Iterable { + + override fun iterator(): Iterator = iterator { + var page = firstPage + var index = 0 + while (true) { + while (index < page.data().size) { + yield(page.data()[index++]) + } + page = page.getNextPage().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListPageAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListPageAsync.kt new file mode 100644 index 0000000..a7739de --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListPageAsync.kt @@ -0,0 +1,240 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.services.async.ModelServiceAsync +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class ModelListPageAsync +private constructor( + private val modelsService: ModelServiceAsync, + private val params: ModelListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun hasMore(): Optional = response().hasMore() + + fun firstId(): Optional = response().firstId() + + fun lastId(): Optional = response().lastId() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ModelListPageAsync && modelsService == other.modelsService && params == other.params && response == other.response /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(modelsService, params, response) /* spotless:on */ + + override fun toString() = + "ModelListPageAsync{modelsService=$modelsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + if (data().isEmpty()) { + return false + } + + return lastId().isPresent + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + ModelListParams.builder() + .from(params) + .apply { lastId().ifPresent { this.afterId(it) } } + .build() + ) + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { modelsService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(modelsService: ModelServiceAsync, params: ModelListParams, response: Response) = + ModelListPageAsync( + modelsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val hasMore: JsonField, + private val firstId: JsonField, + private val lastId: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun hasMore(): Optional = Optional.ofNullable(hasMore.getNullable("has_more")) + + fun firstId(): Optional = Optional.ofNullable(firstId.getNullable("first_id")) + + fun lastId(): Optional = Optional.ofNullable(lastId.getNullable("last_id")) + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("has_more") + fun _hasMore(): Optional> = Optional.ofNullable(hasMore) + + @JsonProperty("first_id") + fun _firstId(): Optional> = Optional.ofNullable(firstId) + + @JsonProperty("last_id") + fun _lastId(): Optional> = Optional.ofNullable(lastId) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + hasMore() + firstId() + lastId() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Response && data == other.data && hasMore == other.hasMore && firstId == other.firstId && lastId == other.lastId && additionalProperties == other.additionalProperties /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(data, hasMore, firstId, lastId, additionalProperties) /* spotless:on */ + + override fun toString() = + "Response{data=$data, hasMore=$hasMore, firstId=$firstId, lastId=$lastId, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var hasMore: JsonField = JsonMissing.of() + private var firstId: JsonField = JsonMissing.of() + private var lastId: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.hasMore = page.hasMore + this.firstId = page.firstId + this.lastId = page.lastId + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun hasMore(hasMore: Boolean) = hasMore(JsonField.of(hasMore)) + + @JsonProperty("has_more") + fun hasMore(hasMore: JsonField) = apply { this.hasMore = hasMore } + + fun firstId(firstId: String) = firstId(JsonField.of(firstId)) + + @JsonProperty("first_id") + fun firstId(firstId: JsonField) = apply { this.firstId = firstId } + + fun lastId(lastId: String) = lastId(JsonField.of(lastId)) + + @JsonProperty("last_id") + fun lastId(lastId: JsonField) = apply { this.lastId = lastId } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + hasMore, + firstId, + lastId, + additionalProperties.toImmutable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: ModelListPageAsync, + ) { + + fun forEach(action: Predicate, executor: Executor): CompletableFuture { + fun CompletableFuture>.forEach( + action: (ModelInfo) -> Boolean, + executor: Executor + ): CompletableFuture = + thenComposeAsync( + { page -> + page + .filter { it.data().all(action) } + .map { it.getNextPage().forEach(action, executor) } + .orElseGet { CompletableFuture.completedFuture(null) } + }, + executor + ) + return CompletableFuture.completedFuture(Optional.of(firstPage)) + .forEach(action::test, executor) + } + + fun toList(executor: Executor): CompletableFuture> { + val values = mutableListOf() + return forEach(values::add, executor).thenApply { values } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListParams.kt new file mode 100644 index 0000000..32dc13e --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelListParams.kt @@ -0,0 +1,206 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import java.util.Objects +import java.util.Optional + +class ModelListParams +constructor( + private val afterId: String?, + private val beforeId: String?, + private val limit: Long?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) { + + fun afterId(): Optional = Optional.ofNullable(afterId) + + fun beforeId(): Optional = Optional.ofNullable(beforeId) + + fun limit(): Optional = Optional.ofNullable(limit) + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic + internal fun getQueryParams(): QueryParams { + val queryParams = QueryParams.builder() + this.afterId?.let { queryParams.put("after_id", listOf(it.toString())) } + this.beforeId?.let { queryParams.put("before_id", listOf(it.toString())) } + this.limit?.let { queryParams.put("limit", listOf(it.toString())) } + queryParams.putAll(additionalQueryParams) + return queryParams.build() + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var afterId: String? = null + private var beforeId: String? = null + private var limit: Long? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(modelListParams: ModelListParams) = apply { + afterId = modelListParams.afterId + beforeId = modelListParams.beforeId + limit = modelListParams.limit + additionalHeaders = modelListParams.additionalHeaders.toBuilder() + additionalQueryParams = modelListParams.additionalQueryParams.toBuilder() + } + + /** + * ID of the object to use as a cursor for pagination. When provided, returns the page of + * results immediately after this object. + */ + fun afterId(afterId: String) = apply { this.afterId = afterId } + + /** + * ID of the object to use as a cursor for pagination. When provided, returns the page of + * results immediately before this object. + */ + fun beforeId(beforeId: String) = apply { this.beforeId = beforeId } + + /** + * Number of items to return per page. + * + * Defaults to `20`. Ranges from `1` to `1000`. + */ + fun limit(limit: Long) = apply { this.limit = limit } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun build(): ModelListParams = + ModelListParams( + afterId, + beforeId, + limit, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ModelListParams && afterId == other.afterId && beforeId == other.beforeId && limit == other.limit && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(afterId, beforeId, limit, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "ModelListParams{afterId=$afterId, beforeId=$beforeId, limit=$limit, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelRetrieveParams.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelRetrieveParams.kt new file mode 100644 index 0000000..8b748d9 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ModelRetrieveParams.kt @@ -0,0 +1,176 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.http.Headers +import com.anthropic.core.http.QueryParams +import java.util.Objects + +class ModelRetrieveParams +constructor( + private val modelId: String, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) { + + fun modelId(): String = modelId + + fun _additionalHeaders(): Headers = additionalHeaders + + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Headers = additionalHeaders + + @JvmSynthetic internal fun getQueryParams(): QueryParams = additionalQueryParams + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> modelId + else -> "" + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var modelId: String? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(modelRetrieveParams: ModelRetrieveParams) = apply { + modelId = modelRetrieveParams.modelId + additionalHeaders = modelRetrieveParams.additionalHeaders.toBuilder() + additionalQueryParams = modelRetrieveParams.additionalQueryParams.toBuilder() + } + + /** Model identifier or alias. */ + fun modelId(modelId: String) = apply { this.modelId = modelId } + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + fun build(): ModelRetrieveParams = + ModelRetrieveParams( + checkNotNull(modelId) { "`modelId` is required but was not set" }, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is ModelRetrieveParams && modelId == other.modelId && additionalHeaders == other.additionalHeaders && additionalQueryParams == other.additionalQueryParams /* spotless:on */ + } + + override fun hashCode(): Int = /* spotless:off */ Objects.hash(modelId, additionalHeaders, additionalQueryParams) /* spotless:on */ + + override fun toString() = + "ModelRetrieveParams{modelId=$modelId, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/NotFoundError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/NotFoundError.kt new file mode 100644 index 0000000..4848916 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/NotFoundError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = NotFoundError.Builder::class) +@NoAutoDetect +class NotFoundError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): NotFoundError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(notFoundError: NotFoundError) = apply { + this.type = notFoundError.type + this.message = notFoundError.message + additionalProperties(notFoundError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): NotFoundError = + NotFoundError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val NOT_FOUND_ERROR = of("not_found_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + NOT_FOUND_ERROR, + } + + enum class Value { + NOT_FOUND_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + NOT_FOUND_ERROR -> Value.NOT_FOUND_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + NOT_FOUND_ERROR -> Known.NOT_FOUND_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is NotFoundError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "NotFoundError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/OverloadedError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/OverloadedError.kt new file mode 100644 index 0000000..96c6528 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/OverloadedError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = OverloadedError.Builder::class) +@NoAutoDetect +class OverloadedError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): OverloadedError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(overloadedError: OverloadedError) = apply { + this.type = overloadedError.type + this.message = overloadedError.message + additionalProperties(overloadedError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): OverloadedError = + OverloadedError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val OVERLOADED_ERROR = of("overloaded_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + OVERLOADED_ERROR, + } + + enum class Value { + OVERLOADED_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + OVERLOADED_ERROR -> Value.OVERLOADED_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + OVERLOADED_ERROR -> Known.OVERLOADED_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is OverloadedError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "OverloadedError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PermissionError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PermissionError.kt new file mode 100644 index 0000000..5852711 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PermissionError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = PermissionError.Builder::class) +@NoAutoDetect +class PermissionError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): PermissionError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(permissionError: PermissionError) = apply { + this.type = permissionError.type + this.message = permissionError.message + additionalProperties(permissionError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): PermissionError = + PermissionError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val PERMISSION_ERROR = of("permission_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + PERMISSION_ERROR, + } + + enum class Value { + PERMISSION_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + PERMISSION_ERROR -> Value.PERMISSION_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + PERMISSION_ERROR -> Known.PERMISSION_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is PermissionError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "PermissionError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaImageBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaImageBlockParam.kt deleted file mode 100644 index 11d098f..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaImageBlockParam.kt +++ /dev/null @@ -1,432 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.Enum -import com.anthropic.core.ExcludeMissing -import com.anthropic.core.JsonField -import com.anthropic.core.JsonMissing -import com.anthropic.core.JsonValue -import com.anthropic.core.NoAutoDetect -import com.anthropic.core.toImmutable -import com.anthropic.errors.AnthropicInvalidDataException -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = PromptCachingBetaImageBlockParam.Builder::class) -@NoAutoDetect -class PromptCachingBetaImageBlockParam -private constructor( - private val cacheControl: JsonField, - private val type: JsonField, - private val source: JsonField, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - fun cacheControl(): Optional = - Optional.ofNullable(cacheControl.getNullable("cache_control")) - - fun type(): Type = type.getRequired("type") - - fun source(): Source = source.getRequired("source") - - @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl - - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonProperty("source") @ExcludeMissing fun _source() = source - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): PromptCachingBetaImageBlockParam = apply { - if (!validated) { - cacheControl().map { it.validate() } - type() - source().validate() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var cacheControl: JsonField = - JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var source: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(promptCachingBetaImageBlockParam: PromptCachingBetaImageBlockParam) = - apply { - this.cacheControl = promptCachingBetaImageBlockParam.cacheControl - this.type = promptCachingBetaImageBlockParam.type - this.source = promptCachingBetaImageBlockParam.source - additionalProperties(promptCachingBetaImageBlockParam.additionalProperties) - } - - fun cacheControl(cacheControl: PromptCachingBetaCacheControlEphemeral) = - cacheControl(JsonField.of(cacheControl)) - - @JsonProperty("cache_control") - @ExcludeMissing - fun cacheControl(cacheControl: JsonField) = apply { - this.cacheControl = cacheControl - } - - fun type(type: Type) = type(JsonField.of(type)) - - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - fun source(source: Source) = source(JsonField.of(source)) - - @JsonProperty("source") - @ExcludeMissing - fun source(source: JsonField) = apply { this.source = source } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): PromptCachingBetaImageBlockParam = - PromptCachingBetaImageBlockParam( - cacheControl, - type, - source, - additionalProperties.toImmutable(), - ) - } - - @JsonDeserialize(builder = Source.Builder::class) - @NoAutoDetect - class Source - private constructor( - private val type: JsonField, - private val mediaType: JsonField, - private val data: JsonField, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - fun type(): Type = type.getRequired("type") - - fun mediaType(): MediaType = mediaType.getRequired("media_type") - - fun data(): String = data.getRequired("data") - - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonProperty("media_type") @ExcludeMissing fun _mediaType() = mediaType - - @JsonProperty("data") @ExcludeMissing fun _data() = data - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): Source = apply { - if (!validated) { - type() - mediaType() - data() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var type: JsonField = JsonMissing.of() - private var mediaType: JsonField = JsonMissing.of() - private var data: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(source: Source) = apply { - this.type = source.type - this.mediaType = source.mediaType - this.data = source.data - additionalProperties(source.additionalProperties) - } - - fun type(type: Type) = type(JsonField.of(type)) - - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - fun mediaType(mediaType: MediaType) = mediaType(JsonField.of(mediaType)) - - @JsonProperty("media_type") - @ExcludeMissing - fun mediaType(mediaType: JsonField) = apply { this.mediaType = mediaType } - - fun data(data: String) = data(JsonField.of(data)) - - @JsonProperty("data") - @ExcludeMissing - fun data(data: JsonField) = apply { this.data = data } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): Source = - Source( - type, - mediaType, - data, - additionalProperties.toImmutable(), - ) - } - - class MediaType - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IMAGE_JPEG = of("image/jpeg") - - @JvmField val IMAGE_PNG = of("image/png") - - @JvmField val IMAGE_GIF = of("image/gif") - - @JvmField val IMAGE_WEBP = of("image/webp") - - @JvmStatic fun of(value: String) = MediaType(JsonField.of(value)) - } - - enum class Known { - IMAGE_JPEG, - IMAGE_PNG, - IMAGE_GIF, - IMAGE_WEBP, - } - - enum class Value { - IMAGE_JPEG, - IMAGE_PNG, - IMAGE_GIF, - IMAGE_WEBP, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - IMAGE_JPEG -> Value.IMAGE_JPEG - IMAGE_PNG -> Value.IMAGE_PNG - IMAGE_GIF -> Value.IMAGE_GIF - IMAGE_WEBP -> Value.IMAGE_WEBP - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - IMAGE_JPEG -> Known.IMAGE_JPEG - IMAGE_PNG -> Known.IMAGE_PNG - IMAGE_GIF -> Known.IMAGE_GIF - IMAGE_WEBP -> Known.IMAGE_WEBP - else -> throw AnthropicInvalidDataException("Unknown MediaType: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is MediaType && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val BASE64 = of("base64") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - BASE64, - } - - enum class Value { - BASE64, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - BASE64 -> Value.BASE64 - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - BASE64 -> Known.BASE64 - else -> throw AnthropicInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Source && type == other.type && mediaType == other.mediaType && data == other.data && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, mediaType, data, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "Source{type=$type, mediaType=$mediaType, data=$data, additionalProperties=$additionalProperties}" - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val IMAGE = of("image") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - IMAGE, - } - - enum class Value { - IMAGE, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - IMAGE -> Value.IMAGE - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - IMAGE -> Known.IMAGE - else -> throw AnthropicInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptCachingBetaImageBlockParam && cacheControl == other.cacheControl && type == other.type && source == other.source && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cacheControl, type, source, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PromptCachingBetaImageBlockParam{cacheControl=$cacheControl, type=$type, source=$source, additionalProperties=$additionalProperties}" -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaMessage.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaMessage.kt deleted file mode 100644 index 96c2d75..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaMessage.kt +++ /dev/null @@ -1,705 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.Enum -import com.anthropic.core.ExcludeMissing -import com.anthropic.core.JsonField -import com.anthropic.core.JsonMissing -import com.anthropic.core.JsonValue -import com.anthropic.core.NoAutoDetect -import com.anthropic.core.toImmutable -import com.anthropic.errors.AnthropicInvalidDataException -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = PromptCachingBetaMessage.Builder::class) -@NoAutoDetect -class PromptCachingBetaMessage -private constructor( - private val id: JsonField, - private val type: JsonField, - private val role: JsonField, - private val content: JsonField>, - private val model: JsonField, - private val stopReason: JsonField, - private val stopSequence: JsonField, - private val usage: JsonField, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - /** - * Unique object identifier. - * - * The format and length of IDs may change over time. - */ - fun id(): String = id.getRequired("id") - - /** - * Object type. - * - * For Messages, this is always `"message"`. - */ - fun type(): Type = type.getRequired("type") - - /** - * Conversational role of the generated message. - * - * This will always be `"assistant"`. - */ - fun role(): Role = role.getRequired("role") - - /** - * Content generated by the model. - * - * This is an array of content blocks, each of which has a `type` that determines its shape. - * - * Example: - * ```json - * [{ "type": "text", "text": "Hi, I'm Claude." }] - * ``` - * - * If the request input `messages` ended with an `assistant` turn, then the response `content` - * will continue directly from that last turn. You can use this to constrain the model's output. - * - * For example, if the input `messages` were: - * ```json - * [ - * { - * "role": "user", - * "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - * }, - * { "role": "assistant", "content": "The best answer is (" } - * ] - * ``` - * - * Then the response `content` might be: - * ```json - * [{ "type": "text", "text": "B)" }] - * ``` - */ - fun content(): List = content.getRequired("content") - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and - * options. - */ - fun model(): Model = model.getRequired("model") - - /** - * The reason that we stopped. - * - * This may be one the following values: - * - `"end_turn"`: the model reached a natural stopping point - * - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - * - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - * - `"tool_use"`: the model invoked one or more tools - * - * In non-streaming mode this value is always non-null. In streaming mode, it is null in the - * `message_start` event and non-null otherwise. - */ - fun stopReason(): Optional = - Optional.ofNullable(stopReason.getNullable("stop_reason")) - - /** - * Which custom stop sequence was generated, if any. - * - * This value will be a non-null string if one of your custom stop sequences was generated. - */ - fun stopSequence(): Optional = - Optional.ofNullable(stopSequence.getNullable("stop_sequence")) - - /** - * Billing and rate-limit usage. - * - * Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying - * cost to our systems. - * - * Under the hood, the API transforms requests into a format suitable for the model. The model's - * output then goes through a parsing stage before becoming an API response. As a result, the - * token counts in `usage` will not match one-to-one with the exact visible content of an API - * request or response. - * - * For example, `output_tokens` will be non-zero, even for an empty string response from Claude. - */ - fun usage(): PromptCachingBetaUsage = usage.getRequired("usage") - - /** - * Unique object identifier. - * - * The format and length of IDs may change over time. - */ - @JsonProperty("id") @ExcludeMissing fun _id() = id - - /** - * Object type. - * - * For Messages, this is always `"message"`. - */ - @JsonProperty("type") @ExcludeMissing fun _type() = type - - /** - * Conversational role of the generated message. - * - * This will always be `"assistant"`. - */ - @JsonProperty("role") @ExcludeMissing fun _role() = role - - /** - * Content generated by the model. - * - * This is an array of content blocks, each of which has a `type` that determines its shape. - * - * Example: - * ```json - * [{ "type": "text", "text": "Hi, I'm Claude." }] - * ``` - * - * If the request input `messages` ended with an `assistant` turn, then the response `content` - * will continue directly from that last turn. You can use this to constrain the model's output. - * - * For example, if the input `messages` were: - * ```json - * [ - * { - * "role": "user", - * "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - * }, - * { "role": "assistant", "content": "The best answer is (" } - * ] - * ``` - * - * Then the response `content` might be: - * ```json - * [{ "type": "text", "text": "B)" }] - * ``` - */ - @JsonProperty("content") @ExcludeMissing fun _content() = content - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and - * options. - */ - @JsonProperty("model") @ExcludeMissing fun _model() = model - - /** - * The reason that we stopped. - * - * This may be one the following values: - * - `"end_turn"`: the model reached a natural stopping point - * - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - * - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - * - `"tool_use"`: the model invoked one or more tools - * - * In non-streaming mode this value is always non-null. In streaming mode, it is null in the - * `message_start` event and non-null otherwise. - */ - @JsonProperty("stop_reason") @ExcludeMissing fun _stopReason() = stopReason - - /** - * Which custom stop sequence was generated, if any. - * - * This value will be a non-null string if one of your custom stop sequences was generated. - */ - @JsonProperty("stop_sequence") @ExcludeMissing fun _stopSequence() = stopSequence - - /** - * Billing and rate-limit usage. - * - * Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying - * cost to our systems. - * - * Under the hood, the API transforms requests into a format suitable for the model. The model's - * output then goes through a parsing stage before becoming an API response. As a result, the - * token counts in `usage` will not match one-to-one with the exact visible content of an API - * request or response. - * - * For example, `output_tokens` will be non-zero, even for an empty string response from Claude. - */ - @JsonProperty("usage") @ExcludeMissing fun _usage() = usage - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): PromptCachingBetaMessage = apply { - if (!validated) { - id() - type() - role() - content() - model() - stopReason() - stopSequence() - usage().validate() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var id: JsonField = JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var role: JsonField = JsonMissing.of() - private var content: JsonField> = JsonMissing.of() - private var model: JsonField = JsonMissing.of() - private var stopReason: JsonField = JsonMissing.of() - private var stopSequence: JsonField = JsonMissing.of() - private var usage: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(promptCachingBetaMessage: PromptCachingBetaMessage) = apply { - this.id = promptCachingBetaMessage.id - this.type = promptCachingBetaMessage.type - this.role = promptCachingBetaMessage.role - this.content = promptCachingBetaMessage.content - this.model = promptCachingBetaMessage.model - this.stopReason = promptCachingBetaMessage.stopReason - this.stopSequence = promptCachingBetaMessage.stopSequence - this.usage = promptCachingBetaMessage.usage - additionalProperties(promptCachingBetaMessage.additionalProperties) - } - - /** - * Unique object identifier. - * - * The format and length of IDs may change over time. - */ - fun id(id: String) = id(JsonField.of(id)) - - /** - * Unique object identifier. - * - * The format and length of IDs may change over time. - */ - @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } - - /** - * Object type. - * - * For Messages, this is always `"message"`. - */ - fun type(type: Type) = type(JsonField.of(type)) - - /** - * Object type. - * - * For Messages, this is always `"message"`. - */ - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - /** - * Conversational role of the generated message. - * - * This will always be `"assistant"`. - */ - fun role(role: Role) = role(JsonField.of(role)) - - /** - * Conversational role of the generated message. - * - * This will always be `"assistant"`. - */ - @JsonProperty("role") - @ExcludeMissing - fun role(role: JsonField) = apply { this.role = role } - - /** - * Content generated by the model. - * - * This is an array of content blocks, each of which has a `type` that determines its shape. - * - * Example: - * ```json - * [{ "type": "text", "text": "Hi, I'm Claude." }] - * ``` - * - * If the request input `messages` ended with an `assistant` turn, then the response - * `content` will continue directly from that last turn. You can use this to constrain the - * model's output. - * - * For example, if the input `messages` were: - * ```json - * [ - * { - * "role": "user", - * "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - * }, - * { "role": "assistant", "content": "The best answer is (" } - * ] - * ``` - * - * Then the response `content` might be: - * ```json - * [{ "type": "text", "text": "B)" }] - * ``` - */ - fun content(content: List) = content(JsonField.of(content)) - - /** - * Content generated by the model. - * - * This is an array of content blocks, each of which has a `type` that determines its shape. - * - * Example: - * ```json - * [{ "type": "text", "text": "Hi, I'm Claude." }] - * ``` - * - * If the request input `messages` ended with an `assistant` turn, then the response - * `content` will continue directly from that last turn. You can use this to constrain the - * model's output. - * - * For example, if the input `messages` were: - * ```json - * [ - * { - * "role": "user", - * "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" - * }, - * { "role": "assistant", "content": "The best answer is (" } - * ] - * ``` - * - * Then the response `content` might be: - * ```json - * [{ "type": "text", "text": "B)" }] - * ``` - */ - @JsonProperty("content") - @ExcludeMissing - fun content(content: JsonField>) = apply { this.content = content } - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and - * options. - */ - fun model(model: Model) = model(JsonField.of(model)) - - /** - * The model that will complete your prompt.\n\nSee - * [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and - * options. - */ - @JsonProperty("model") - @ExcludeMissing - fun model(model: JsonField) = apply { this.model = model } - - /** - * The reason that we stopped. - * - * This may be one the following values: - * - `"end_turn"`: the model reached a natural stopping point - * - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - * - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - * - `"tool_use"`: the model invoked one or more tools - * - * In non-streaming mode this value is always non-null. In streaming mode, it is null in the - * `message_start` event and non-null otherwise. - */ - fun stopReason(stopReason: StopReason) = stopReason(JsonField.of(stopReason)) - - /** - * The reason that we stopped. - * - * This may be one the following values: - * - `"end_turn"`: the model reached a natural stopping point - * - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - * - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - * - `"tool_use"`: the model invoked one or more tools - * - * In non-streaming mode this value is always non-null. In streaming mode, it is null in the - * `message_start` event and non-null otherwise. - */ - @JsonProperty("stop_reason") - @ExcludeMissing - fun stopReason(stopReason: JsonField) = apply { this.stopReason = stopReason } - - /** - * Which custom stop sequence was generated, if any. - * - * This value will be a non-null string if one of your custom stop sequences was generated. - */ - fun stopSequence(stopSequence: String) = stopSequence(JsonField.of(stopSequence)) - - /** - * Which custom stop sequence was generated, if any. - * - * This value will be a non-null string if one of your custom stop sequences was generated. - */ - @JsonProperty("stop_sequence") - @ExcludeMissing - fun stopSequence(stopSequence: JsonField) = apply { - this.stopSequence = stopSequence - } - - /** - * Billing and rate-limit usage. - * - * Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying - * cost to our systems. - * - * Under the hood, the API transforms requests into a format suitable for the model. The - * model's output then goes through a parsing stage before becoming an API response. As a - * result, the token counts in `usage` will not match one-to-one with the exact visible - * content of an API request or response. - * - * For example, `output_tokens` will be non-zero, even for an empty string response from - * Claude. - */ - fun usage(usage: PromptCachingBetaUsage) = usage(JsonField.of(usage)) - - /** - * Billing and rate-limit usage. - * - * Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying - * cost to our systems. - * - * Under the hood, the API transforms requests into a format suitable for the model. The - * model's output then goes through a parsing stage before becoming an API response. As a - * result, the token counts in `usage` will not match one-to-one with the exact visible - * content of an API request or response. - * - * For example, `output_tokens` will be non-zero, even for an empty string response from - * Claude. - */ - @JsonProperty("usage") - @ExcludeMissing - fun usage(usage: JsonField) = apply { this.usage = usage } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): PromptCachingBetaMessage = - PromptCachingBetaMessage( - id, - type, - role, - content.map { it.toImmutable() }, - model, - stopReason, - stopSequence, - usage, - additionalProperties.toImmutable(), - ) - } - - class Role - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val ASSISTANT = of("assistant") - - @JvmStatic fun of(value: String) = Role(JsonField.of(value)) - } - - enum class Known { - ASSISTANT, - } - - enum class Value { - ASSISTANT, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - ASSISTANT -> Value.ASSISTANT - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - ASSISTANT -> Known.ASSISTANT - else -> throw AnthropicInvalidDataException("Unknown Role: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Role && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class StopReason - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val END_TURN = of("end_turn") - - @JvmField val MAX_TOKENS = of("max_tokens") - - @JvmField val STOP_SEQUENCE = of("stop_sequence") - - @JvmField val TOOL_USE = of("tool_use") - - @JvmStatic fun of(value: String) = StopReason(JsonField.of(value)) - } - - enum class Known { - END_TURN, - MAX_TOKENS, - STOP_SEQUENCE, - TOOL_USE, - } - - enum class Value { - END_TURN, - MAX_TOKENS, - STOP_SEQUENCE, - TOOL_USE, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - END_TURN -> Value.END_TURN - MAX_TOKENS -> Value.MAX_TOKENS - STOP_SEQUENCE -> Value.STOP_SEQUENCE - TOOL_USE -> Value.TOOL_USE - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - END_TURN -> Known.END_TURN - MAX_TOKENS -> Known.MAX_TOKENS - STOP_SEQUENCE -> Known.STOP_SEQUENCE - TOOL_USE -> Known.TOOL_USE - else -> throw AnthropicInvalidDataException("Unknown StopReason: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is StopReason && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val MESSAGE = of("message") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - MESSAGE, - } - - enum class Value { - MESSAGE, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - MESSAGE -> Value.MESSAGE - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - MESSAGE -> Known.MESSAGE - else -> throw AnthropicInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptCachingBetaMessage && id == other.id && type == other.type && role == other.role && content == other.content && model == other.model && stopReason == other.stopReason && stopSequence == other.stopSequence && usage == other.usage && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(id, type, role, content, model, stopReason, stopSequence, usage, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PromptCachingBetaMessage{id=$id, type=$type, role=$role, content=$content, model=$model, stopReason=$stopReason, stopSequence=$stopSequence, usage=$usage, additionalProperties=$additionalProperties}" -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaMessageParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaMessageParam.kt deleted file mode 100644 index 119887e..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaMessageParam.kt +++ /dev/null @@ -1,560 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.BaseDeserializer -import com.anthropic.core.BaseSerializer -import com.anthropic.core.Enum -import com.anthropic.core.ExcludeMissing -import com.anthropic.core.JsonField -import com.anthropic.core.JsonMissing -import com.anthropic.core.JsonValue -import com.anthropic.core.NoAutoDetect -import com.anthropic.core.getOrThrow -import com.anthropic.core.toImmutable -import com.anthropic.errors.AnthropicInvalidDataException -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -@JsonDeserialize(builder = PromptCachingBetaMessageParam.Builder::class) -@NoAutoDetect -class PromptCachingBetaMessageParam -private constructor( - private val role: JsonField, - private val content: JsonField, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - fun role(): Role = role.getRequired("role") - - fun content(): Content = content.getRequired("content") - - @JsonProperty("role") @ExcludeMissing fun _role() = role - - @JsonProperty("content") @ExcludeMissing fun _content() = content - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): PromptCachingBetaMessageParam = apply { - if (!validated) { - role() - content() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var role: JsonField = JsonMissing.of() - private var content: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(promptCachingBetaMessageParam: PromptCachingBetaMessageParam) = apply { - this.role = promptCachingBetaMessageParam.role - this.content = promptCachingBetaMessageParam.content - additionalProperties(promptCachingBetaMessageParam.additionalProperties) - } - - fun role(role: Role) = role(JsonField.of(role)) - - @JsonProperty("role") - @ExcludeMissing - fun role(role: JsonField) = apply { this.role = role } - - fun content(content: Content) = content(JsonField.of(content)) - - @JsonProperty("content") - @ExcludeMissing - fun content(content: JsonField) = apply { this.content = content } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): PromptCachingBetaMessageParam = - PromptCachingBetaMessageParam( - role, - content, - additionalProperties.toImmutable(), - ) - } - - @JsonDeserialize(using = Content.Deserializer::class) - @JsonSerialize(using = Content.Serializer::class) - class Content - private constructor( - private val string: String? = null, - private val blocks: List? = null, - private val _json: JsonValue? = null, - ) { - - private var validated: Boolean = false - - fun string(): Optional = Optional.ofNullable(string) - - fun blocks(): Optional> = Optional.ofNullable(blocks) - - fun isString(): Boolean = string != null - - fun isBlocks(): Boolean = blocks != null - - fun asString(): String = string.getOrThrow("string") - - fun asBlocks(): List = blocks.getOrThrow("blocks") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - string != null -> visitor.visitString(string) - blocks != null -> visitor.visitBlocks(blocks) - else -> visitor.unknown(_json) - } - } - - fun validate(): Content = apply { - if (!validated) { - if (string == null && blocks == null) { - throw AnthropicInvalidDataException("Unknown Content: $_json") - } - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Content && string == other.string && blocks == other.blocks /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, blocks) /* spotless:on */ - - override fun toString(): String = - when { - string != null -> "Content{string=$string}" - blocks != null -> "Content{blocks=$blocks}" - _json != null -> "Content{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Content") - } - - companion object { - - @JvmStatic fun ofString(string: String) = Content(string = string) - - @JvmStatic fun ofBlocks(blocks: List) = Content(blocks = blocks) - } - - interface Visitor { - - fun visitString(string: String): T - - fun visitBlocks(blocks: List): T - - fun unknown(json: JsonValue?): T { - throw AnthropicInvalidDataException("Unknown Content: $json") - } - } - - class Deserializer : BaseDeserializer(Content::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Content { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Content(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Content(blocks = it, _json = json) - } - - return Content(_json = json) - } - } - - class Serializer : BaseSerializer(Content::class) { - - override fun serialize( - value: Content, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.blocks != null -> generator.writeObject(value.blocks) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Content") - } - } - } - - @JsonDeserialize(using = Block.Deserializer::class) - @JsonSerialize(using = Block.Serializer::class) - class Block - private constructor( - private val promptCachingBetaTextBlockParam: PromptCachingBetaTextBlockParam? = null, - private val promptCachingBetaImageBlockParam: PromptCachingBetaImageBlockParam? = null, - private val promptCachingBetaToolUseBlockParam: PromptCachingBetaToolUseBlockParam? = - null, - private val promptCachingBetaToolResultBlockParam: - PromptCachingBetaToolResultBlockParam? = - null, - private val _json: JsonValue? = null, - ) { - - private var validated: Boolean = false - - fun promptCachingBetaTextBlockParam(): Optional = - Optional.ofNullable(promptCachingBetaTextBlockParam) - - fun promptCachingBetaImageBlockParam(): Optional = - Optional.ofNullable(promptCachingBetaImageBlockParam) - - fun promptCachingBetaToolUseBlockParam(): Optional = - Optional.ofNullable(promptCachingBetaToolUseBlockParam) - - fun promptCachingBetaToolResultBlockParam(): - Optional = - Optional.ofNullable(promptCachingBetaToolResultBlockParam) - - fun isPromptCachingBetaTextBlockParam(): Boolean = - promptCachingBetaTextBlockParam != null - - fun isPromptCachingBetaImageBlockParam(): Boolean = - promptCachingBetaImageBlockParam != null - - fun isPromptCachingBetaToolUseBlockParam(): Boolean = - promptCachingBetaToolUseBlockParam != null - - fun isPromptCachingBetaToolResultBlockParam(): Boolean = - promptCachingBetaToolResultBlockParam != null - - fun asPromptCachingBetaTextBlockParam(): PromptCachingBetaTextBlockParam = - promptCachingBetaTextBlockParam.getOrThrow("promptCachingBetaTextBlockParam") - - fun asPromptCachingBetaImageBlockParam(): PromptCachingBetaImageBlockParam = - promptCachingBetaImageBlockParam.getOrThrow("promptCachingBetaImageBlockParam") - - fun asPromptCachingBetaToolUseBlockParam(): PromptCachingBetaToolUseBlockParam = - promptCachingBetaToolUseBlockParam.getOrThrow("promptCachingBetaToolUseBlockParam") - - fun asPromptCachingBetaToolResultBlockParam(): PromptCachingBetaToolResultBlockParam = - promptCachingBetaToolResultBlockParam.getOrThrow( - "promptCachingBetaToolResultBlockParam" - ) - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - promptCachingBetaTextBlockParam != null -> - visitor.visitPromptCachingBetaTextBlockParam( - promptCachingBetaTextBlockParam - ) - promptCachingBetaImageBlockParam != null -> - visitor.visitPromptCachingBetaImageBlockParam( - promptCachingBetaImageBlockParam - ) - promptCachingBetaToolUseBlockParam != null -> - visitor.visitPromptCachingBetaToolUseBlockParam( - promptCachingBetaToolUseBlockParam - ) - promptCachingBetaToolResultBlockParam != null -> - visitor.visitPromptCachingBetaToolResultBlockParam( - promptCachingBetaToolResultBlockParam - ) - else -> visitor.unknown(_json) - } - } - - fun validate(): Block = apply { - if (!validated) { - if ( - promptCachingBetaTextBlockParam == null && - promptCachingBetaImageBlockParam == null && - promptCachingBetaToolUseBlockParam == null && - promptCachingBetaToolResultBlockParam == null - ) { - throw AnthropicInvalidDataException("Unknown Block: $_json") - } - promptCachingBetaTextBlockParam?.validate() - promptCachingBetaImageBlockParam?.validate() - promptCachingBetaToolUseBlockParam?.validate() - promptCachingBetaToolResultBlockParam?.validate() - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Block && promptCachingBetaTextBlockParam == other.promptCachingBetaTextBlockParam && promptCachingBetaImageBlockParam == other.promptCachingBetaImageBlockParam && promptCachingBetaToolUseBlockParam == other.promptCachingBetaToolUseBlockParam && promptCachingBetaToolResultBlockParam == other.promptCachingBetaToolResultBlockParam /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(promptCachingBetaTextBlockParam, promptCachingBetaImageBlockParam, promptCachingBetaToolUseBlockParam, promptCachingBetaToolResultBlockParam) /* spotless:on */ - - override fun toString(): String = - when { - promptCachingBetaTextBlockParam != null -> - "Block{promptCachingBetaTextBlockParam=$promptCachingBetaTextBlockParam}" - promptCachingBetaImageBlockParam != null -> - "Block{promptCachingBetaImageBlockParam=$promptCachingBetaImageBlockParam}" - promptCachingBetaToolUseBlockParam != null -> - "Block{promptCachingBetaToolUseBlockParam=$promptCachingBetaToolUseBlockParam}" - promptCachingBetaToolResultBlockParam != null -> - "Block{promptCachingBetaToolResultBlockParam=$promptCachingBetaToolResultBlockParam}" - _json != null -> "Block{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Block") - } - - companion object { - - @JvmStatic - fun ofPromptCachingBetaTextBlockParam( - promptCachingBetaTextBlockParam: PromptCachingBetaTextBlockParam - ) = Block(promptCachingBetaTextBlockParam = promptCachingBetaTextBlockParam) - - @JvmStatic - fun ofPromptCachingBetaImageBlockParam( - promptCachingBetaImageBlockParam: PromptCachingBetaImageBlockParam - ) = Block(promptCachingBetaImageBlockParam = promptCachingBetaImageBlockParam) - - @JvmStatic - fun ofPromptCachingBetaToolUseBlockParam( - promptCachingBetaToolUseBlockParam: PromptCachingBetaToolUseBlockParam - ) = Block(promptCachingBetaToolUseBlockParam = promptCachingBetaToolUseBlockParam) - - @JvmStatic - fun ofPromptCachingBetaToolResultBlockParam( - promptCachingBetaToolResultBlockParam: PromptCachingBetaToolResultBlockParam - ) = - Block( - promptCachingBetaToolResultBlockParam = - promptCachingBetaToolResultBlockParam - ) - } - - interface Visitor { - - fun visitPromptCachingBetaTextBlockParam( - promptCachingBetaTextBlockParam: PromptCachingBetaTextBlockParam - ): T - - fun visitPromptCachingBetaImageBlockParam( - promptCachingBetaImageBlockParam: PromptCachingBetaImageBlockParam - ): T - - fun visitPromptCachingBetaToolUseBlockParam( - promptCachingBetaToolUseBlockParam: PromptCachingBetaToolUseBlockParam - ): T - - fun visitPromptCachingBetaToolResultBlockParam( - promptCachingBetaToolResultBlockParam: PromptCachingBetaToolResultBlockParam - ): T - - fun unknown(json: JsonValue?): T { - throw AnthropicInvalidDataException("Unknown Block: $json") - } - } - - class Deserializer : BaseDeserializer(Block::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Block { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text" -> { - tryDeserialize( - node, - jacksonTypeRef() - ) { - it.validate() - } - ?.let { - return Block(promptCachingBetaTextBlockParam = it, _json = json) - } - } - "image" -> { - tryDeserialize( - node, - jacksonTypeRef() - ) { - it.validate() - } - ?.let { - return Block( - promptCachingBetaImageBlockParam = it, - _json = json - ) - } - } - "tool_use" -> { - tryDeserialize( - node, - jacksonTypeRef() - ) { - it.validate() - } - ?.let { - return Block( - promptCachingBetaToolUseBlockParam = it, - _json = json - ) - } - } - "tool_result" -> { - tryDeserialize( - node, - jacksonTypeRef() - ) { - it.validate() - } - ?.let { - return Block( - promptCachingBetaToolResultBlockParam = it, - _json = json - ) - } - } - } - - return Block(_json = json) - } - } - - class Serializer : BaseSerializer(Block::class) { - - override fun serialize( - value: Block, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.promptCachingBetaTextBlockParam != null -> - generator.writeObject(value.promptCachingBetaTextBlockParam) - value.promptCachingBetaImageBlockParam != null -> - generator.writeObject(value.promptCachingBetaImageBlockParam) - value.promptCachingBetaToolUseBlockParam != null -> - generator.writeObject(value.promptCachingBetaToolUseBlockParam) - value.promptCachingBetaToolResultBlockParam != null -> - generator.writeObject(value.promptCachingBetaToolResultBlockParam) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Block") - } - } - } - } - } - - class Role - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val USER = of("user") - - @JvmField val ASSISTANT = of("assistant") - - @JvmStatic fun of(value: String) = Role(JsonField.of(value)) - } - - enum class Known { - USER, - ASSISTANT, - } - - enum class Value { - USER, - ASSISTANT, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - USER -> Value.USER - ASSISTANT -> Value.ASSISTANT - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - USER -> Known.USER - ASSISTANT -> Known.ASSISTANT - else -> throw AnthropicInvalidDataException("Unknown Role: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Role && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptCachingBetaMessageParam && role == other.role && content == other.content && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(role, content, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PromptCachingBetaMessageParam{role=$role, content=$content, additionalProperties=$additionalProperties}" -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaTool.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaTool.kt deleted file mode 100644 index 01252bb..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaTool.kt +++ /dev/null @@ -1,386 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.Enum -import com.anthropic.core.ExcludeMissing -import com.anthropic.core.JsonField -import com.anthropic.core.JsonMissing -import com.anthropic.core.JsonValue -import com.anthropic.core.NoAutoDetect -import com.anthropic.core.toImmutable -import com.anthropic.errors.AnthropicInvalidDataException -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = PromptCachingBetaTool.Builder::class) -@NoAutoDetect -class PromptCachingBetaTool -private constructor( - private val description: JsonField, - private val name: JsonField, - private val inputSchema: JsonField, - private val cacheControl: JsonField, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - /** - * Description of what this tool does. - * - * Tool descriptions should be as detailed as possible. The more information that the model has - * about what the tool is and how to use it, the better it will perform. You can use natural - * language descriptions to reinforce important aspects of the tool input JSON schema. - */ - fun description(): Optional = - Optional.ofNullable(description.getNullable("description")) - - /** - * Name of the tool. - * - * This is how the tool will be called by the model and in tool_use blocks. - */ - fun name(): String = name.getRequired("name") - - /** - * [JSON schema](https://json-schema.org/) for this tool's input. - * - * This defines the shape of the `input` that your tool accepts and that the model will produce. - */ - fun inputSchema(): InputSchema = inputSchema.getRequired("input_schema") - - fun cacheControl(): Optional = - Optional.ofNullable(cacheControl.getNullable("cache_control")) - - /** - * Description of what this tool does. - * - * Tool descriptions should be as detailed as possible. The more information that the model has - * about what the tool is and how to use it, the better it will perform. You can use natural - * language descriptions to reinforce important aspects of the tool input JSON schema. - */ - @JsonProperty("description") @ExcludeMissing fun _description() = description - - /** - * Name of the tool. - * - * This is how the tool will be called by the model and in tool_use blocks. - */ - @JsonProperty("name") @ExcludeMissing fun _name() = name - - /** - * [JSON schema](https://json-schema.org/) for this tool's input. - * - * This defines the shape of the `input` that your tool accepts and that the model will produce. - */ - @JsonProperty("input_schema") @ExcludeMissing fun _inputSchema() = inputSchema - - @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): PromptCachingBetaTool = apply { - if (!validated) { - description() - name() - inputSchema().validate() - cacheControl().map { it.validate() } - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var description: JsonField = JsonMissing.of() - private var name: JsonField = JsonMissing.of() - private var inputSchema: JsonField = JsonMissing.of() - private var cacheControl: JsonField = - JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(promptCachingBetaTool: PromptCachingBetaTool) = apply { - this.description = promptCachingBetaTool.description - this.name = promptCachingBetaTool.name - this.inputSchema = promptCachingBetaTool.inputSchema - this.cacheControl = promptCachingBetaTool.cacheControl - additionalProperties(promptCachingBetaTool.additionalProperties) - } - - /** - * Description of what this tool does. - * - * Tool descriptions should be as detailed as possible. The more information that the model - * has about what the tool is and how to use it, the better it will perform. You can use - * natural language descriptions to reinforce important aspects of the tool input JSON - * schema. - */ - fun description(description: String) = description(JsonField.of(description)) - - /** - * Description of what this tool does. - * - * Tool descriptions should be as detailed as possible. The more information that the model - * has about what the tool is and how to use it, the better it will perform. You can use - * natural language descriptions to reinforce important aspects of the tool input JSON - * schema. - */ - @JsonProperty("description") - @ExcludeMissing - fun description(description: JsonField) = apply { this.description = description } - - /** - * Name of the tool. - * - * This is how the tool will be called by the model and in tool_use blocks. - */ - fun name(name: String) = name(JsonField.of(name)) - - /** - * Name of the tool. - * - * This is how the tool will be called by the model and in tool_use blocks. - */ - @JsonProperty("name") - @ExcludeMissing - fun name(name: JsonField) = apply { this.name = name } - - /** - * [JSON schema](https://json-schema.org/) for this tool's input. - * - * This defines the shape of the `input` that your tool accepts and that the model will - * produce. - */ - fun inputSchema(inputSchema: InputSchema) = inputSchema(JsonField.of(inputSchema)) - - /** - * [JSON schema](https://json-schema.org/) for this tool's input. - * - * This defines the shape of the `input` that your tool accepts and that the model will - * produce. - */ - @JsonProperty("input_schema") - @ExcludeMissing - fun inputSchema(inputSchema: JsonField) = apply { - this.inputSchema = inputSchema - } - - fun cacheControl(cacheControl: PromptCachingBetaCacheControlEphemeral) = - cacheControl(JsonField.of(cacheControl)) - - @JsonProperty("cache_control") - @ExcludeMissing - fun cacheControl(cacheControl: JsonField) = apply { - this.cacheControl = cacheControl - } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): PromptCachingBetaTool = - PromptCachingBetaTool( - description, - name, - inputSchema, - cacheControl, - additionalProperties.toImmutable(), - ) - } - - /** - * [JSON schema](https://json-schema.org/) for this tool's input. - * - * This defines the shape of the `input` that your tool accepts and that the model will produce. - */ - @JsonDeserialize(builder = InputSchema.Builder::class) - @NoAutoDetect - class InputSchema - private constructor( - private val type: JsonField, - private val properties: JsonValue, - private val additionalProperties: Map, - ) { - - private var validated: Boolean = false - - fun type(): Type = type.getRequired("type") - - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonProperty("properties") @ExcludeMissing fun _properties() = properties - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): InputSchema = apply { - if (!validated) { - type() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var type: JsonField = JsonMissing.of() - private var properties: JsonValue = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(inputSchema: InputSchema) = apply { - this.type = inputSchema.type - this.properties = inputSchema.properties - additionalProperties(inputSchema.additionalProperties) - } - - fun type(type: Type) = type(JsonField.of(type)) - - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - @JsonProperty("properties") - @ExcludeMissing - fun properties(properties: JsonValue) = apply { this.properties = properties } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): InputSchema = - InputSchema( - type, - properties, - additionalProperties.toImmutable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val OBJECT = of("object") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - OBJECT, - } - - enum class Value { - OBJECT, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - OBJECT -> Value.OBJECT - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - OBJECT -> Known.OBJECT - else -> throw AnthropicInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is InputSchema && type == other.type && properties == other.properties && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, properties, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "InputSchema{type=$type, properties=$properties, additionalProperties=$additionalProperties}" - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptCachingBetaTool && description == other.description && name == other.name && inputSchema == other.inputSchema && cacheControl == other.cacheControl && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, name, inputSchema, cacheControl, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PromptCachingBetaTool{description=$description, name=$name, inputSchema=$inputSchema, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaToolResultBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaToolResultBlockParam.kt deleted file mode 100644 index 6231ff0..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaToolResultBlockParam.kt +++ /dev/null @@ -1,510 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.BaseDeserializer -import com.anthropic.core.BaseSerializer -import com.anthropic.core.Enum -import com.anthropic.core.ExcludeMissing -import com.anthropic.core.JsonField -import com.anthropic.core.JsonMissing -import com.anthropic.core.JsonValue -import com.anthropic.core.NoAutoDetect -import com.anthropic.core.getOrThrow -import com.anthropic.core.toImmutable -import com.anthropic.errors.AnthropicInvalidDataException -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonCreator -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -@JsonDeserialize(builder = PromptCachingBetaToolResultBlockParam.Builder::class) -@NoAutoDetect -class PromptCachingBetaToolResultBlockParam -private constructor( - private val cacheControl: JsonField, - private val type: JsonField, - private val toolUseId: JsonField, - private val isError: JsonField, - private val content: JsonField, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - fun cacheControl(): Optional = - Optional.ofNullable(cacheControl.getNullable("cache_control")) - - fun type(): Type = type.getRequired("type") - - fun toolUseId(): String = toolUseId.getRequired("tool_use_id") - - fun isError(): Optional = Optional.ofNullable(isError.getNullable("is_error")) - - fun content(): Optional = Optional.ofNullable(content.getNullable("content")) - - @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl - - @JsonProperty("type") @ExcludeMissing fun _type() = type - - @JsonProperty("tool_use_id") @ExcludeMissing fun _toolUseId() = toolUseId - - @JsonProperty("is_error") @ExcludeMissing fun _isError() = isError - - @JsonProperty("content") @ExcludeMissing fun _content() = content - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): PromptCachingBetaToolResultBlockParam = apply { - if (!validated) { - cacheControl().map { it.validate() } - type() - toolUseId() - isError() - content() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var cacheControl: JsonField = - JsonMissing.of() - private var type: JsonField = JsonMissing.of() - private var toolUseId: JsonField = JsonMissing.of() - private var isError: JsonField = JsonMissing.of() - private var content: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from( - promptCachingBetaToolResultBlockParam: PromptCachingBetaToolResultBlockParam - ) = apply { - this.cacheControl = promptCachingBetaToolResultBlockParam.cacheControl - this.type = promptCachingBetaToolResultBlockParam.type - this.toolUseId = promptCachingBetaToolResultBlockParam.toolUseId - this.isError = promptCachingBetaToolResultBlockParam.isError - this.content = promptCachingBetaToolResultBlockParam.content - additionalProperties(promptCachingBetaToolResultBlockParam.additionalProperties) - } - - fun cacheControl(cacheControl: PromptCachingBetaCacheControlEphemeral) = - cacheControl(JsonField.of(cacheControl)) - - @JsonProperty("cache_control") - @ExcludeMissing - fun cacheControl(cacheControl: JsonField) = apply { - this.cacheControl = cacheControl - } - - fun type(type: Type) = type(JsonField.of(type)) - - @JsonProperty("type") - @ExcludeMissing - fun type(type: JsonField) = apply { this.type = type } - - fun toolUseId(toolUseId: String) = toolUseId(JsonField.of(toolUseId)) - - @JsonProperty("tool_use_id") - @ExcludeMissing - fun toolUseId(toolUseId: JsonField) = apply { this.toolUseId = toolUseId } - - fun isError(isError: Boolean) = isError(JsonField.of(isError)) - - @JsonProperty("is_error") - @ExcludeMissing - fun isError(isError: JsonField) = apply { this.isError = isError } - - fun content(content: Content) = content(JsonField.of(content)) - - @JsonProperty("content") - @ExcludeMissing - fun content(content: JsonField) = apply { this.content = content } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): PromptCachingBetaToolResultBlockParam = - PromptCachingBetaToolResultBlockParam( - cacheControl, - type, - toolUseId, - isError, - content, - additionalProperties.toImmutable(), - ) - } - - class Type - @JsonCreator - private constructor( - private val value: JsonField, - ) : Enum { - - @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value - - companion object { - - @JvmField val TOOL_RESULT = of("tool_result") - - @JvmStatic fun of(value: String) = Type(JsonField.of(value)) - } - - enum class Known { - TOOL_RESULT, - } - - enum class Value { - TOOL_RESULT, - _UNKNOWN, - } - - fun value(): Value = - when (this) { - TOOL_RESULT -> Value.TOOL_RESULT - else -> Value._UNKNOWN - } - - fun known(): Known = - when (this) { - TOOL_RESULT -> Known.TOOL_RESULT - else -> throw AnthropicInvalidDataException("Unknown Type: $value") - } - - fun asString(): String = _value().asStringOrThrow() - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Type && value == other.value /* spotless:on */ - } - - override fun hashCode() = value.hashCode() - - override fun toString() = value.toString() - } - - @JsonDeserialize(using = Content.Deserializer::class) - @JsonSerialize(using = Content.Serializer::class) - class Content - private constructor( - private val string: String? = null, - private val blocks: List? = null, - private val _json: JsonValue? = null, - ) { - - private var validated: Boolean = false - - fun string(): Optional = Optional.ofNullable(string) - - fun blocks(): Optional> = Optional.ofNullable(blocks) - - fun isString(): Boolean = string != null - - fun isBlocks(): Boolean = blocks != null - - fun asString(): String = string.getOrThrow("string") - - fun asBlocks(): List = blocks.getOrThrow("blocks") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - string != null -> visitor.visitString(string) - blocks != null -> visitor.visitBlocks(blocks) - else -> visitor.unknown(_json) - } - } - - fun validate(): Content = apply { - if (!validated) { - if (string == null && blocks == null) { - throw AnthropicInvalidDataException("Unknown Content: $_json") - } - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Content && string == other.string && blocks == other.blocks /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(string, blocks) /* spotless:on */ - - override fun toString(): String = - when { - string != null -> "Content{string=$string}" - blocks != null -> "Content{blocks=$blocks}" - _json != null -> "Content{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Content") - } - - companion object { - - @JvmStatic fun ofString(string: String) = Content(string = string) - - @JvmStatic fun ofBlocks(blocks: List) = Content(blocks = blocks) - } - - interface Visitor { - - fun visitString(string: String): T - - fun visitBlocks(blocks: List): T - - fun unknown(json: JsonValue?): T { - throw AnthropicInvalidDataException("Unknown Content: $json") - } - } - - class Deserializer : BaseDeserializer(Content::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Content { - val json = JsonValue.fromJsonNode(node) - - tryDeserialize(node, jacksonTypeRef())?.let { - return Content(string = it, _json = json) - } - tryDeserialize(node, jacksonTypeRef>())?.let { - return Content(blocks = it, _json = json) - } - - return Content(_json = json) - } - } - - class Serializer : BaseSerializer(Content::class) { - - override fun serialize( - value: Content, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.string != null -> generator.writeObject(value.string) - value.blocks != null -> generator.writeObject(value.blocks) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Content") - } - } - } - - @JsonDeserialize(using = Block.Deserializer::class) - @JsonSerialize(using = Block.Serializer::class) - class Block - private constructor( - private val promptCachingBetaTextBlockParam: PromptCachingBetaTextBlockParam? = null, - private val promptCachingBetaImageBlockParam: PromptCachingBetaImageBlockParam? = null, - private val _json: JsonValue? = null, - ) { - - private var validated: Boolean = false - - fun promptCachingBetaTextBlockParam(): Optional = - Optional.ofNullable(promptCachingBetaTextBlockParam) - - fun promptCachingBetaImageBlockParam(): Optional = - Optional.ofNullable(promptCachingBetaImageBlockParam) - - fun isPromptCachingBetaTextBlockParam(): Boolean = - promptCachingBetaTextBlockParam != null - - fun isPromptCachingBetaImageBlockParam(): Boolean = - promptCachingBetaImageBlockParam != null - - fun asPromptCachingBetaTextBlockParam(): PromptCachingBetaTextBlockParam = - promptCachingBetaTextBlockParam.getOrThrow("promptCachingBetaTextBlockParam") - - fun asPromptCachingBetaImageBlockParam(): PromptCachingBetaImageBlockParam = - promptCachingBetaImageBlockParam.getOrThrow("promptCachingBetaImageBlockParam") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - promptCachingBetaTextBlockParam != null -> - visitor.visitPromptCachingBetaTextBlockParam( - promptCachingBetaTextBlockParam - ) - promptCachingBetaImageBlockParam != null -> - visitor.visitPromptCachingBetaImageBlockParam( - promptCachingBetaImageBlockParam - ) - else -> visitor.unknown(_json) - } - } - - fun validate(): Block = apply { - if (!validated) { - if ( - promptCachingBetaTextBlockParam == null && - promptCachingBetaImageBlockParam == null - ) { - throw AnthropicInvalidDataException("Unknown Block: $_json") - } - promptCachingBetaTextBlockParam?.validate() - promptCachingBetaImageBlockParam?.validate() - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is Block && promptCachingBetaTextBlockParam == other.promptCachingBetaTextBlockParam && promptCachingBetaImageBlockParam == other.promptCachingBetaImageBlockParam /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(promptCachingBetaTextBlockParam, promptCachingBetaImageBlockParam) /* spotless:on */ - - override fun toString(): String = - when { - promptCachingBetaTextBlockParam != null -> - "Block{promptCachingBetaTextBlockParam=$promptCachingBetaTextBlockParam}" - promptCachingBetaImageBlockParam != null -> - "Block{promptCachingBetaImageBlockParam=$promptCachingBetaImageBlockParam}" - _json != null -> "Block{_unknown=$_json}" - else -> throw IllegalStateException("Invalid Block") - } - - companion object { - - @JvmStatic - fun ofPromptCachingBetaTextBlockParam( - promptCachingBetaTextBlockParam: PromptCachingBetaTextBlockParam - ) = Block(promptCachingBetaTextBlockParam = promptCachingBetaTextBlockParam) - - @JvmStatic - fun ofPromptCachingBetaImageBlockParam( - promptCachingBetaImageBlockParam: PromptCachingBetaImageBlockParam - ) = Block(promptCachingBetaImageBlockParam = promptCachingBetaImageBlockParam) - } - - interface Visitor { - - fun visitPromptCachingBetaTextBlockParam( - promptCachingBetaTextBlockParam: PromptCachingBetaTextBlockParam - ): T - - fun visitPromptCachingBetaImageBlockParam( - promptCachingBetaImageBlockParam: PromptCachingBetaImageBlockParam - ): T - - fun unknown(json: JsonValue?): T { - throw AnthropicInvalidDataException("Unknown Block: $json") - } - } - - class Deserializer : BaseDeserializer(Block::class) { - - override fun ObjectCodec.deserialize(node: JsonNode): Block { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text" -> { - tryDeserialize( - node, - jacksonTypeRef() - ) { - it.validate() - } - ?.let { - return Block(promptCachingBetaTextBlockParam = it, _json = json) - } - } - "image" -> { - tryDeserialize( - node, - jacksonTypeRef() - ) { - it.validate() - } - ?.let { - return Block( - promptCachingBetaImageBlockParam = it, - _json = json - ) - } - } - } - - return Block(_json = json) - } - } - - class Serializer : BaseSerializer(Block::class) { - - override fun serialize( - value: Block, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.promptCachingBetaTextBlockParam != null -> - generator.writeObject(value.promptCachingBetaTextBlockParam) - value.promptCachingBetaImageBlockParam != null -> - generator.writeObject(value.promptCachingBetaImageBlockParam) - value._json != null -> generator.writeObject(value._json) - else -> throw IllegalStateException("Invalid Block") - } - } - } - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptCachingBetaToolResultBlockParam && cacheControl == other.cacheControl && type == other.type && toolUseId == other.toolUseId && isError == other.isError && content == other.content && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(cacheControl, type, toolUseId, isError, content, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PromptCachingBetaToolResultBlockParam{cacheControl=$cacheControl, type=$type, toolUseId=$toolUseId, isError=$isError, content=$content, additionalProperties=$additionalProperties}" -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaUsage.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaUsage.kt deleted file mode 100644 index 3d75c5a..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/PromptCachingBetaUsage.kt +++ /dev/null @@ -1,177 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.ExcludeMissing -import com.anthropic.core.JsonField -import com.anthropic.core.JsonMissing -import com.anthropic.core.JsonValue -import com.anthropic.core.NoAutoDetect -import com.anthropic.core.toImmutable -import com.fasterxml.jackson.annotation.JsonAnyGetter -import com.fasterxml.jackson.annotation.JsonAnySetter -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import java.util.Objects -import java.util.Optional - -@JsonDeserialize(builder = PromptCachingBetaUsage.Builder::class) -@NoAutoDetect -class PromptCachingBetaUsage -private constructor( - private val inputTokens: JsonField, - private val cacheCreationInputTokens: JsonField, - private val cacheReadInputTokens: JsonField, - private val outputTokens: JsonField, - private val additionalProperties: Map, -) { - - private var validated: Boolean = false - - /** The number of input tokens which were used. */ - fun inputTokens(): Long = inputTokens.getRequired("input_tokens") - - /** The number of input tokens used to create the cache entry. */ - fun cacheCreationInputTokens(): Optional = - Optional.ofNullable(cacheCreationInputTokens.getNullable("cache_creation_input_tokens")) - - /** The number of input tokens read from the cache. */ - fun cacheReadInputTokens(): Optional = - Optional.ofNullable(cacheReadInputTokens.getNullable("cache_read_input_tokens")) - - /** The number of output tokens which were used. */ - fun outputTokens(): Long = outputTokens.getRequired("output_tokens") - - /** The number of input tokens which were used. */ - @JsonProperty("input_tokens") @ExcludeMissing fun _inputTokens() = inputTokens - - /** The number of input tokens used to create the cache entry. */ - @JsonProperty("cache_creation_input_tokens") - @ExcludeMissing - fun _cacheCreationInputTokens() = cacheCreationInputTokens - - /** The number of input tokens read from the cache. */ - @JsonProperty("cache_read_input_tokens") - @ExcludeMissing - fun _cacheReadInputTokens() = cacheReadInputTokens - - /** The number of output tokens which were used. */ - @JsonProperty("output_tokens") @ExcludeMissing fun _outputTokens() = outputTokens - - @JsonAnyGetter - @ExcludeMissing - fun _additionalProperties(): Map = additionalProperties - - fun validate(): PromptCachingBetaUsage = apply { - if (!validated) { - inputTokens() - cacheCreationInputTokens() - cacheReadInputTokens() - outputTokens() - validated = true - } - } - - fun toBuilder() = Builder().from(this) - - companion object { - - @JvmStatic fun builder() = Builder() - } - - class Builder { - - private var inputTokens: JsonField = JsonMissing.of() - private var cacheCreationInputTokens: JsonField = JsonMissing.of() - private var cacheReadInputTokens: JsonField = JsonMissing.of() - private var outputTokens: JsonField = JsonMissing.of() - private var additionalProperties: MutableMap = mutableMapOf() - - @JvmSynthetic - internal fun from(promptCachingBetaUsage: PromptCachingBetaUsage) = apply { - this.inputTokens = promptCachingBetaUsage.inputTokens - this.cacheCreationInputTokens = promptCachingBetaUsage.cacheCreationInputTokens - this.cacheReadInputTokens = promptCachingBetaUsage.cacheReadInputTokens - this.outputTokens = promptCachingBetaUsage.outputTokens - additionalProperties(promptCachingBetaUsage.additionalProperties) - } - - /** The number of input tokens which were used. */ - fun inputTokens(inputTokens: Long) = inputTokens(JsonField.of(inputTokens)) - - /** The number of input tokens which were used. */ - @JsonProperty("input_tokens") - @ExcludeMissing - fun inputTokens(inputTokens: JsonField) = apply { this.inputTokens = inputTokens } - - /** The number of input tokens used to create the cache entry. */ - fun cacheCreationInputTokens(cacheCreationInputTokens: Long) = - cacheCreationInputTokens(JsonField.of(cacheCreationInputTokens)) - - /** The number of input tokens used to create the cache entry. */ - @JsonProperty("cache_creation_input_tokens") - @ExcludeMissing - fun cacheCreationInputTokens(cacheCreationInputTokens: JsonField) = apply { - this.cacheCreationInputTokens = cacheCreationInputTokens - } - - /** The number of input tokens read from the cache. */ - fun cacheReadInputTokens(cacheReadInputTokens: Long) = - cacheReadInputTokens(JsonField.of(cacheReadInputTokens)) - - /** The number of input tokens read from the cache. */ - @JsonProperty("cache_read_input_tokens") - @ExcludeMissing - fun cacheReadInputTokens(cacheReadInputTokens: JsonField) = apply { - this.cacheReadInputTokens = cacheReadInputTokens - } - - /** The number of output tokens which were used. */ - fun outputTokens(outputTokens: Long) = outputTokens(JsonField.of(outputTokens)) - - /** The number of output tokens which were used. */ - @JsonProperty("output_tokens") - @ExcludeMissing - fun outputTokens(outputTokens: JsonField) = apply { this.outputTokens = outputTokens } - - fun additionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.clear() - this.additionalProperties.putAll(additionalProperties) - } - - @JsonAnySetter - fun putAdditionalProperty(key: String, value: JsonValue) = apply { - this.additionalProperties.put(key, value) - } - - fun putAllAdditionalProperties(additionalProperties: Map) = apply { - this.additionalProperties.putAll(additionalProperties) - } - - fun build(): PromptCachingBetaUsage = - PromptCachingBetaUsage( - inputTokens, - cacheCreationInputTokens, - cacheReadInputTokens, - outputTokens, - additionalProperties.toImmutable(), - ) - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is PromptCachingBetaUsage && inputTokens == other.inputTokens && cacheCreationInputTokens == other.cacheCreationInputTokens && cacheReadInputTokens == other.cacheReadInputTokens && outputTokens == other.outputTokens && additionalProperties == other.additionalProperties /* spotless:on */ - } - - /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(inputTokens, cacheCreationInputTokens, cacheReadInputTokens, outputTokens, additionalProperties) } - /* spotless:on */ - - override fun hashCode(): Int = hashCode - - override fun toString() = - "PromptCachingBetaUsage{inputTokens=$inputTokens, cacheCreationInputTokens=$cacheCreationInputTokens, cacheReadInputTokens=$cacheReadInputTokens, outputTokens=$outputTokens, additionalProperties=$additionalProperties}" -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/RateLimitError.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/RateLimitError.kt new file mode 100644 index 0000000..9a17a0e --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/RateLimitError.kt @@ -0,0 +1,172 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.Enum +import com.anthropic.core.ExcludeMissing +import com.anthropic.core.JsonField +import com.anthropic.core.JsonMissing +import com.anthropic.core.JsonValue +import com.anthropic.core.NoAutoDetect +import com.anthropic.core.toImmutable +import com.anthropic.errors.AnthropicInvalidDataException +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import java.util.Objects + +@JsonDeserialize(builder = RateLimitError.Builder::class) +@NoAutoDetect +class RateLimitError +private constructor( + private val type: JsonField, + private val message: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + fun type(): Type = type.getRequired("type") + + fun message(): String = message.getRequired("message") + + @JsonProperty("type") @ExcludeMissing fun _type() = type + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): RateLimitError = apply { + if (!validated) { + type() + message() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(rateLimitError: RateLimitError) = apply { + this.type = rateLimitError.type + this.message = rateLimitError.message + additionalProperties(rateLimitError.additionalProperties) + } + + fun type(type: Type) = type(JsonField.of(type)) + + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): RateLimitError = + RateLimitError( + type, + message, + additionalProperties.toImmutable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + companion object { + + @JvmField val RATE_LIMIT_ERROR = of("rate_limit_error") + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + RATE_LIMIT_ERROR, + } + + enum class Value { + RATE_LIMIT_ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + RATE_LIMIT_ERROR -> Value.RATE_LIMIT_ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + RATE_LIMIT_ERROR -> Known.RATE_LIMIT_ERROR + else -> throw AnthropicInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is Type && value == other.value /* spotless:on */ + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return /* spotless:off */ other is RateLimitError && type == other.type && message == other.message && additionalProperties == other.additionalProperties /* spotless:on */ + } + + /* spotless:off */ + private val hashCode: Int by lazy { Objects.hash(type, message, additionalProperties) } + /* spotless:on */ + + override fun hashCode(): Int = hashCode + + override fun toString() = + "RateLimitError{type=$type, message=$message, additionalProperties=$additionalProperties}" +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawContentBlockDeltaEvent.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawContentBlockDeltaEvent.kt index f048ff0..9d7789c 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawContentBlockDeltaEvent.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawContentBlockDeltaEvent.kt @@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import java.util.Objects import java.util.Optional -import kotlin.jvm.optionals.getOrNull @JsonDeserialize(builder = RawContentBlockDeltaEvent.Builder::class) @NoAutoDetect @@ -214,22 +213,15 @@ private constructor( override fun ObjectCodec.deserialize(node: JsonNode): Delta { val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "text_delta" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Delta(textDelta = it, _json = json) - } + + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return Delta(textDelta = it, _json = json) } - "input_json_delta" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return Delta(inputJsonDelta = it, _json = json) - } + tryDeserialize(node, jacksonTypeRef()) { it.validate() } + ?.let { + return Delta(inputJsonDelta = it, _json = json) } - } return Delta(_json = json) } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStreamEvent.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStreamEvent.kt deleted file mode 100644 index f4cb06c..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStreamEvent.kt +++ /dev/null @@ -1,327 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.BaseDeserializer -import com.anthropic.core.BaseSerializer -import com.anthropic.core.JsonValue -import com.anthropic.core.getOrThrow -import com.anthropic.errors.AnthropicInvalidDataException -import com.fasterxml.jackson.core.JsonGenerator -import com.fasterxml.jackson.core.ObjectCodec -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.SerializerProvider -import com.fasterxml.jackson.databind.annotation.JsonDeserialize -import com.fasterxml.jackson.databind.annotation.JsonSerialize -import com.fasterxml.jackson.module.kotlin.jacksonTypeRef -import java.util.Objects -import java.util.Optional -import kotlin.jvm.optionals.getOrNull - -@JsonDeserialize(using = RawPromptCachingBetaMessageStreamEvent.Deserializer::class) -@JsonSerialize(using = RawPromptCachingBetaMessageStreamEvent.Serializer::class) -class RawPromptCachingBetaMessageStreamEvent -private constructor( - private val rawPromptCachingBetaMessageStartEvent: RawPromptCachingBetaMessageStartEvent? = - null, - private val rawMessageDeltaEvent: RawMessageDeltaEvent? = null, - private val rawMessageStopEvent: RawMessageStopEvent? = null, - private val rawContentBlockStartEvent: RawContentBlockStartEvent? = null, - private val rawContentBlockDeltaEvent: RawContentBlockDeltaEvent? = null, - private val rawContentBlockStopEvent: RawContentBlockStopEvent? = null, - private val _json: JsonValue? = null, -) { - - private var validated: Boolean = false - - fun rawPromptCachingBetaMessageStartEvent(): Optional = - Optional.ofNullable(rawPromptCachingBetaMessageStartEvent) - - fun rawMessageDeltaEvent(): Optional = - Optional.ofNullable(rawMessageDeltaEvent) - - fun rawMessageStopEvent(): Optional = - Optional.ofNullable(rawMessageStopEvent) - - fun rawContentBlockStartEvent(): Optional = - Optional.ofNullable(rawContentBlockStartEvent) - - fun rawContentBlockDeltaEvent(): Optional = - Optional.ofNullable(rawContentBlockDeltaEvent) - - fun rawContentBlockStopEvent(): Optional = - Optional.ofNullable(rawContentBlockStopEvent) - - fun isRawPromptCachingBetaMessageStartEvent(): Boolean = - rawPromptCachingBetaMessageStartEvent != null - - fun isRawMessageDeltaEvent(): Boolean = rawMessageDeltaEvent != null - - fun isRawMessageStopEvent(): Boolean = rawMessageStopEvent != null - - fun isRawContentBlockStartEvent(): Boolean = rawContentBlockStartEvent != null - - fun isRawContentBlockDeltaEvent(): Boolean = rawContentBlockDeltaEvent != null - - fun isRawContentBlockStopEvent(): Boolean = rawContentBlockStopEvent != null - - fun asRawPromptCachingBetaMessageStartEvent(): RawPromptCachingBetaMessageStartEvent = - rawPromptCachingBetaMessageStartEvent.getOrThrow("rawPromptCachingBetaMessageStartEvent") - - fun asRawMessageDeltaEvent(): RawMessageDeltaEvent = - rawMessageDeltaEvent.getOrThrow("rawMessageDeltaEvent") - - fun asRawMessageStopEvent(): RawMessageStopEvent = - rawMessageStopEvent.getOrThrow("rawMessageStopEvent") - - fun asRawContentBlockStartEvent(): RawContentBlockStartEvent = - rawContentBlockStartEvent.getOrThrow("rawContentBlockStartEvent") - - fun asRawContentBlockDeltaEvent(): RawContentBlockDeltaEvent = - rawContentBlockDeltaEvent.getOrThrow("rawContentBlockDeltaEvent") - - fun asRawContentBlockStopEvent(): RawContentBlockStopEvent = - rawContentBlockStopEvent.getOrThrow("rawContentBlockStopEvent") - - fun _json(): Optional = Optional.ofNullable(_json) - - fun accept(visitor: Visitor): T { - return when { - rawPromptCachingBetaMessageStartEvent != null -> - visitor.visitRawPromptCachingBetaMessageStartEvent( - rawPromptCachingBetaMessageStartEvent - ) - rawMessageDeltaEvent != null -> visitor.visitRawMessageDeltaEvent(rawMessageDeltaEvent) - rawMessageStopEvent != null -> visitor.visitRawMessageStopEvent(rawMessageStopEvent) - rawContentBlockStartEvent != null -> - visitor.visitRawContentBlockStartEvent(rawContentBlockStartEvent) - rawContentBlockDeltaEvent != null -> - visitor.visitRawContentBlockDeltaEvent(rawContentBlockDeltaEvent) - rawContentBlockStopEvent != null -> - visitor.visitRawContentBlockStopEvent(rawContentBlockStopEvent) - else -> visitor.unknown(_json) - } - } - - fun validate(): RawPromptCachingBetaMessageStreamEvent = apply { - if (!validated) { - if ( - rawPromptCachingBetaMessageStartEvent == null && - rawMessageDeltaEvent == null && - rawMessageStopEvent == null && - rawContentBlockStartEvent == null && - rawContentBlockDeltaEvent == null && - rawContentBlockStopEvent == null - ) { - throw AnthropicInvalidDataException( - "Unknown RawPromptCachingBetaMessageStreamEvent: $_json" - ) - } - rawPromptCachingBetaMessageStartEvent?.validate() - rawMessageDeltaEvent?.validate() - rawMessageStopEvent?.validate() - rawContentBlockStartEvent?.validate() - rawContentBlockDeltaEvent?.validate() - rawContentBlockStopEvent?.validate() - validated = true - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - - return /* spotless:off */ other is RawPromptCachingBetaMessageStreamEvent && rawPromptCachingBetaMessageStartEvent == other.rawPromptCachingBetaMessageStartEvent && rawMessageDeltaEvent == other.rawMessageDeltaEvent && rawMessageStopEvent == other.rawMessageStopEvent && rawContentBlockStartEvent == other.rawContentBlockStartEvent && rawContentBlockDeltaEvent == other.rawContentBlockDeltaEvent && rawContentBlockStopEvent == other.rawContentBlockStopEvent /* spotless:on */ - } - - override fun hashCode(): Int = /* spotless:off */ Objects.hash(rawPromptCachingBetaMessageStartEvent, rawMessageDeltaEvent, rawMessageStopEvent, rawContentBlockStartEvent, rawContentBlockDeltaEvent, rawContentBlockStopEvent) /* spotless:on */ - - override fun toString(): String = - when { - rawPromptCachingBetaMessageStartEvent != null -> - "RawPromptCachingBetaMessageStreamEvent{rawPromptCachingBetaMessageStartEvent=$rawPromptCachingBetaMessageStartEvent}" - rawMessageDeltaEvent != null -> - "RawPromptCachingBetaMessageStreamEvent{rawMessageDeltaEvent=$rawMessageDeltaEvent}" - rawMessageStopEvent != null -> - "RawPromptCachingBetaMessageStreamEvent{rawMessageStopEvent=$rawMessageStopEvent}" - rawContentBlockStartEvent != null -> - "RawPromptCachingBetaMessageStreamEvent{rawContentBlockStartEvent=$rawContentBlockStartEvent}" - rawContentBlockDeltaEvent != null -> - "RawPromptCachingBetaMessageStreamEvent{rawContentBlockDeltaEvent=$rawContentBlockDeltaEvent}" - rawContentBlockStopEvent != null -> - "RawPromptCachingBetaMessageStreamEvent{rawContentBlockStopEvent=$rawContentBlockStopEvent}" - _json != null -> "RawPromptCachingBetaMessageStreamEvent{_unknown=$_json}" - else -> throw IllegalStateException("Invalid RawPromptCachingBetaMessageStreamEvent") - } - - companion object { - - @JvmStatic - fun ofRawPromptCachingBetaMessageStartEvent( - rawPromptCachingBetaMessageStartEvent: RawPromptCachingBetaMessageStartEvent - ) = - RawPromptCachingBetaMessageStreamEvent( - rawPromptCachingBetaMessageStartEvent = rawPromptCachingBetaMessageStartEvent - ) - - @JvmStatic - fun ofRawMessageDeltaEvent(rawMessageDeltaEvent: RawMessageDeltaEvent) = - RawPromptCachingBetaMessageStreamEvent(rawMessageDeltaEvent = rawMessageDeltaEvent) - - @JvmStatic - fun ofRawMessageStopEvent(rawMessageStopEvent: RawMessageStopEvent) = - RawPromptCachingBetaMessageStreamEvent(rawMessageStopEvent = rawMessageStopEvent) - - @JvmStatic - fun ofRawContentBlockStartEvent(rawContentBlockStartEvent: RawContentBlockStartEvent) = - RawPromptCachingBetaMessageStreamEvent( - rawContentBlockStartEvent = rawContentBlockStartEvent - ) - - @JvmStatic - fun ofRawContentBlockDeltaEvent(rawContentBlockDeltaEvent: RawContentBlockDeltaEvent) = - RawPromptCachingBetaMessageStreamEvent( - rawContentBlockDeltaEvent = rawContentBlockDeltaEvent - ) - - @JvmStatic - fun ofRawContentBlockStopEvent(rawContentBlockStopEvent: RawContentBlockStopEvent) = - RawPromptCachingBetaMessageStreamEvent( - rawContentBlockStopEvent = rawContentBlockStopEvent - ) - } - - interface Visitor { - - fun visitRawPromptCachingBetaMessageStartEvent( - rawPromptCachingBetaMessageStartEvent: RawPromptCachingBetaMessageStartEvent - ): T - - fun visitRawMessageDeltaEvent(rawMessageDeltaEvent: RawMessageDeltaEvent): T - - fun visitRawMessageStopEvent(rawMessageStopEvent: RawMessageStopEvent): T - - fun visitRawContentBlockStartEvent(rawContentBlockStartEvent: RawContentBlockStartEvent): T - - fun visitRawContentBlockDeltaEvent(rawContentBlockDeltaEvent: RawContentBlockDeltaEvent): T - - fun visitRawContentBlockStopEvent(rawContentBlockStopEvent: RawContentBlockStopEvent): T - - fun unknown(json: JsonValue?): T { - throw AnthropicInvalidDataException( - "Unknown RawPromptCachingBetaMessageStreamEvent: $json" - ) - } - } - - class Deserializer : - BaseDeserializer( - RawPromptCachingBetaMessageStreamEvent::class - ) { - - override fun ObjectCodec.deserialize( - node: JsonNode - ): RawPromptCachingBetaMessageStreamEvent { - val json = JsonValue.fromJsonNode(node) - val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull() - - when (type) { - "message_start" -> { - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return RawPromptCachingBetaMessageStreamEvent( - rawPromptCachingBetaMessageStartEvent = it, - _json = json - ) - } - } - "message_delta" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return RawPromptCachingBetaMessageStreamEvent( - rawMessageDeltaEvent = it, - _json = json - ) - } - } - "message_stop" -> { - tryDeserialize(node, jacksonTypeRef()) { it.validate() } - ?.let { - return RawPromptCachingBetaMessageStreamEvent( - rawMessageStopEvent = it, - _json = json - ) - } - } - "content_block_start" -> { - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return RawPromptCachingBetaMessageStreamEvent( - rawContentBlockStartEvent = it, - _json = json - ) - } - } - "content_block_delta" -> { - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return RawPromptCachingBetaMessageStreamEvent( - rawContentBlockDeltaEvent = it, - _json = json - ) - } - } - "content_block_stop" -> { - tryDeserialize(node, jacksonTypeRef()) { - it.validate() - } - ?.let { - return RawPromptCachingBetaMessageStreamEvent( - rawContentBlockStopEvent = it, - _json = json - ) - } - } - } - - return RawPromptCachingBetaMessageStreamEvent(_json = json) - } - } - - class Serializer : - BaseSerializer( - RawPromptCachingBetaMessageStreamEvent::class - ) { - - override fun serialize( - value: RawPromptCachingBetaMessageStreamEvent, - generator: JsonGenerator, - provider: SerializerProvider - ) { - when { - value.rawPromptCachingBetaMessageStartEvent != null -> - generator.writeObject(value.rawPromptCachingBetaMessageStartEvent) - value.rawMessageDeltaEvent != null -> - generator.writeObject(value.rawMessageDeltaEvent) - value.rawMessageStopEvent != null -> - generator.writeObject(value.rawMessageStopEvent) - value.rawContentBlockStartEvent != null -> - generator.writeObject(value.rawContentBlockStartEvent) - value.rawContentBlockDeltaEvent != null -> - generator.writeObject(value.rawContentBlockDeltaEvent) - value.rawContentBlockStopEvent != null -> - generator.writeObject(value.rawContentBlockStopEvent) - value._json != null -> generator.writeObject(value._json) - else -> - throw IllegalStateException("Invalid RawPromptCachingBetaMessageStreamEvent") - } - } - } -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/TextBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/TextBlockParam.kt index 7b59a70..a5cbec6 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/TextBlockParam.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/TextBlockParam.kt @@ -16,11 +16,13 @@ import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects +import java.util.Optional @JsonDeserialize(builder = TextBlockParam.Builder::class) @NoAutoDetect class TextBlockParam private constructor( + private val cacheControl: JsonField, private val type: JsonField, private val text: JsonField, private val additionalProperties: Map, @@ -28,10 +30,15 @@ private constructor( private var validated: Boolean = false + fun cacheControl(): Optional = + Optional.ofNullable(cacheControl.getNullable("cache_control")) + fun type(): Type = type.getRequired("type") fun text(): String = text.getRequired("text") + @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl + @JsonProperty("type") @ExcludeMissing fun _type() = type @JsonProperty("text") @ExcludeMissing fun _text() = text @@ -42,6 +49,7 @@ private constructor( fun validate(): TextBlockParam = apply { if (!validated) { + cacheControl().map { it.validate() } type() text() validated = true @@ -57,17 +65,28 @@ private constructor( class Builder { + private var cacheControl: JsonField = JsonMissing.of() private var type: JsonField = JsonMissing.of() private var text: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(textBlockParam: TextBlockParam) = apply { + this.cacheControl = textBlockParam.cacheControl this.type = textBlockParam.type this.text = textBlockParam.text additionalProperties(textBlockParam.additionalProperties) } + fun cacheControl(cacheControl: CacheControlEphemeral) = + cacheControl(JsonField.of(cacheControl)) + + @JsonProperty("cache_control") + @ExcludeMissing + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + fun type(type: Type) = type(JsonField.of(type)) @JsonProperty("type") @@ -96,6 +115,7 @@ private constructor( fun build(): TextBlockParam = TextBlockParam( + cacheControl, type, text, additionalProperties.toImmutable(), @@ -158,15 +178,15 @@ private constructor( return true } - return /* spotless:off */ other is TextBlockParam && type == other.type && text == other.text && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is TextBlockParam && cacheControl == other.cacheControl && type == other.type && text == other.text && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, text, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(cacheControl, type, text, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "TextBlockParam{type=$type, text=$text, additionalProperties=$additionalProperties}" + "TextBlockParam{cacheControl=$cacheControl, type=$type, text=$text, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/Tool.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/Tool.kt index 0073d94..79c38e7 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/Tool.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/Tool.kt @@ -25,6 +25,7 @@ private constructor( private val description: JsonField, private val name: JsonField, private val inputSchema: JsonField, + private val cacheControl: JsonField, private val additionalProperties: Map, ) { @@ -54,6 +55,9 @@ private constructor( */ fun inputSchema(): InputSchema = inputSchema.getRequired("input_schema") + fun cacheControl(): Optional = + Optional.ofNullable(cacheControl.getNullable("cache_control")) + /** * Description of what this tool does. * @@ -77,6 +81,8 @@ private constructor( */ @JsonProperty("input_schema") @ExcludeMissing fun _inputSchema() = inputSchema + @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl + @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map = additionalProperties @@ -86,6 +92,7 @@ private constructor( description() name() inputSchema().validate() + cacheControl().map { it.validate() } validated = true } } @@ -102,6 +109,7 @@ private constructor( private var description: JsonField = JsonMissing.of() private var name: JsonField = JsonMissing.of() private var inputSchema: JsonField = JsonMissing.of() + private var cacheControl: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic @@ -109,6 +117,7 @@ private constructor( this.description = tool.description this.name = tool.name this.inputSchema = tool.inputSchema + this.cacheControl = tool.cacheControl additionalProperties(tool.additionalProperties) } @@ -170,6 +179,15 @@ private constructor( this.inputSchema = inputSchema } + fun cacheControl(cacheControl: CacheControlEphemeral) = + cacheControl(JsonField.of(cacheControl)) + + @JsonProperty("cache_control") + @ExcludeMissing + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + fun additionalProperties(additionalProperties: Map) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) @@ -189,6 +207,7 @@ private constructor( description, name, inputSchema, + cacheControl, additionalProperties.toImmutable(), ) } @@ -352,15 +371,15 @@ private constructor( return true } - return /* spotless:off */ other is Tool && description == other.description && name == other.name && inputSchema == other.inputSchema && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is Tool && description == other.description && name == other.name && inputSchema == other.inputSchema && cacheControl == other.cacheControl && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(description, name, inputSchema, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(description, name, inputSchema, cacheControl, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "Tool{description=$description, name=$name, inputSchema=$inputSchema, additionalProperties=$additionalProperties}" + "Tool{description=$description, name=$name, inputSchema=$inputSchema, cacheControl=$cacheControl, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolResultBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolResultBlockParam.kt index 53056e2..a418839 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolResultBlockParam.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolResultBlockParam.kt @@ -32,6 +32,7 @@ import kotlin.jvm.optionals.getOrNull @NoAutoDetect class ToolResultBlockParam private constructor( + private val cacheControl: JsonField, private val type: JsonField, private val toolUseId: JsonField, private val isError: JsonField, @@ -41,6 +42,9 @@ private constructor( private var validated: Boolean = false + fun cacheControl(): Optional = + Optional.ofNullable(cacheControl.getNullable("cache_control")) + fun type(): Type = type.getRequired("type") fun toolUseId(): String = toolUseId.getRequired("tool_use_id") @@ -49,6 +53,8 @@ private constructor( fun content(): Optional = Optional.ofNullable(content.getNullable("content")) + @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl + @JsonProperty("type") @ExcludeMissing fun _type() = type @JsonProperty("tool_use_id") @ExcludeMissing fun _toolUseId() = toolUseId @@ -63,6 +69,7 @@ private constructor( fun validate(): ToolResultBlockParam = apply { if (!validated) { + cacheControl().map { it.validate() } type() toolUseId() isError() @@ -80,6 +87,7 @@ private constructor( class Builder { + private var cacheControl: JsonField = JsonMissing.of() private var type: JsonField = JsonMissing.of() private var toolUseId: JsonField = JsonMissing.of() private var isError: JsonField = JsonMissing.of() @@ -88,6 +96,7 @@ private constructor( @JvmSynthetic internal fun from(toolResultBlockParam: ToolResultBlockParam) = apply { + this.cacheControl = toolResultBlockParam.cacheControl this.type = toolResultBlockParam.type this.toolUseId = toolResultBlockParam.toolUseId this.isError = toolResultBlockParam.isError @@ -95,6 +104,15 @@ private constructor( additionalProperties(toolResultBlockParam.additionalProperties) } + fun cacheControl(cacheControl: CacheControlEphemeral) = + cacheControl(JsonField.of(cacheControl)) + + @JsonProperty("cache_control") + @ExcludeMissing + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + fun type(type: Type) = type(JsonField.of(type)) @JsonProperty("type") @@ -135,6 +153,7 @@ private constructor( fun build(): ToolResultBlockParam = ToolResultBlockParam( + cacheControl, type, toolUseId, isError, @@ -439,15 +458,15 @@ private constructor( return true } - return /* spotless:off */ other is ToolResultBlockParam && type == other.type && toolUseId == other.toolUseId && isError == other.isError && content == other.content && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is ToolResultBlockParam && cacheControl == other.cacheControl && type == other.type && toolUseId == other.toolUseId && isError == other.isError && content == other.content && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, toolUseId, isError, content, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(cacheControl, type, toolUseId, isError, content, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "ToolResultBlockParam{type=$type, toolUseId=$toolUseId, isError=$isError, content=$content, additionalProperties=$additionalProperties}" + "ToolResultBlockParam{cacheControl=$cacheControl, type=$type, toolUseId=$toolUseId, isError=$isError, content=$content, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolUseBlockParam.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolUseBlockParam.kt index 80691c9..48fc1b3 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolUseBlockParam.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/ToolUseBlockParam.kt @@ -16,11 +16,13 @@ import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects +import java.util.Optional @JsonDeserialize(builder = ToolUseBlockParam.Builder::class) @NoAutoDetect class ToolUseBlockParam private constructor( + private val cacheControl: JsonField, private val type: JsonField, private val id: JsonField, private val name: JsonField, @@ -30,12 +32,17 @@ private constructor( private var validated: Boolean = false + fun cacheControl(): Optional = + Optional.ofNullable(cacheControl.getNullable("cache_control")) + fun type(): Type = type.getRequired("type") fun id(): String = id.getRequired("id") fun name(): String = name.getRequired("name") + @JsonProperty("cache_control") @ExcludeMissing fun _cacheControl() = cacheControl + @JsonProperty("type") @ExcludeMissing fun _type() = type @JsonProperty("id") @ExcludeMissing fun _id() = id @@ -50,6 +57,7 @@ private constructor( fun validate(): ToolUseBlockParam = apply { if (!validated) { + cacheControl().map { it.validate() } type() id() name() @@ -66,6 +74,7 @@ private constructor( class Builder { + private var cacheControl: JsonField = JsonMissing.of() private var type: JsonField = JsonMissing.of() private var id: JsonField = JsonMissing.of() private var name: JsonField = JsonMissing.of() @@ -74,6 +83,7 @@ private constructor( @JvmSynthetic internal fun from(toolUseBlockParam: ToolUseBlockParam) = apply { + this.cacheControl = toolUseBlockParam.cacheControl this.type = toolUseBlockParam.type this.id = toolUseBlockParam.id this.name = toolUseBlockParam.name @@ -81,6 +91,15 @@ private constructor( additionalProperties(toolUseBlockParam.additionalProperties) } + fun cacheControl(cacheControl: CacheControlEphemeral) = + cacheControl(JsonField.of(cacheControl)) + + @JsonProperty("cache_control") + @ExcludeMissing + fun cacheControl(cacheControl: JsonField) = apply { + this.cacheControl = cacheControl + } + fun type(type: Type) = type(JsonField.of(type)) @JsonProperty("type") @@ -117,6 +136,7 @@ private constructor( fun build(): ToolUseBlockParam = ToolUseBlockParam( + cacheControl, type, id, name, @@ -181,15 +201,15 @@ private constructor( return true } - return /* spotless:off */ other is ToolUseBlockParam && type == other.type && id == other.id && name == other.name && input == other.input && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is ToolUseBlockParam && cacheControl == other.cacheControl && type == other.type && id == other.id && name == other.name && input == other.input && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(type, id, name, input, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(cacheControl, type, id, name, input, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "ToolUseBlockParam{type=$type, id=$id, name=$name, input=$input, additionalProperties=$additionalProperties}" + "ToolUseBlockParam{cacheControl=$cacheControl, type=$type, id=$id, name=$name, input=$input, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/models/Usage.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/models/Usage.kt index 5665d64..2bd0406 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/models/Usage.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/models/Usage.kt @@ -13,12 +13,15 @@ import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects +import java.util.Optional @JsonDeserialize(builder = Usage.Builder::class) @NoAutoDetect class Usage private constructor( private val inputTokens: JsonField, + private val cacheCreationInputTokens: JsonField, + private val cacheReadInputTokens: JsonField, private val outputTokens: JsonField, private val additionalProperties: Map, ) { @@ -28,12 +31,30 @@ private constructor( /** The number of input tokens which were used. */ fun inputTokens(): Long = inputTokens.getRequired("input_tokens") + /** The number of input tokens used to create the cache entry. */ + fun cacheCreationInputTokens(): Optional = + Optional.ofNullable(cacheCreationInputTokens.getNullable("cache_creation_input_tokens")) + + /** The number of input tokens read from the cache. */ + fun cacheReadInputTokens(): Optional = + Optional.ofNullable(cacheReadInputTokens.getNullable("cache_read_input_tokens")) + /** The number of output tokens which were used. */ fun outputTokens(): Long = outputTokens.getRequired("output_tokens") /** The number of input tokens which were used. */ @JsonProperty("input_tokens") @ExcludeMissing fun _inputTokens() = inputTokens + /** The number of input tokens used to create the cache entry. */ + @JsonProperty("cache_creation_input_tokens") + @ExcludeMissing + fun _cacheCreationInputTokens() = cacheCreationInputTokens + + /** The number of input tokens read from the cache. */ + @JsonProperty("cache_read_input_tokens") + @ExcludeMissing + fun _cacheReadInputTokens() = cacheReadInputTokens + /** The number of output tokens which were used. */ @JsonProperty("output_tokens") @ExcludeMissing fun _outputTokens() = outputTokens @@ -44,6 +65,8 @@ private constructor( fun validate(): Usage = apply { if (!validated) { inputTokens() + cacheCreationInputTokens() + cacheReadInputTokens() outputTokens() validated = true } @@ -59,12 +82,16 @@ private constructor( class Builder { private var inputTokens: JsonField = JsonMissing.of() + private var cacheCreationInputTokens: JsonField = JsonMissing.of() + private var cacheReadInputTokens: JsonField = JsonMissing.of() private var outputTokens: JsonField = JsonMissing.of() private var additionalProperties: MutableMap = mutableMapOf() @JvmSynthetic internal fun from(usage: Usage) = apply { this.inputTokens = usage.inputTokens + this.cacheCreationInputTokens = usage.cacheCreationInputTokens + this.cacheReadInputTokens = usage.cacheReadInputTokens this.outputTokens = usage.outputTokens additionalProperties(usage.additionalProperties) } @@ -77,6 +104,28 @@ private constructor( @ExcludeMissing fun inputTokens(inputTokens: JsonField) = apply { this.inputTokens = inputTokens } + /** The number of input tokens used to create the cache entry. */ + fun cacheCreationInputTokens(cacheCreationInputTokens: Long) = + cacheCreationInputTokens(JsonField.of(cacheCreationInputTokens)) + + /** The number of input tokens used to create the cache entry. */ + @JsonProperty("cache_creation_input_tokens") + @ExcludeMissing + fun cacheCreationInputTokens(cacheCreationInputTokens: JsonField) = apply { + this.cacheCreationInputTokens = cacheCreationInputTokens + } + + /** The number of input tokens read from the cache. */ + fun cacheReadInputTokens(cacheReadInputTokens: Long) = + cacheReadInputTokens(JsonField.of(cacheReadInputTokens)) + + /** The number of input tokens read from the cache. */ + @JsonProperty("cache_read_input_tokens") + @ExcludeMissing + fun cacheReadInputTokens(cacheReadInputTokens: JsonField) = apply { + this.cacheReadInputTokens = cacheReadInputTokens + } + /** The number of output tokens which were used. */ fun outputTokens(outputTokens: Long) = outputTokens(JsonField.of(outputTokens)) @@ -102,6 +151,8 @@ private constructor( fun build(): Usage = Usage( inputTokens, + cacheCreationInputTokens, + cacheReadInputTokens, outputTokens, additionalProperties.toImmutable(), ) @@ -112,15 +163,15 @@ private constructor( return true } - return /* spotless:off */ other is Usage && inputTokens == other.inputTokens && outputTokens == other.outputTokens && additionalProperties == other.additionalProperties /* spotless:on */ + return /* spotless:off */ other is Usage && inputTokens == other.inputTokens && cacheCreationInputTokens == other.cacheCreationInputTokens && cacheReadInputTokens == other.cacheReadInputTokens && outputTokens == other.outputTokens && additionalProperties == other.additionalProperties /* spotless:on */ } /* spotless:off */ - private val hashCode: Int by lazy { Objects.hash(inputTokens, outputTokens, additionalProperties) } + private val hashCode: Int by lazy { Objects.hash(inputTokens, cacheCreationInputTokens, cacheReadInputTokens, outputTokens, additionalProperties) } /* spotless:on */ override fun hashCode(): Int = hashCode override fun toString() = - "Usage{inputTokens=$inputTokens, outputTokens=$outputTokens, additionalProperties=$additionalProperties}" + "Usage{inputTokens=$inputTokens, cacheCreationInputTokens=$cacheCreationInputTokens, cacheReadInputTokens=$cacheReadInputTokens, outputTokens=$outputTokens, additionalProperties=$additionalProperties}" } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsync.kt index 8707a89..a2a2fd5 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsync.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsync.kt @@ -3,11 +3,11 @@ package com.anthropic.services.async import com.anthropic.services.async.beta.MessageServiceAsync -import com.anthropic.services.async.beta.PromptCachingServiceAsync +import com.anthropic.services.async.beta.ModelServiceAsync interface BetaServiceAsync { - fun messages(): MessageServiceAsync + fun models(): ModelServiceAsync - fun promptCaching(): PromptCachingServiceAsync + fun messages(): MessageServiceAsync } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsyncImpl.kt index c8b7752..02bb133 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsyncImpl.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/BetaServiceAsyncImpl.kt @@ -5,21 +5,19 @@ package com.anthropic.services.async import com.anthropic.core.ClientOptions import com.anthropic.services.async.beta.MessageServiceAsync import com.anthropic.services.async.beta.MessageServiceAsyncImpl -import com.anthropic.services.async.beta.PromptCachingServiceAsync -import com.anthropic.services.async.beta.PromptCachingServiceAsyncImpl +import com.anthropic.services.async.beta.ModelServiceAsync +import com.anthropic.services.async.beta.ModelServiceAsyncImpl class BetaServiceAsyncImpl constructor( private val clientOptions: ClientOptions, ) : BetaServiceAsync { + private val models: ModelServiceAsync by lazy { ModelServiceAsyncImpl(clientOptions) } + private val messages: MessageServiceAsync by lazy { MessageServiceAsyncImpl(clientOptions) } - private val promptCaching: PromptCachingServiceAsync by lazy { - PromptCachingServiceAsyncImpl(clientOptions) - } + override fun models(): ModelServiceAsync = models override fun messages(): MessageServiceAsync = messages - - override fun promptCaching(): PromptCachingServiceAsync = promptCaching } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsync.kt index c7409f8..f67230c 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsync.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsync.kt @@ -7,12 +7,17 @@ package com.anthropic.services.async import com.anthropic.core.RequestOptions import com.anthropic.core.http.AsyncStreamResponse import com.anthropic.models.Message +import com.anthropic.models.MessageCountTokensParams import com.anthropic.models.MessageCreateParams +import com.anthropic.models.MessageTokensCount import com.anthropic.models.RawMessageStreamEvent +import com.anthropic.services.async.messages.BatchServiceAsync import java.util.concurrent.CompletableFuture interface MessageServiceAsync { + fun batches(): BatchServiceAsync + /** * Send a structured list of input messages with text and/or image content, and the model will * generate the next message in the conversation. @@ -36,4 +41,16 @@ interface MessageServiceAsync { params: MessageCreateParams, requestOptions: RequestOptions = RequestOptions.none() ): AsyncStreamResponse + + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, including tools, + * images, and documents, without creating it. + */ + @JvmOverloads + fun countTokens( + params: MessageCountTokensParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsyncImpl.kt index 5304e66..b53ab3f 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsyncImpl.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/MessageServiceAsyncImpl.kt @@ -20,8 +20,12 @@ import com.anthropic.core.http.toAsync import com.anthropic.core.json import com.anthropic.errors.AnthropicError import com.anthropic.models.Message +import com.anthropic.models.MessageCountTokensParams import com.anthropic.models.MessageCreateParams +import com.anthropic.models.MessageTokensCount import com.anthropic.models.RawMessageStreamEvent +import com.anthropic.services.async.messages.BatchServiceAsync +import com.anthropic.services.async.messages.BatchServiceAsyncImpl import java.time.Duration import java.util.concurrent.CompletableFuture @@ -32,6 +36,10 @@ constructor( private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val batches: BatchServiceAsync by lazy { BatchServiceAsyncImpl(clientOptions) } + + override fun batches(): BatchServiceAsync = batches + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -127,4 +135,39 @@ constructor( } .toAsync(clientOptions.streamHandlerExecutor) } + + private val countTokensHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, including tools, + * images, and documents, without creating it. + */ + override fun countTokens( + params: MessageCountTokensParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("v1", "messages", "count_tokens") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { countTokensHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/ModelServiceAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/ModelServiceAsync.kt new file mode 100644 index 0000000..9e4ad76 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/ModelServiceAsync.kt @@ -0,0 +1,39 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.anthropic.services.async + +import com.anthropic.core.RequestOptions +import com.anthropic.models.ModelInfo +import com.anthropic.models.ModelListPageAsync +import com.anthropic.models.ModelListParams +import com.anthropic.models.ModelRetrieveParams +import java.util.concurrent.CompletableFuture + +interface ModelServiceAsync { + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + @JvmOverloads + fun retrieve( + params: ModelRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + @JvmOverloads + fun list( + params: ModelListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/ModelServiceAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/ModelServiceAsyncImpl.kt new file mode 100644 index 0000000..45d6e86 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/ModelServiceAsyncImpl.kt @@ -0,0 +1,96 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.async + +import com.anthropic.core.ClientOptions +import com.anthropic.core.RequestOptions +import com.anthropic.core.handlers.errorHandler +import com.anthropic.core.handlers.jsonHandler +import com.anthropic.core.handlers.withErrorHandler +import com.anthropic.core.http.HttpMethod +import com.anthropic.core.http.HttpRequest +import com.anthropic.core.http.HttpResponse.Handler +import com.anthropic.errors.AnthropicError +import com.anthropic.models.ModelInfo +import com.anthropic.models.ModelListPageAsync +import com.anthropic.models.ModelListParams +import com.anthropic.models.ModelRetrieveParams +import java.util.concurrent.CompletableFuture + +class ModelServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : ModelServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + override fun retrieve( + params: ModelRetrieveParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + override fun list( + params: ModelListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { ModelListPageAsync.of(this, params, it) } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/ModelServiceAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/ModelServiceAsync.kt new file mode 100644 index 0000000..0801ce4 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/ModelServiceAsync.kt @@ -0,0 +1,39 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.anthropic.services.async.beta + +import com.anthropic.core.RequestOptions +import com.anthropic.models.BetaModelInfo +import com.anthropic.models.BetaModelListPageAsync +import com.anthropic.models.BetaModelListParams +import com.anthropic.models.BetaModelRetrieveParams +import java.util.concurrent.CompletableFuture + +interface ModelServiceAsync { + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + @JvmOverloads + fun retrieve( + params: BetaModelRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + @JvmOverloads + fun list( + params: BetaModelListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/ModelServiceAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/ModelServiceAsyncImpl.kt new file mode 100644 index 0000000..755074f --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/ModelServiceAsyncImpl.kt @@ -0,0 +1,98 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.async.beta + +import com.anthropic.core.ClientOptions +import com.anthropic.core.RequestOptions +import com.anthropic.core.handlers.errorHandler +import com.anthropic.core.handlers.jsonHandler +import com.anthropic.core.handlers.withErrorHandler +import com.anthropic.core.http.HttpMethod +import com.anthropic.core.http.HttpRequest +import com.anthropic.core.http.HttpResponse.Handler +import com.anthropic.errors.AnthropicError +import com.anthropic.models.BetaModelInfo +import com.anthropic.models.BetaModelListPageAsync +import com.anthropic.models.BetaModelListParams +import com.anthropic.models.BetaModelRetrieveParams +import java.util.concurrent.CompletableFuture + +class ModelServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : ModelServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + override fun retrieve( + params: BetaModelRetrieveParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models", params.getPathParam(0)) + .putQueryParam("beta", "true") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + override fun list( + params: BetaModelListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models") + .putQueryParam("beta", "true") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { BetaModelListPageAsync.of(this, params, it) } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/PromptCachingServiceAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/PromptCachingServiceAsync.kt deleted file mode 100644 index f0a772f..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/PromptCachingServiceAsync.kt +++ /dev/null @@ -1,10 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.services.async.beta - -import com.anthropic.services.async.beta.promptCaching.MessageServiceAsync - -interface PromptCachingServiceAsync { - - fun messages(): MessageServiceAsync -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/PromptCachingServiceAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/PromptCachingServiceAsyncImpl.kt deleted file mode 100644 index 9dea429..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/PromptCachingServiceAsyncImpl.kt +++ /dev/null @@ -1,17 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.services.async.beta - -import com.anthropic.core.ClientOptions -import com.anthropic.services.async.beta.promptCaching.MessageServiceAsync -import com.anthropic.services.async.beta.promptCaching.MessageServiceAsyncImpl - -class PromptCachingServiceAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : PromptCachingServiceAsync { - - private val messages: MessageServiceAsync by lazy { MessageServiceAsyncImpl(clientOptions) } - - override fun messages(): MessageServiceAsync = messages -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/promptCaching/MessageServiceAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/promptCaching/MessageServiceAsync.kt deleted file mode 100644 index dbce194..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/promptCaching/MessageServiceAsync.kt +++ /dev/null @@ -1,39 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - -package com.anthropic.services.async.beta.promptCaching - -import com.anthropic.core.RequestOptions -import com.anthropic.core.http.AsyncStreamResponse -import com.anthropic.models.BetaPromptCachingMessageCreateParams -import com.anthropic.models.PromptCachingBetaMessage -import com.anthropic.models.RawPromptCachingBetaMessageStreamEvent -import java.util.concurrent.CompletableFuture - -interface MessageServiceAsync { - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - @JvmOverloads - fun create( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions = RequestOptions.none() - ): CompletableFuture - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - @JvmOverloads - fun createStreaming( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions = RequestOptions.none() - ): AsyncStreamResponse -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/promptCaching/MessageServiceAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/promptCaching/MessageServiceAsyncImpl.kt deleted file mode 100644 index 6472034..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/beta/promptCaching/MessageServiceAsyncImpl.kt +++ /dev/null @@ -1,134 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.services.async.beta.promptCaching - -import com.anthropic.core.ClientOptions -import com.anthropic.core.JsonValue -import com.anthropic.core.RequestOptions -import com.anthropic.core.handlers.errorHandler -import com.anthropic.core.handlers.jsonHandler -import com.anthropic.core.handlers.map -import com.anthropic.core.handlers.mapJson -import com.anthropic.core.handlers.sseHandler -import com.anthropic.core.handlers.withErrorHandler -import com.anthropic.core.http.AsyncStreamResponse -import com.anthropic.core.http.HttpMethod -import com.anthropic.core.http.HttpRequest -import com.anthropic.core.http.HttpResponse.Handler -import com.anthropic.core.http.StreamResponse -import com.anthropic.core.http.toAsync -import com.anthropic.core.json -import com.anthropic.errors.AnthropicError -import com.anthropic.models.BetaPromptCachingMessageCreateParams -import com.anthropic.models.PromptCachingBetaMessage -import com.anthropic.models.RawPromptCachingBetaMessageStreamEvent -import java.time.Duration -import java.util.concurrent.CompletableFuture - -class MessageServiceAsyncImpl -constructor( - private val clientOptions: ClientOptions, -) : MessageServiceAsync { - - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - override fun create( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions - ): CompletableFuture { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "messages") - .putQueryParam("beta", "prompt_caching") - .putAllQueryParams(clientOptions.queryParams) - .replaceAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .replaceAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient - .executeAsync( - request, - requestOptions.applyDefaults( - RequestOptions.builder().timeout(Duration.ofMillis(600000)).build() - ) - ) - .thenApply { response -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } - - private val createStreamingHandler: - Handler> = - sseHandler(clientOptions.jsonMapper) - .mapJson() - .withErrorHandler(errorHandler) - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - override fun createStreaming( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions - ): AsyncStreamResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "messages") - .putQueryParam("beta", "prompt_caching") - .putAllQueryParams(clientOptions.queryParams) - .replaceAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .replaceAllHeaders(params.getHeaders()) - .body( - json( - clientOptions.jsonMapper, - params - .getBody() - .toBuilder() - .putAdditionalProperty("stream", JsonValue.from(true)) - .build() - ) - ) - .build() - return clientOptions.httpClient - .executeAsync( - request, - requestOptions.applyDefaults( - RequestOptions.builder().timeout(Duration.ofMillis(600000)).build() - ) - ) - .thenApply { response -> - response - .let { createStreamingHandler.handle(it) } - .let { streamResponse -> - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - streamResponse.map { it.validate() } - } else { - streamResponse - } - } - } - .toAsync(clientOptions.streamHandlerExecutor) - } -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/messages/BatchServiceAsync.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/messages/BatchServiceAsync.kt new file mode 100644 index 0000000..3076d87 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/messages/BatchServiceAsync.kt @@ -0,0 +1,65 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.anthropic.services.async.messages + +import com.anthropic.core.RequestOptions +import com.anthropic.models.MessageBatch +import com.anthropic.models.MessageBatchCancelParams +import com.anthropic.models.MessageBatchCreateParams +import com.anthropic.models.MessageBatchListPageAsync +import com.anthropic.models.MessageBatchListParams +import com.anthropic.models.MessageBatchRetrieveParams +import java.util.concurrent.CompletableFuture + +interface BatchServiceAsync { + + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at once. Once a + * Message Batch is created, it begins processing immediately. Batches can take up to 24 hours + * to complete. + */ + @JvmOverloads + fun create( + params: MessageBatchCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * This endpoint is idempotent and can be used to poll for Message Batch completion. To access + * the results of a Message Batch, make a request to the `results_url` field in the response. + */ + @JvmOverloads + fun retrieve( + params: MessageBatchRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * List all Message Batches within a Workspace. Most recently created batches are returned + * first. + */ + @JvmOverloads + fun list( + params: MessageBatchListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * Batches may be canceled any time before processing ends. Once cancellation is initiated, the + * batch enters a `canceling` state, at which time the system may complete any in-progress, + * non-interruptible requests before finalizing cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine which requests + * were canceled, check the individual results within the batch. Note that cancellation may not + * result in any canceled requests if they were non-interruptible. + */ + @JvmOverloads + fun cancel( + params: MessageBatchCancelParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/messages/BatchServiceAsyncImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/messages/BatchServiceAsyncImpl.kt new file mode 100644 index 0000000..10f0053 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/async/messages/BatchServiceAsyncImpl.kt @@ -0,0 +1,169 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.async.messages + +import com.anthropic.core.ClientOptions +import com.anthropic.core.RequestOptions +import com.anthropic.core.handlers.errorHandler +import com.anthropic.core.handlers.jsonHandler +import com.anthropic.core.handlers.withErrorHandler +import com.anthropic.core.http.HttpMethod +import com.anthropic.core.http.HttpRequest +import com.anthropic.core.http.HttpResponse.Handler +import com.anthropic.core.json +import com.anthropic.errors.AnthropicError +import com.anthropic.models.MessageBatch +import com.anthropic.models.MessageBatchCancelParams +import com.anthropic.models.MessageBatchCreateParams +import com.anthropic.models.MessageBatchListPageAsync +import com.anthropic.models.MessageBatchListParams +import com.anthropic.models.MessageBatchRetrieveParams +import java.util.concurrent.CompletableFuture + +class BatchServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : BatchServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at once. Once a + * Message Batch is created, it begins processing immediately. Batches can take up to 24 hours + * to complete. + */ + override fun create( + params: MessageBatchCreateParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("v1", "messages", "batches") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * This endpoint is idempotent and can be used to poll for Message Batch completion. To access + * the results of a Message Batch, make a request to the `results_url` field in the response. + */ + override fun retrieve( + params: MessageBatchRetrieveParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "messages", "batches", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** + * List all Message Batches within a Workspace. Most recently created batches are returned + * first. + */ + override fun list( + params: MessageBatchListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "messages", "batches") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { MessageBatchListPageAsync.of(this, params, it) } + } + } + + private val cancelHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Batches may be canceled any time before processing ends. Once cancellation is initiated, the + * batch enters a `canceling` state, at which time the system may complete any in-progress, + * non-interruptible requests before finalizing cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine which requests + * were canceled, check the individual results within the batch. Note that cancellation may not + * result in any canceled requests if they were non-interruptible. + */ + override fun cancel( + params: MessageBatchCancelParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("v1", "messages", "batches", params.getPathParam(0), "cancel") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { cancelHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaService.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaService.kt index a58d330..f818ab9 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaService.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaService.kt @@ -3,11 +3,11 @@ package com.anthropic.services.blocking import com.anthropic.services.blocking.beta.MessageService -import com.anthropic.services.blocking.beta.PromptCachingService +import com.anthropic.services.blocking.beta.ModelService interface BetaService { - fun messages(): MessageService + fun models(): ModelService - fun promptCaching(): PromptCachingService + fun messages(): MessageService } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaServiceImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaServiceImpl.kt index 3940c28..5e522a6 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaServiceImpl.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/BetaServiceImpl.kt @@ -5,21 +5,19 @@ package com.anthropic.services.blocking import com.anthropic.core.ClientOptions import com.anthropic.services.blocking.beta.MessageService import com.anthropic.services.blocking.beta.MessageServiceImpl -import com.anthropic.services.blocking.beta.PromptCachingService -import com.anthropic.services.blocking.beta.PromptCachingServiceImpl +import com.anthropic.services.blocking.beta.ModelService +import com.anthropic.services.blocking.beta.ModelServiceImpl class BetaServiceImpl constructor( private val clientOptions: ClientOptions, ) : BetaService { + private val models: ModelService by lazy { ModelServiceImpl(clientOptions) } + private val messages: MessageService by lazy { MessageServiceImpl(clientOptions) } - private val promptCaching: PromptCachingService by lazy { - PromptCachingServiceImpl(clientOptions) - } + override fun models(): ModelService = models override fun messages(): MessageService = messages - - override fun promptCaching(): PromptCachingService = promptCaching } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageService.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageService.kt index 820709a..b456fb3 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageService.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageService.kt @@ -7,12 +7,17 @@ package com.anthropic.services.blocking import com.anthropic.core.RequestOptions import com.anthropic.core.http.StreamResponse import com.anthropic.models.Message +import com.anthropic.models.MessageCountTokensParams import com.anthropic.models.MessageCreateParams +import com.anthropic.models.MessageTokensCount import com.anthropic.models.RawMessageStreamEvent +import com.anthropic.services.blocking.messages.BatchService import com.google.errorprone.annotations.MustBeClosed interface MessageService { + fun batches(): BatchService + /** * Send a structured list of input messages with text and/or image content, and the model will * generate the next message in the conversation. @@ -37,4 +42,16 @@ interface MessageService { params: MessageCreateParams, requestOptions: RequestOptions = RequestOptions.none() ): StreamResponse + + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, including tools, + * images, and documents, without creating it. + */ + @JvmOverloads + fun countTokens( + params: MessageCountTokensParams, + requestOptions: RequestOptions = RequestOptions.none() + ): MessageTokensCount } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageServiceImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageServiceImpl.kt index 4f57e8f..b4f5cd1 100644 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageServiceImpl.kt +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/MessageServiceImpl.kt @@ -18,8 +18,12 @@ import com.anthropic.core.http.StreamResponse import com.anthropic.core.json import com.anthropic.errors.AnthropicError import com.anthropic.models.Message +import com.anthropic.models.MessageCountTokensParams import com.anthropic.models.MessageCreateParams +import com.anthropic.models.MessageTokensCount import com.anthropic.models.RawMessageStreamEvent +import com.anthropic.services.blocking.messages.BatchService +import com.anthropic.services.blocking.messages.BatchServiceImpl import java.time.Duration class MessageServiceImpl @@ -29,6 +33,10 @@ constructor( private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + private val batches: BatchService by lazy { BatchServiceImpl(clientOptions) } + + override fun batches(): BatchService = batches + private val createHandler: Handler = jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) @@ -120,4 +128,38 @@ constructor( } } } + + private val countTokensHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, including tools, + * images, and documents, without creating it. + */ + override fun countTokens( + params: MessageCountTokensParams, + requestOptions: RequestOptions + ): MessageTokensCount { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("v1", "messages", "count_tokens") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { countTokensHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } } diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/ModelService.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/ModelService.kt new file mode 100644 index 0000000..25932ee --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/ModelService.kt @@ -0,0 +1,38 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.anthropic.services.blocking + +import com.anthropic.core.RequestOptions +import com.anthropic.models.ModelInfo +import com.anthropic.models.ModelListPage +import com.anthropic.models.ModelListParams +import com.anthropic.models.ModelRetrieveParams + +interface ModelService { + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + @JvmOverloads + fun retrieve( + params: ModelRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): ModelInfo + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + @JvmOverloads + fun list( + params: ModelListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): ModelListPage +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/ModelServiceImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/ModelServiceImpl.kt new file mode 100644 index 0000000..19d7f99 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/ModelServiceImpl.kt @@ -0,0 +1,86 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.blocking + +import com.anthropic.core.ClientOptions +import com.anthropic.core.RequestOptions +import com.anthropic.core.handlers.errorHandler +import com.anthropic.core.handlers.jsonHandler +import com.anthropic.core.handlers.withErrorHandler +import com.anthropic.core.http.HttpMethod +import com.anthropic.core.http.HttpRequest +import com.anthropic.core.http.HttpResponse.Handler +import com.anthropic.errors.AnthropicError +import com.anthropic.models.ModelInfo +import com.anthropic.models.ModelListPage +import com.anthropic.models.ModelListParams +import com.anthropic.models.ModelRetrieveParams + +class ModelServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : ModelService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + override fun retrieve(params: ModelRetrieveParams, requestOptions: RequestOptions): ModelInfo { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + override fun list(params: ModelListParams, requestOptions: RequestOptions): ModelListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { ModelListPage.of(this, params, it) } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/ModelService.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/ModelService.kt new file mode 100644 index 0000000..869c858 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/ModelService.kt @@ -0,0 +1,38 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.anthropic.services.blocking.beta + +import com.anthropic.core.RequestOptions +import com.anthropic.models.BetaModelInfo +import com.anthropic.models.BetaModelListPage +import com.anthropic.models.BetaModelListParams +import com.anthropic.models.BetaModelRetrieveParams + +interface ModelService { + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + @JvmOverloads + fun retrieve( + params: BetaModelRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): BetaModelInfo + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + @JvmOverloads + fun list( + params: BetaModelListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): BetaModelListPage +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/ModelServiceImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/ModelServiceImpl.kt new file mode 100644 index 0000000..0b461ee --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/ModelServiceImpl.kt @@ -0,0 +1,95 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.blocking.beta + +import com.anthropic.core.ClientOptions +import com.anthropic.core.RequestOptions +import com.anthropic.core.handlers.errorHandler +import com.anthropic.core.handlers.jsonHandler +import com.anthropic.core.handlers.withErrorHandler +import com.anthropic.core.http.HttpMethod +import com.anthropic.core.http.HttpRequest +import com.anthropic.core.http.HttpResponse.Handler +import com.anthropic.errors.AnthropicError +import com.anthropic.models.BetaModelInfo +import com.anthropic.models.BetaModelListPage +import com.anthropic.models.BetaModelListParams +import com.anthropic.models.BetaModelRetrieveParams + +class ModelServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : ModelService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or + * resolve a model alias to a model ID. + */ + override fun retrieve( + params: BetaModelRetrieveParams, + requestOptions: RequestOptions + ): BetaModelInfo { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models", params.getPathParam(0)) + .putQueryParam("beta", "true") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the + * API. More recently released models are listed first. + */ + override fun list( + params: BetaModelListParams, + requestOptions: RequestOptions + ): BetaModelListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "models") + .putQueryParam("beta", "true") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { BetaModelListPage.of(this, params, it) } + } + } +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/PromptCachingService.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/PromptCachingService.kt deleted file mode 100644 index d6a305c..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/PromptCachingService.kt +++ /dev/null @@ -1,10 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.services.blocking.beta - -import com.anthropic.services.blocking.beta.promptCaching.MessageService - -interface PromptCachingService { - - fun messages(): MessageService -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/PromptCachingServiceImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/PromptCachingServiceImpl.kt deleted file mode 100644 index 5a6f5a5..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/PromptCachingServiceImpl.kt +++ /dev/null @@ -1,17 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.services.blocking.beta - -import com.anthropic.core.ClientOptions -import com.anthropic.services.blocking.beta.promptCaching.MessageService -import com.anthropic.services.blocking.beta.promptCaching.MessageServiceImpl - -class PromptCachingServiceImpl -constructor( - private val clientOptions: ClientOptions, -) : PromptCachingService { - - private val messages: MessageService by lazy { MessageServiceImpl(clientOptions) } - - override fun messages(): MessageService = messages -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageService.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageService.kt deleted file mode 100644 index 058f7b1..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageService.kt +++ /dev/null @@ -1,40 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 - -package com.anthropic.services.blocking.beta.promptCaching - -import com.anthropic.core.RequestOptions -import com.anthropic.core.http.StreamResponse -import com.anthropic.models.BetaPromptCachingMessageCreateParams -import com.anthropic.models.PromptCachingBetaMessage -import com.anthropic.models.RawPromptCachingBetaMessageStreamEvent -import com.google.errorprone.annotations.MustBeClosed - -interface MessageService { - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - @JvmOverloads - fun create( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions = RequestOptions.none() - ): PromptCachingBetaMessage - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - @JvmOverloads - @MustBeClosed - fun createStreaming( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions = RequestOptions.none() - ): StreamResponse -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageServiceImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageServiceImpl.kt deleted file mode 100644 index 4c88563..0000000 --- a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageServiceImpl.kt +++ /dev/null @@ -1,130 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.services.blocking.beta.promptCaching - -import com.anthropic.core.ClientOptions -import com.anthropic.core.JsonValue -import com.anthropic.core.RequestOptions -import com.anthropic.core.handlers.errorHandler -import com.anthropic.core.handlers.jsonHandler -import com.anthropic.core.handlers.map -import com.anthropic.core.handlers.mapJson -import com.anthropic.core.handlers.sseHandler -import com.anthropic.core.handlers.withErrorHandler -import com.anthropic.core.http.HttpMethod -import com.anthropic.core.http.HttpRequest -import com.anthropic.core.http.HttpResponse.Handler -import com.anthropic.core.http.StreamResponse -import com.anthropic.core.json -import com.anthropic.errors.AnthropicError -import com.anthropic.models.BetaPromptCachingMessageCreateParams -import com.anthropic.models.PromptCachingBetaMessage -import com.anthropic.models.RawPromptCachingBetaMessageStreamEvent -import java.time.Duration - -class MessageServiceImpl -constructor( - private val clientOptions: ClientOptions, -) : MessageService { - - private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) - - private val createHandler: Handler = - jsonHandler(clientOptions.jsonMapper) - .withErrorHandler(errorHandler) - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - override fun create( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions - ): PromptCachingBetaMessage { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "messages") - .putQueryParam("beta", "prompt_caching") - .putAllQueryParams(clientOptions.queryParams) - .replaceAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .replaceAllHeaders(params.getHeaders()) - .body(json(clientOptions.jsonMapper, params.getBody())) - .build() - return clientOptions.httpClient - .execute( - request, - requestOptions.applyDefaults( - RequestOptions.builder().timeout(Duration.ofMillis(600000)).build() - ) - ) - .let { response -> - response - .use { createHandler.handle(it) } - .apply { - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - validate() - } - } - } - } - - private val createStreamingHandler: - Handler> = - sseHandler(clientOptions.jsonMapper) - .mapJson() - .withErrorHandler(errorHandler) - - /** - * Send a structured list of input messages with text and/or image content, and the model will - * generate the next message in the conversation. - * - * The Messages API can be used for either single queries or stateless multi-turn conversations. - */ - override fun createStreaming( - params: BetaPromptCachingMessageCreateParams, - requestOptions: RequestOptions - ): StreamResponse { - val request = - HttpRequest.builder() - .method(HttpMethod.POST) - .addPathSegments("v1", "messages") - .putQueryParam("beta", "prompt_caching") - .putAllQueryParams(clientOptions.queryParams) - .replaceAllQueryParams(params.getQueryParams()) - .putAllHeaders(clientOptions.headers) - .replaceAllHeaders(params.getHeaders()) - .body( - json( - clientOptions.jsonMapper, - params - .getBody() - .toBuilder() - .putAdditionalProperty("stream", JsonValue.from(true)) - .build() - ) - ) - .build() - return clientOptions.httpClient - .execute( - request, - requestOptions.applyDefaults( - RequestOptions.builder().timeout(Duration.ofMillis(600000)).build() - ) - ) - .let { response -> - response - .let { createStreamingHandler.handle(it) } - .let { streamResponse -> - if (requestOptions.responseValidation ?: clientOptions.responseValidation) { - streamResponse.map { it.validate() } - } else { - streamResponse - } - } - } - } -} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/messages/BatchService.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/messages/BatchService.kt new file mode 100644 index 0000000..b098e43 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/messages/BatchService.kt @@ -0,0 +1,64 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.anthropic.services.blocking.messages + +import com.anthropic.core.RequestOptions +import com.anthropic.models.MessageBatch +import com.anthropic.models.MessageBatchCancelParams +import com.anthropic.models.MessageBatchCreateParams +import com.anthropic.models.MessageBatchListPage +import com.anthropic.models.MessageBatchListParams +import com.anthropic.models.MessageBatchRetrieveParams + +interface BatchService { + + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at once. Once a + * Message Batch is created, it begins processing immediately. Batches can take up to 24 hours + * to complete. + */ + @JvmOverloads + fun create( + params: MessageBatchCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): MessageBatch + + /** + * This endpoint is idempotent and can be used to poll for Message Batch completion. To access + * the results of a Message Batch, make a request to the `results_url` field in the response. + */ + @JvmOverloads + fun retrieve( + params: MessageBatchRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): MessageBatch + + /** + * List all Message Batches within a Workspace. Most recently created batches are returned + * first. + */ + @JvmOverloads + fun list( + params: MessageBatchListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): MessageBatchListPage + + /** + * Batches may be canceled any time before processing ends. Once cancellation is initiated, the + * batch enters a `canceling` state, at which time the system may complete any in-progress, + * non-interruptible requests before finalizing cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine which requests + * were canceled, check the individual results within the batch. Note that cancellation may not + * result in any canceled requests if they were non-interruptible. + */ + @JvmOverloads + fun cancel( + params: MessageBatchCancelParams, + requestOptions: RequestOptions = RequestOptions.none() + ): MessageBatch +} diff --git a/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/messages/BatchServiceImpl.kt b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/messages/BatchServiceImpl.kt new file mode 100644 index 0000000..b2cab06 --- /dev/null +++ b/anthropic-java-core/src/main/kotlin/com/anthropic/services/blocking/messages/BatchServiceImpl.kt @@ -0,0 +1,164 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.blocking.messages + +import com.anthropic.core.ClientOptions +import com.anthropic.core.RequestOptions +import com.anthropic.core.handlers.errorHandler +import com.anthropic.core.handlers.jsonHandler +import com.anthropic.core.handlers.withErrorHandler +import com.anthropic.core.http.HttpMethod +import com.anthropic.core.http.HttpRequest +import com.anthropic.core.http.HttpResponse.Handler +import com.anthropic.core.json +import com.anthropic.errors.AnthropicError +import com.anthropic.models.MessageBatch +import com.anthropic.models.MessageBatchCancelParams +import com.anthropic.models.MessageBatchCreateParams +import com.anthropic.models.MessageBatchListPage +import com.anthropic.models.MessageBatchListParams +import com.anthropic.models.MessageBatchRetrieveParams + +class BatchServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : BatchService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at once. Once a + * Message Batch is created, it begins processing immediately. Batches can take up to 24 hours + * to complete. + */ + override fun create( + params: MessageBatchCreateParams, + requestOptions: RequestOptions + ): MessageBatch { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("v1", "messages", "batches") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * This endpoint is idempotent and can be used to poll for Message Batch completion. To access + * the results of a Message Batch, make a request to the `results_url` field in the response. + */ + override fun retrieve( + params: MessageBatchRetrieveParams, + requestOptions: RequestOptions + ): MessageBatch { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "messages", "batches", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** + * List all Message Batches within a Workspace. Most recently created batches are returned + * first. + */ + override fun list( + params: MessageBatchListParams, + requestOptions: RequestOptions + ): MessageBatchListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("v1", "messages", "batches") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { MessageBatchListPage.of(this, params, it) } + } + } + + private val cancelHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Batches may be canceled any time before processing ends. Once cancellation is initiated, the + * batch enters a `canceling` state, at which time the system may complete any in-progress, + * non-interruptible requests before finalizing cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine which requests + * were canceled, check the individual results within the batch. Note that cancellation may not + * result in any canceled requests if they were non-interruptible. + */ + override fun cancel( + params: MessageBatchCancelParams, + requestOptions: RequestOptions + ): MessageBatch { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("v1", "messages", "batches", params.getPathParam(0), "cancel") + .putAllQueryParams(clientOptions.queryParams) + .replaceAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .replaceAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { cancelHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ApiErrorObjectTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ApiErrorObjectTest.kt new file mode 100644 index 0000000..5e67949 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ApiErrorObjectTest.kt @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ApiErrorObjectTest { + + @Test + fun createApiErrorObject() { + val apiErrorObject = + ApiErrorObject.builder().message("message").type(ApiErrorObject.Type.API_ERROR).build() + assertThat(apiErrorObject).isNotNull + assertThat(apiErrorObject.message()).isEqualTo("message") + assertThat(apiErrorObject.type()).isEqualTo(ApiErrorObject.Type.API_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/AuthenticationErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/AuthenticationErrorTest.kt new file mode 100644 index 0000000..02c116d --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/AuthenticationErrorTest.kt @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class AuthenticationErrorTest { + + @Test + fun createAuthenticationError() { + val authenticationError = + AuthenticationError.builder() + .message("message") + .type(AuthenticationError.Type.AUTHENTICATION_ERROR) + .build() + assertThat(authenticationError).isNotNull + assertThat(authenticationError.message()).isEqualTo("message") + assertThat(authenticationError.type()) + .isEqualTo(AuthenticationError.Type.AUTHENTICATION_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/Base64PdfSourceTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/Base64PdfSourceTest.kt new file mode 100644 index 0000000..b983efd --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/Base64PdfSourceTest.kt @@ -0,0 +1,23 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class Base64PdfSourceTest { + + @Test + fun createBase64PdfSource() { + val base64PdfSource = + Base64PdfSource.builder() + .data("U3RhaW5sZXNzIHJvY2tz") + .mediaType(Base64PdfSource.MediaType.APPLICATION_PDF) + .type(Base64PdfSource.Type.BASE64) + .build() + assertThat(base64PdfSource).isNotNull + assertThat(base64PdfSource.data()).isEqualTo("U3RhaW5sZXNzIHJvY2tz") + assertThat(base64PdfSource.mediaType()).isEqualTo(Base64PdfSource.MediaType.APPLICATION_PDF) + assertThat(base64PdfSource.type()).isEqualTo(Base64PdfSource.Type.BASE64) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaBillingErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaBillingErrorTest.kt new file mode 100644 index 0000000..05007c1 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaBillingErrorTest.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BetaBillingErrorTest { + + @Test + fun createBetaBillingError() { + val betaBillingError = + BetaBillingError.builder() + .message("message") + .type(BetaBillingError.Type.BILLING_ERROR) + .build() + assertThat(betaBillingError).isNotNull + assertThat(betaBillingError.message()).isEqualTo("message") + assertThat(betaBillingError.type()).isEqualTo(BetaBillingError.Type.BILLING_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaGatewayTimeoutErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaGatewayTimeoutErrorTest.kt new file mode 100644 index 0000000..46e6d65 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaGatewayTimeoutErrorTest.kt @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BetaGatewayTimeoutErrorTest { + + @Test + fun createBetaGatewayTimeoutError() { + val betaGatewayTimeoutError = + BetaGatewayTimeoutError.builder() + .message("message") + .type(BetaGatewayTimeoutError.Type.TIMEOUT_ERROR) + .build() + assertThat(betaGatewayTimeoutError).isNotNull + assertThat(betaGatewayTimeoutError.message()).isEqualTo("message") + assertThat(betaGatewayTimeoutError.type()) + .isEqualTo(BetaGatewayTimeoutError.Type.TIMEOUT_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelInfoTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelInfoTest.kt new file mode 100644 index 0000000..11eb12d --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelInfoTest.kt @@ -0,0 +1,27 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BetaModelInfoTest { + + @Test + fun createBetaModelInfo() { + val betaModelInfo = + BetaModelInfo.builder() + .id("claude-3-5-sonnet-20241022") + .createdAt(OffsetDateTime.parse("2024-10-22T00:00:00Z")) + .displayName("Claude 3.5 Sonnet (New)") + .type(BetaModelInfo.Type.MODEL) + .build() + assertThat(betaModelInfo).isNotNull + assertThat(betaModelInfo.id()).isEqualTo("claude-3-5-sonnet-20241022") + assertThat(betaModelInfo.createdAt()) + .isEqualTo(OffsetDateTime.parse("2024-10-22T00:00:00Z")) + assertThat(betaModelInfo.displayName()).isEqualTo("Claude 3.5 Sonnet (New)") + assertThat(betaModelInfo.type()).isEqualTo(BetaModelInfo.Type.MODEL) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelListParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelListParamsTest.kt new file mode 100644 index 0000000..0dc0f28 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelListParamsTest.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BetaModelListParamsTest { + + @Test + fun createBetaModelListParams() { + BetaModelListParams.builder().afterId("after_id").beforeId("before_id").limit(1L).build() + } + + @Test + fun getQueryParams() { + val params = + BetaModelListParams.builder() + .afterId("after_id") + .beforeId("before_id") + .limit(1L) + .build() + val expected = QueryParams.builder() + expected.put("after_id", "after_id") + expected.put("before_id", "before_id") + expected.put("limit", "1") + assertThat(params.getQueryParams()).isEqualTo(expected.build()) + } + + @Test + fun getQueryParamsWithoutOptionalFields() { + val params = BetaModelListParams.builder().build() + val expected = QueryParams.builder() + assertThat(params.getQueryParams()).isEqualTo(expected.build()) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelRetrieveParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelRetrieveParamsTest.kt new file mode 100644 index 0000000..cd2de39 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaModelRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BetaModelRetrieveParamsTest { + + @Test + fun createBetaModelRetrieveParams() { + BetaModelRetrieveParams.builder().modelId("model_id").build() + } + + @Test + fun getPathParam() { + val params = BetaModelRetrieveParams.builder().modelId("model_id").build() + assertThat(params).isNotNull + // path param "modelId" + assertThat(params.getPathParam(0)).isEqualTo("model_id") + // out-of-bound path param + assertThat(params.getPathParam(1)).isEqualTo("") + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BillingErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BillingErrorTest.kt new file mode 100644 index 0000000..6ae5969 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/BillingErrorTest.kt @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BillingErrorTest { + + @Test + fun createBillingError() { + val billingError = + BillingError.builder().message("message").type(BillingError.Type.BILLING_ERROR).build() + assertThat(billingError).isNotNull + assertThat(billingError.message()).isEqualTo("message") + assertThat(billingError.type()).isEqualTo(BillingError.Type.BILLING_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/CacheControlEphemeralTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/CacheControlEphemeralTest.kt new file mode 100644 index 0000000..f8b583d --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/CacheControlEphemeralTest.kt @@ -0,0 +1,17 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class CacheControlEphemeralTest { + + @Test + fun createCacheControlEphemeral() { + val cacheControlEphemeral = + CacheControlEphemeral.builder().type(CacheControlEphemeral.Type.EPHEMERAL).build() + assertThat(cacheControlEphemeral).isNotNull + assertThat(cacheControlEphemeral.type()).isEqualTo(CacheControlEphemeral.Type.EPHEMERAL) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/DocumentBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/DocumentBlockParamTest.kt new file mode 100644 index 0000000..38afa2a --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/DocumentBlockParamTest.kt @@ -0,0 +1,43 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class DocumentBlockParamTest { + + @Test + fun createDocumentBlockParam() { + val documentBlockParam = + DocumentBlockParam.builder() + .source( + Base64PdfSource.builder() + .data("U3RhaW5sZXNzIHJvY2tz") + .mediaType(Base64PdfSource.MediaType.APPLICATION_PDF) + .type(Base64PdfSource.Type.BASE64) + .build() + ) + .type(DocumentBlockParam.Type.DOCUMENT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) + .build() + assertThat(documentBlockParam).isNotNull + assertThat(documentBlockParam.source()) + .isEqualTo( + Base64PdfSource.builder() + .data("U3RhaW5sZXNzIHJvY2tz") + .mediaType(Base64PdfSource.MediaType.APPLICATION_PDF) + .type(Base64PdfSource.Type.BASE64) + .build() + ) + assertThat(documentBlockParam.type()).isEqualTo(DocumentBlockParam.Type.DOCUMENT) + assertThat(documentBlockParam.cacheControl()) + .contains( + CacheControlEphemeral.builder().type(CacheControlEphemeral.Type.EPHEMERAL).build() + ) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ErrorResponseTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ErrorResponseTest.kt new file mode 100644 index 0000000..45ad98e --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ErrorResponseTest.kt @@ -0,0 +1,36 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ErrorResponseTest { + + @Test + fun createErrorResponse() { + val errorResponse = + ErrorResponse.builder() + .error( + ErrorObject.ofInvalidRequestError( + InvalidRequestError.builder() + .message("message") + .type(InvalidRequestError.Type.INVALID_REQUEST_ERROR) + .build() + ) + ) + .type(ErrorResponse.Type.ERROR) + .build() + assertThat(errorResponse).isNotNull + assertThat(errorResponse.error()) + .isEqualTo( + ErrorObject.ofInvalidRequestError( + InvalidRequestError.builder() + .message("message") + .type(InvalidRequestError.Type.INVALID_REQUEST_ERROR) + .build() + ) + ) + assertThat(errorResponse.type()).isEqualTo(ErrorResponse.Type.ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/GatewayTimeoutErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/GatewayTimeoutErrorTest.kt new file mode 100644 index 0000000..e34cfb4 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/GatewayTimeoutErrorTest.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class GatewayTimeoutErrorTest { + + @Test + fun createGatewayTimeoutError() { + val gatewayTimeoutError = + GatewayTimeoutError.builder() + .message("message") + .type(GatewayTimeoutError.Type.TIMEOUT_ERROR) + .build() + assertThat(gatewayTimeoutError).isNotNull + assertThat(gatewayTimeoutError.message()).isEqualTo("message") + assertThat(gatewayTimeoutError.type()).isEqualTo(GatewayTimeoutError.Type.TIMEOUT_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ImageBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ImageBlockParamTest.kt index 8644a98..29e1eac 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ImageBlockParamTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ImageBlockParamTest.kt @@ -19,6 +19,11 @@ class ImageBlockParamTest { .build() ) .type(ImageBlockParam.Type.IMAGE) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() assertThat(imageBlockParam).isNotNull assertThat(imageBlockParam.source()) @@ -30,5 +35,9 @@ class ImageBlockParamTest { .build() ) assertThat(imageBlockParam.type()).isEqualTo(ImageBlockParam.Type.IMAGE) + assertThat(imageBlockParam.cacheControl()) + .contains( + CacheControlEphemeral.builder().type(CacheControlEphemeral.Type.EPHEMERAL).build() + ) } } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/InvalidRequestErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/InvalidRequestErrorTest.kt new file mode 100644 index 0000000..5b27890 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/InvalidRequestErrorTest.kt @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class InvalidRequestErrorTest { + + @Test + fun createInvalidRequestError() { + val invalidRequestError = + InvalidRequestError.builder() + .message("message") + .type(InvalidRequestError.Type.INVALID_REQUEST_ERROR) + .build() + assertThat(invalidRequestError).isNotNull + assertThat(invalidRequestError.message()).isEqualTo("message") + assertThat(invalidRequestError.type()) + .isEqualTo(InvalidRequestError.Type.INVALID_REQUEST_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCancelParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCancelParamsTest.kt new file mode 100644 index 0000000..2f7d014 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCancelParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchCancelParamsTest { + + @Test + fun createMessageBatchCancelParams() { + MessageBatchCancelParams.builder().messageBatchId("message_batch_id").build() + } + + @Test + fun getPathParam() { + val params = MessageBatchCancelParams.builder().messageBatchId("message_batch_id").build() + assertThat(params).isNotNull + // path param "messageBatchId" + assertThat(params.getPathParam(0)).isEqualTo("message_batch_id") + // out-of-bound path param + assertThat(params.getPathParam(1)).isEqualTo("") + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCanceledResultTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCanceledResultTest.kt new file mode 100644 index 0000000..68826f7 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCanceledResultTest.kt @@ -0,0 +1,20 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchCanceledResultTest { + + @Test + fun createMessageBatchCanceledResult() { + val messageBatchCanceledResult = + MessageBatchCanceledResult.builder() + .type(MessageBatchCanceledResult.Type.CANCELED) + .build() + assertThat(messageBatchCanceledResult).isNotNull + assertThat(messageBatchCanceledResult.type()) + .isEqualTo(MessageBatchCanceledResult.Type.CANCELED) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCreateParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCreateParamsTest.kt new file mode 100644 index 0000000..80c4661 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchCreateParamsTest.kt @@ -0,0 +1,368 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.JsonValue +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchCreateParamsTest { + + @Test + fun createMessageBatchCreateParams() { + MessageBatchCreateParams.builder() + .requests( + listOf( + MessageBatchCreateParams.Request.builder() + .customId("my-custom-id-1") + .params( + MessageBatchCreateParams.Request.Params.builder() + .maxTokens(1024L) + .messages( + listOf( + MessageParam.builder() + .content(MessageParam.Content.ofString("Hello, world")) + .role(MessageParam.Role.USER) + .build() + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .metadata( + Metadata.builder() + .userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b") + .build() + ) + .stopSequences(listOf("string")) + .stream(true) + .system( + MessageBatchCreateParams.Request.Params.System + .ofTextBlockParams( + listOf( + TextBlockParam.builder() + .text("Today's date is 2024-06-01.") + .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type( + CacheControlEphemeral.Type.EPHEMERAL + ) + .build() + ) + .build() + ) + ) + ) + .temperature(1.0) + .toolChoice( + ToolChoice.ofToolChoiceAuto( + ToolChoiceAuto.builder() + .type(ToolChoiceAuto.Type.AUTO) + .disableParallelToolUse(true) + .build() + ) + ) + .tools( + listOf( + Tool.builder() + .inputSchema( + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) + .properties( + JsonValue.from( + mapOf( + "location" to + mapOf( + "description" to + "The city and state, e.g. San Francisco, CA", + "type" to "string" + ), + "unit" to + mapOf( + "description" to + "Unit for the output - one of (celsius, fahrenheit)", + "type" to "string" + ) + ) + ) + ) + .build() + ) + .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) + .description( + "Get the current weather in a given location" + ) + .build() + ) + ) + .topK(5L) + .topP(0.7) + .build() + ) + .build() + ) + ) + .build() + } + + @Test + fun getBody() { + val params = + MessageBatchCreateParams.builder() + .requests( + listOf( + MessageBatchCreateParams.Request.builder() + .customId("my-custom-id-1") + .params( + MessageBatchCreateParams.Request.Params.builder() + .maxTokens(1024L) + .messages( + listOf( + MessageParam.builder() + .content( + MessageParam.Content.ofString("Hello, world") + ) + .role(MessageParam.Role.USER) + .build() + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .metadata( + Metadata.builder() + .userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b") + .build() + ) + .stopSequences(listOf("string")) + .stream(true) + .system( + MessageBatchCreateParams.Request.Params.System + .ofTextBlockParams( + listOf( + TextBlockParam.builder() + .text("Today's date is 2024-06-01.") + .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type( + CacheControlEphemeral.Type + .EPHEMERAL + ) + .build() + ) + .build() + ) + ) + ) + .temperature(1.0) + .toolChoice( + ToolChoice.ofToolChoiceAuto( + ToolChoiceAuto.builder() + .type(ToolChoiceAuto.Type.AUTO) + .disableParallelToolUse(true) + .build() + ) + ) + .tools( + listOf( + Tool.builder() + .inputSchema( + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) + .properties( + JsonValue.from( + mapOf( + "location" to + mapOf( + "description" to + "The city and state, e.g. San Francisco, CA", + "type" to "string" + ), + "unit" to + mapOf( + "description" to + "Unit for the output - one of (celsius, fahrenheit)", + "type" to "string" + ) + ) + ) + ) + .build() + ) + .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) + .description( + "Get the current weather in a given location" + ) + .build() + ) + ) + .topK(5L) + .topP(0.7) + .build() + ) + .build() + ) + ) + .build() + val body = params.getBody() + assertThat(body).isNotNull + assertThat(body.requests()) + .isEqualTo( + listOf( + MessageBatchCreateParams.Request.builder() + .customId("my-custom-id-1") + .params( + MessageBatchCreateParams.Request.Params.builder() + .maxTokens(1024L) + .messages( + listOf( + MessageParam.builder() + .content(MessageParam.Content.ofString("Hello, world")) + .role(MessageParam.Role.USER) + .build() + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .metadata( + Metadata.builder() + .userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b") + .build() + ) + .stopSequences(listOf("string")) + .stream(true) + .system( + MessageBatchCreateParams.Request.Params.System + .ofTextBlockParams( + listOf( + TextBlockParam.builder() + .text("Today's date is 2024-06-01.") + .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type( + CacheControlEphemeral.Type.EPHEMERAL + ) + .build() + ) + .build() + ) + ) + ) + .temperature(1.0) + .toolChoice( + ToolChoice.ofToolChoiceAuto( + ToolChoiceAuto.builder() + .type(ToolChoiceAuto.Type.AUTO) + .disableParallelToolUse(true) + .build() + ) + ) + .tools( + listOf( + Tool.builder() + .inputSchema( + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) + .properties( + JsonValue.from( + mapOf( + "location" to + mapOf( + "description" to + "The city and state, e.g. San Francisco, CA", + "type" to "string" + ), + "unit" to + mapOf( + "description" to + "Unit for the output - one of (celsius, fahrenheit)", + "type" to "string" + ) + ) + ) + ) + .build() + ) + .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) + .description( + "Get the current weather in a given location" + ) + .build() + ) + ) + .topK(5L) + .topP(0.7) + .build() + ) + .build() + ) + ) + } + + @Test + fun getBodyWithoutOptionalFields() { + val params = + MessageBatchCreateParams.builder() + .requests( + listOf( + MessageBatchCreateParams.Request.builder() + .customId("my-custom-id-1") + .params( + MessageBatchCreateParams.Request.Params.builder() + .maxTokens(1024L) + .messages( + listOf( + MessageParam.builder() + .content( + MessageParam.Content.ofString("Hello, world") + ) + .role(MessageParam.Role.USER) + .build() + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .build() + ) + .build() + ) + ) + .build() + val body = params.getBody() + assertThat(body).isNotNull + assertThat(body.requests()) + .isEqualTo( + listOf( + MessageBatchCreateParams.Request.builder() + .customId("my-custom-id-1") + .params( + MessageBatchCreateParams.Request.Params.builder() + .maxTokens(1024L) + .messages( + listOf( + MessageParam.builder() + .content(MessageParam.Content.ofString("Hello, world")) + .role(MessageParam.Role.USER) + .build() + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .build() + ) + .build() + ) + ) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchErroredResultTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchErroredResultTest.kt new file mode 100644 index 0000000..b86592f --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchErroredResultTest.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchErroredResultTest { + + @Test + fun createMessageBatchErroredResult() { + val messageBatchErroredResult = + MessageBatchErroredResult.builder() + .error( + ErrorResponse.builder() + .error( + ErrorObject.ofInvalidRequestError( + InvalidRequestError.builder() + .message("message") + .type(InvalidRequestError.Type.INVALID_REQUEST_ERROR) + .build() + ) + ) + .type(ErrorResponse.Type.ERROR) + .build() + ) + .type(MessageBatchErroredResult.Type.ERRORED) + .build() + assertThat(messageBatchErroredResult).isNotNull + assertThat(messageBatchErroredResult.error()) + .isEqualTo( + ErrorResponse.builder() + .error( + ErrorObject.ofInvalidRequestError( + InvalidRequestError.builder() + .message("message") + .type(InvalidRequestError.Type.INVALID_REQUEST_ERROR) + .build() + ) + ) + .type(ErrorResponse.Type.ERROR) + .build() + ) + assertThat(messageBatchErroredResult.type()) + .isEqualTo(MessageBatchErroredResult.Type.ERRORED) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchExpiredResultTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchExpiredResultTest.kt new file mode 100644 index 0000000..0499b00 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchExpiredResultTest.kt @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchExpiredResultTest { + + @Test + fun createMessageBatchExpiredResult() { + val messageBatchExpiredResult = + MessageBatchExpiredResult.builder().type(MessageBatchExpiredResult.Type.EXPIRED).build() + assertThat(messageBatchExpiredResult).isNotNull + assertThat(messageBatchExpiredResult.type()) + .isEqualTo(MessageBatchExpiredResult.Type.EXPIRED) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchIndividualResponseTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchIndividualResponseTest.kt new file mode 100644 index 0000000..aeaab70 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchIndividualResponseTest.kt @@ -0,0 +1,88 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchIndividualResponseTest { + + @Test + fun createMessageBatchIndividualResponse() { + val messageBatchIndividualResponse = + MessageBatchIndividualResponse.builder() + .customId("my-custom-id-1") + .result( + MessageBatchResult.ofMessageBatchSucceededResult( + MessageBatchSucceededResult.builder() + .message( + Message.builder() + .id("msg_013Zva2CMHLNnXjNJJKqJ2EF") + .content( + listOf( + ContentBlock.ofTextBlock( + TextBlock.builder() + .text("Hi! My name is Claude.") + .type(TextBlock.Type.TEXT) + .build() + ) + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .role(Message.Role.ASSISTANT) + .stopReason(Message.StopReason.END_TURN) + .type(Message.Type.MESSAGE) + .usage( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) + .build() + ) + .type(MessageBatchSucceededResult.Type.SUCCEEDED) + .build() + ) + ) + .build() + assertThat(messageBatchIndividualResponse).isNotNull + assertThat(messageBatchIndividualResponse.customId()).isEqualTo("my-custom-id-1") + assertThat(messageBatchIndividualResponse.result()) + .isEqualTo( + MessageBatchResult.ofMessageBatchSucceededResult( + MessageBatchSucceededResult.builder() + .message( + Message.builder() + .id("msg_013Zva2CMHLNnXjNJJKqJ2EF") + .content( + listOf( + ContentBlock.ofTextBlock( + TextBlock.builder() + .text("Hi! My name is Claude.") + .type(TextBlock.Type.TEXT) + .build() + ) + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .role(Message.Role.ASSISTANT) + .stopReason(Message.StopReason.END_TURN) + .type(Message.Type.MESSAGE) + .usage( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) + .build() + ) + .type(MessageBatchSucceededResult.Type.SUCCEEDED) + .build() + ) + ) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchListParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchListParamsTest.kt new file mode 100644 index 0000000..1b47d9b --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchListParamsTest.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchListParamsTest { + + @Test + fun createMessageBatchListParams() { + MessageBatchListParams.builder().afterId("after_id").beforeId("before_id").limit(1L).build() + } + + @Test + fun getQueryParams() { + val params = + MessageBatchListParams.builder() + .afterId("after_id") + .beforeId("before_id") + .limit(1L) + .build() + val expected = QueryParams.builder() + expected.put("after_id", "after_id") + expected.put("before_id", "before_id") + expected.put("limit", "1") + assertThat(params.getQueryParams()).isEqualTo(expected.build()) + } + + @Test + fun getQueryParamsWithoutOptionalFields() { + val params = MessageBatchListParams.builder().build() + val expected = QueryParams.builder() + assertThat(params.getQueryParams()).isEqualTo(expected.build()) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchRequestCountsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchRequestCountsTest.kt new file mode 100644 index 0000000..a80e464 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchRequestCountsTest.kt @@ -0,0 +1,27 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchRequestCountsTest { + + @Test + fun createMessageBatchRequestCounts() { + val messageBatchRequestCounts = + MessageBatchRequestCounts.builder() + .canceled(10L) + .errored(30L) + .expired(10L) + .processing(100L) + .succeeded(50L) + .build() + assertThat(messageBatchRequestCounts).isNotNull + assertThat(messageBatchRequestCounts.canceled()).isEqualTo(10L) + assertThat(messageBatchRequestCounts.errored()).isEqualTo(30L) + assertThat(messageBatchRequestCounts.expired()).isEqualTo(10L) + assertThat(messageBatchRequestCounts.processing()).isEqualTo(100L) + assertThat(messageBatchRequestCounts.succeeded()).isEqualTo(50L) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchRetrieveParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchRetrieveParamsTest.kt new file mode 100644 index 0000000..7b994f3 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchRetrieveParamsTest { + + @Test + fun createMessageBatchRetrieveParams() { + MessageBatchRetrieveParams.builder().messageBatchId("message_batch_id").build() + } + + @Test + fun getPathParam() { + val params = MessageBatchRetrieveParams.builder().messageBatchId("message_batch_id").build() + assertThat(params).isNotNull + // path param "messageBatchId" + assertThat(params.getPathParam(0)).isEqualTo("message_batch_id") + // out-of-bound path param + assertThat(params.getPathParam(1)).isEqualTo("") + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStartEventTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchSucceededResultTest.kt similarity index 63% rename from anthropic-java-core/src/test/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStartEventTest.kt rename to anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchSucceededResultTest.kt index ec694ce..21b0d9c 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/RawPromptCachingBetaMessageStartEventTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchSucceededResultTest.kt @@ -5,14 +5,14 @@ package com.anthropic.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class RawPromptCachingBetaMessageStartEventTest { +class MessageBatchSucceededResultTest { @Test - fun createRawPromptCachingBetaMessageStartEvent() { - val rawPromptCachingBetaMessageStartEvent = - RawPromptCachingBetaMessageStartEvent.builder() + fun createMessageBatchSucceededResult() { + val messageBatchSucceededResult = + MessageBatchSucceededResult.builder() .message( - PromptCachingBetaMessage.builder() + Message.builder() .id("msg_013Zva2CMHLNnXjNJJKqJ2EF") .content( listOf( @@ -25,11 +25,11 @@ class RawPromptCachingBetaMessageStartEventTest { ) ) .model(Model.CLAUDE_3_5_HAIKU_LATEST) - .role(PromptCachingBetaMessage.Role.ASSISTANT) - .stopReason(PromptCachingBetaMessage.StopReason.END_TURN) - .type(PromptCachingBetaMessage.Type.MESSAGE) + .role(Message.Role.ASSISTANT) + .stopReason(Message.StopReason.END_TURN) + .type(Message.Type.MESSAGE) .usage( - PromptCachingBetaUsage.builder() + Usage.builder() .cacheCreationInputTokens(2051L) .cacheReadInputTokens(2051L) .inputTokens(2095L) @@ -38,12 +38,12 @@ class RawPromptCachingBetaMessageStartEventTest { ) .build() ) - .type(RawPromptCachingBetaMessageStartEvent.Type.MESSAGE_START) + .type(MessageBatchSucceededResult.Type.SUCCEEDED) .build() - assertThat(rawPromptCachingBetaMessageStartEvent).isNotNull - assertThat(rawPromptCachingBetaMessageStartEvent.message()) + assertThat(messageBatchSucceededResult).isNotNull + assertThat(messageBatchSucceededResult.message()) .isEqualTo( - PromptCachingBetaMessage.builder() + Message.builder() .id("msg_013Zva2CMHLNnXjNJJKqJ2EF") .content( listOf( @@ -56,11 +56,11 @@ class RawPromptCachingBetaMessageStartEventTest { ) ) .model(Model.CLAUDE_3_5_HAIKU_LATEST) - .role(PromptCachingBetaMessage.Role.ASSISTANT) - .stopReason(PromptCachingBetaMessage.StopReason.END_TURN) - .type(PromptCachingBetaMessage.Type.MESSAGE) + .role(Message.Role.ASSISTANT) + .stopReason(Message.StopReason.END_TURN) + .type(Message.Type.MESSAGE) .usage( - PromptCachingBetaUsage.builder() + Usage.builder() .cacheCreationInputTokens(2051L) .cacheReadInputTokens(2051L) .inputTokens(2095L) @@ -69,7 +69,7 @@ class RawPromptCachingBetaMessageStartEventTest { ) .build() ) - assertThat(rawPromptCachingBetaMessageStartEvent.type()) - .isEqualTo(RawPromptCachingBetaMessageStartEvent.Type.MESSAGE_START) + assertThat(messageBatchSucceededResult.type()) + .isEqualTo(MessageBatchSucceededResult.Type.SUCCEEDED) } } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchTest.kt new file mode 100644 index 0000000..8f70cdc --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageBatchTest.kt @@ -0,0 +1,66 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageBatchTest { + + @Test + fun createMessageBatch() { + val messageBatch = + MessageBatch.builder() + .id("msgbatch_013Zva2CMHLNnXjNJJKqJ2EF") + .archivedAt(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + .cancelInitiatedAt(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + .createdAt(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + .endedAt(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + .expiresAt(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + .processingStatus(MessageBatch.ProcessingStatus.IN_PROGRESS) + .requestCounts( + MessageBatchRequestCounts.builder() + .canceled(10L) + .errored(30L) + .expired(10L) + .processing(100L) + .succeeded(50L) + .build() + ) + .resultsUrl( + "https://api.anthropic.com/v1/messages/batches/msgbatch_013Zva2CMHLNnXjNJJKqJ2EF/results" + ) + .type(MessageBatch.Type.MESSAGE_BATCH) + .build() + assertThat(messageBatch).isNotNull + assertThat(messageBatch.id()).isEqualTo("msgbatch_013Zva2CMHLNnXjNJJKqJ2EF") + assertThat(messageBatch.archivedAt()) + .contains(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + assertThat(messageBatch.cancelInitiatedAt()) + .contains(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + assertThat(messageBatch.createdAt()) + .isEqualTo(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + assertThat(messageBatch.endedAt()) + .contains(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + assertThat(messageBatch.expiresAt()) + .isEqualTo(OffsetDateTime.parse("2024-08-20T18:37:24.100435Z")) + assertThat(messageBatch.processingStatus()) + .isEqualTo(MessageBatch.ProcessingStatus.IN_PROGRESS) + assertThat(messageBatch.requestCounts()) + .isEqualTo( + MessageBatchRequestCounts.builder() + .canceled(10L) + .errored(30L) + .expired(10L) + .processing(100L) + .succeeded(50L) + .build() + ) + assertThat(messageBatch.resultsUrl()) + .contains( + "https://api.anthropic.com/v1/messages/batches/msgbatch_013Zva2CMHLNnXjNJJKqJ2EF/results" + ) + assertThat(messageBatch.type()).isEqualTo(MessageBatch.Type.MESSAGE_BATCH) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaPromptCachingMessageCreateParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageCountTokensParamsTest.kt similarity index 62% rename from anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaPromptCachingMessageCreateParamsTest.kt rename to anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageCountTokensParamsTest.kt index b1e9239..680be4c 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/BetaPromptCachingMessageCreateParamsTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageCountTokensParamsTest.kt @@ -6,39 +6,35 @@ import com.anthropic.core.JsonValue import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test -class BetaPromptCachingMessageCreateParamsTest { +class MessageCountTokensParamsTest { @Test - fun createBetaPromptCachingMessageCreateParams() { - BetaPromptCachingMessageCreateParams.builder() - .maxTokens(1024L) + fun createMessageCountTokensParams() { + MessageCountTokensParams.builder() .messages( listOf( - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) + MessageParam.builder() + .content(MessageParam.Content.ofString("string")) + .role(MessageParam.Role.USER) .build() ) ) .model(Model.CLAUDE_3_5_HAIKU_LATEST) - .metadata(Metadata.builder().userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b").build()) - .stopSequences(listOf("string")) .system( - BetaPromptCachingMessageCreateParams.System.ofPromptCachingBetaTextBlockParams( + MessageCountTokensParams.System.ofTextBlockParams( listOf( - PromptCachingBetaTextBlockParam.builder() + TextBlockParam.builder() .text("Today's date is 2024-06-01.") - .type(PromptCachingBetaTextBlockParam.Type.TEXT) + .type(TextBlockParam.Type.TEXT) .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) .build() ) .build() ) ) ) - .temperature(1.0) .toolChoice( ToolChoice.ofToolChoiceAuto( ToolChoiceAuto.builder() @@ -49,10 +45,10 @@ class BetaPromptCachingMessageCreateParamsTest { ) .tools( listOf( - PromptCachingBetaTool.builder() + Tool.builder() .inputSchema( - PromptCachingBetaTool.InputSchema.builder() - .type(PromptCachingBetaTool.InputSchema.Type.OBJECT) + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) .properties( JsonValue.from( mapOf( @@ -75,52 +71,45 @@ class BetaPromptCachingMessageCreateParamsTest { ) .name("x") .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) .build() ) .description("Get the current weather in a given location") .build() ) ) - .topK(5L) - .topP(0.7) - .betas(listOf(AnthropicBeta.MESSAGE_BATCHES_2024_09_24)) .build() } @Test fun getBody() { val params = - BetaPromptCachingMessageCreateParams.builder() - .maxTokens(1024L) + MessageCountTokensParams.builder() .messages( listOf( - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) + MessageParam.builder() + .content(MessageParam.Content.ofString("string")) + .role(MessageParam.Role.USER) .build() ) ) .model(Model.CLAUDE_3_5_HAIKU_LATEST) - .metadata(Metadata.builder().userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b").build()) - .stopSequences(listOf("string")) .system( - BetaPromptCachingMessageCreateParams.System.ofPromptCachingBetaTextBlockParams( + MessageCountTokensParams.System.ofTextBlockParams( listOf( - PromptCachingBetaTextBlockParam.builder() + TextBlockParam.builder() .text("Today's date is 2024-06-01.") - .type(PromptCachingBetaTextBlockParam.Type.TEXT) + .type(TextBlockParam.Type.TEXT) .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) .build() ) .build() ) ) ) - .temperature(1.0) .toolChoice( ToolChoice.ofToolChoiceAuto( ToolChoiceAuto.builder() @@ -131,10 +120,10 @@ class BetaPromptCachingMessageCreateParamsTest { ) .tools( listOf( - PromptCachingBetaTool.builder() + Tool.builder() .inputSchema( - PromptCachingBetaTool.InputSchema.builder() - .type(PromptCachingBetaTool.InputSchema.Type.OBJECT) + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) .properties( JsonValue.from( mapOf( @@ -157,51 +146,43 @@ class BetaPromptCachingMessageCreateParamsTest { ) .name("x") .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) .build() ) .description("Get the current weather in a given location") .build() ) ) - .topK(5L) - .topP(0.7) - .betas(listOf(AnthropicBeta.MESSAGE_BATCHES_2024_09_24)) .build() val body = params.getBody() assertThat(body).isNotNull - assertThat(body.maxTokens()).isEqualTo(1024L) assertThat(body.messages()) .isEqualTo( listOf( - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) + MessageParam.builder() + .content(MessageParam.Content.ofString("string")) + .role(MessageParam.Role.USER) .build() ) ) assertThat(body.model()).isEqualTo(Model.CLAUDE_3_5_HAIKU_LATEST) - assertThat(body.metadata()) - .isEqualTo(Metadata.builder().userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b").build()) - assertThat(body.stopSequences()).isEqualTo(listOf("string")) assertThat(body.system()) .isEqualTo( - BetaPromptCachingMessageCreateParams.System.ofPromptCachingBetaTextBlockParams( + MessageCountTokensParams.System.ofTextBlockParams( listOf( - PromptCachingBetaTextBlockParam.builder() + TextBlockParam.builder() .text("Today's date is 2024-06-01.") - .type(PromptCachingBetaTextBlockParam.Type.TEXT) + .type(TextBlockParam.Type.TEXT) .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) .build() ) .build() ) ) ) - assertThat(body.temperature()).isEqualTo(1.0) assertThat(body.toolChoice()) .isEqualTo( ToolChoice.ofToolChoiceAuto( @@ -214,10 +195,10 @@ class BetaPromptCachingMessageCreateParamsTest { assertThat(body.tools()) .isEqualTo( listOf( - PromptCachingBetaTool.builder() + Tool.builder() .inputSchema( - PromptCachingBetaTool.InputSchema.builder() - .type(PromptCachingBetaTool.InputSchema.Type.OBJECT) + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) .properties( JsonValue.from( mapOf( @@ -240,28 +221,25 @@ class BetaPromptCachingMessageCreateParamsTest { ) .name("x") .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) .build() ) .description("Get the current weather in a given location") .build() ) ) - assertThat(body.topK()).isEqualTo(5L) - assertThat(body.topP()).isEqualTo(0.7) } @Test fun getBodyWithoutOptionalFields() { val params = - BetaPromptCachingMessageCreateParams.builder() - .maxTokens(1024L) + MessageCountTokensParams.builder() .messages( listOf( - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) + MessageParam.builder() + .content(MessageParam.Content.ofString("string")) + .role(MessageParam.Role.USER) .build() ) ) @@ -269,13 +247,12 @@ class BetaPromptCachingMessageCreateParamsTest { .build() val body = params.getBody() assertThat(body).isNotNull - assertThat(body.maxTokens()).isEqualTo(1024L) assertThat(body.messages()) .isEqualTo( listOf( - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) + MessageParam.builder() + .content(MessageParam.Content.ofString("string")) + .role(MessageParam.Role.USER) .build() ) ) diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageCreateParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageCreateParamsTest.kt index 994bf02..486fbee 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageCreateParamsTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageCreateParamsTest.kt @@ -29,6 +29,11 @@ class MessageCreateParamsTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -69,6 +74,11 @@ class MessageCreateParamsTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -100,6 +110,11 @@ class MessageCreateParamsTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -140,6 +155,11 @@ class MessageCreateParamsTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -170,6 +190,11 @@ class MessageCreateParamsTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -212,6 +237,11 @@ class MessageCreateParamsTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageTest.kt index 091c548..b5d9b1f 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageTest.kt @@ -26,7 +26,14 @@ class MessageTest { .role(Message.Role.ASSISTANT) .stopReason(Message.StopReason.END_TURN) .type(Message.Type.MESSAGE) - .usage(Usage.builder().inputTokens(2095L).outputTokens(503L).build()) + .usage( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) .build() assertThat(message).isNotNull assertThat(message.id()).isEqualTo("msg_013Zva2CMHLNnXjNJJKqJ2EF") @@ -44,6 +51,13 @@ class MessageTest { assertThat(message.stopReason()).contains(Message.StopReason.END_TURN) assertThat(message.type()).isEqualTo(Message.Type.MESSAGE) assertThat(message.usage()) - .isEqualTo(Usage.builder().inputTokens(2095L).outputTokens(503L).build()) + .isEqualTo( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) } } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageTokensCountTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageTokensCountTest.kt new file mode 100644 index 0000000..f3ed5eb --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/MessageTokensCountTest.kt @@ -0,0 +1,16 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class MessageTokensCountTest { + + @Test + fun createMessageTokensCount() { + val messageTokensCount = MessageTokensCount.builder().inputTokens(2095L).build() + assertThat(messageTokensCount).isNotNull + assertThat(messageTokensCount.inputTokens()).isEqualTo(2095L) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelInfoTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelInfoTest.kt new file mode 100644 index 0000000..1a77006 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelInfoTest.kt @@ -0,0 +1,26 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ModelInfoTest { + + @Test + fun createModelInfo() { + val modelInfo = + ModelInfo.builder() + .id("claude-3-5-sonnet-20241022") + .createdAt(OffsetDateTime.parse("2024-10-22T00:00:00Z")) + .displayName("Claude 3.5 Sonnet (New)") + .type(ModelInfo.Type.MODEL) + .build() + assertThat(modelInfo).isNotNull + assertThat(modelInfo.id()).isEqualTo("claude-3-5-sonnet-20241022") + assertThat(modelInfo.createdAt()).isEqualTo(OffsetDateTime.parse("2024-10-22T00:00:00Z")) + assertThat(modelInfo.displayName()).isEqualTo("Claude 3.5 Sonnet (New)") + assertThat(modelInfo.type()).isEqualTo(ModelInfo.Type.MODEL) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelListParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelListParamsTest.kt new file mode 100644 index 0000000..7eaafd3 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelListParamsTest.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import com.anthropic.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ModelListParamsTest { + + @Test + fun createModelListParams() { + ModelListParams.builder().afterId("after_id").beforeId("before_id").limit(1L).build() + } + + @Test + fun getQueryParams() { + val params = + ModelListParams.builder().afterId("after_id").beforeId("before_id").limit(1L).build() + val expected = QueryParams.builder() + expected.put("after_id", "after_id") + expected.put("before_id", "before_id") + expected.put("limit", "1") + assertThat(params.getQueryParams()).isEqualTo(expected.build()) + } + + @Test + fun getQueryParamsWithoutOptionalFields() { + val params = ModelListParams.builder().build() + val expected = QueryParams.builder() + assertThat(params.getQueryParams()).isEqualTo(expected.build()) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelRetrieveParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelRetrieveParamsTest.kt new file mode 100644 index 0000000..429260f --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ModelRetrieveParamsTest.kt @@ -0,0 +1,24 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ModelRetrieveParamsTest { + + @Test + fun createModelRetrieveParams() { + ModelRetrieveParams.builder().modelId("model_id").build() + } + + @Test + fun getPathParam() { + val params = ModelRetrieveParams.builder().modelId("model_id").build() + assertThat(params).isNotNull + // path param "modelId" + assertThat(params.getPathParam(0)).isEqualTo("model_id") + // out-of-bound path param + assertThat(params.getPathParam(1)).isEqualTo("") + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/NotFoundErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/NotFoundErrorTest.kt new file mode 100644 index 0000000..5afc5fe --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/NotFoundErrorTest.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class NotFoundErrorTest { + + @Test + fun createNotFoundError() { + val notFoundError = + NotFoundError.builder() + .message("message") + .type(NotFoundError.Type.NOT_FOUND_ERROR) + .build() + assertThat(notFoundError).isNotNull + assertThat(notFoundError.message()).isEqualTo("message") + assertThat(notFoundError.type()).isEqualTo(NotFoundError.Type.NOT_FOUND_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/OverloadedErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/OverloadedErrorTest.kt new file mode 100644 index 0000000..2cb38d4 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/OverloadedErrorTest.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class OverloadedErrorTest { + + @Test + fun createOverloadedError() { + val overloadedError = + OverloadedError.builder() + .message("message") + .type(OverloadedError.Type.OVERLOADED_ERROR) + .build() + assertThat(overloadedError).isNotNull + assertThat(overloadedError.message()).isEqualTo("message") + assertThat(overloadedError.type()).isEqualTo(OverloadedError.Type.OVERLOADED_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PermissionErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PermissionErrorTest.kt new file mode 100644 index 0000000..18f9410 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PermissionErrorTest.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class PermissionErrorTest { + + @Test + fun createPermissionError() { + val permissionError = + PermissionError.builder() + .message("message") + .type(PermissionError.Type.PERMISSION_ERROR) + .build() + assertThat(permissionError).isNotNull + assertThat(permissionError.message()).isEqualTo("message") + assertThat(permissionError.type()).isEqualTo(PermissionError.Type.PERMISSION_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaCacheControlEphemeralTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaCacheControlEphemeralTest.kt deleted file mode 100644 index 64e9b68..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaCacheControlEphemeralTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaCacheControlEphemeralTest { - - @Test - fun createPromptCachingBetaCacheControlEphemeral() { - val promptCachingBetaCacheControlEphemeral = - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - assertThat(promptCachingBetaCacheControlEphemeral).isNotNull - assertThat(promptCachingBetaCacheControlEphemeral.type()) - .isEqualTo(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaImageBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaImageBlockParamTest.kt deleted file mode 100644 index a95929b..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaImageBlockParamTest.kt +++ /dev/null @@ -1,46 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaImageBlockParamTest { - - @Test - fun createPromptCachingBetaImageBlockParam() { - val promptCachingBetaImageBlockParam = - PromptCachingBetaImageBlockParam.builder() - .source( - PromptCachingBetaImageBlockParam.Source.builder() - .data("U3RhaW5sZXNzIHJvY2tz") - .mediaType(PromptCachingBetaImageBlockParam.Source.MediaType.IMAGE_JPEG) - .type(PromptCachingBetaImageBlockParam.Source.Type.BASE64) - .build() - ) - .type(PromptCachingBetaImageBlockParam.Type.IMAGE) - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - .build() - assertThat(promptCachingBetaImageBlockParam).isNotNull - assertThat(promptCachingBetaImageBlockParam.source()) - .isEqualTo( - PromptCachingBetaImageBlockParam.Source.builder() - .data("U3RhaW5sZXNzIHJvY2tz") - .mediaType(PromptCachingBetaImageBlockParam.Source.MediaType.IMAGE_JPEG) - .type(PromptCachingBetaImageBlockParam.Source.Type.BASE64) - .build() - ) - assertThat(promptCachingBetaImageBlockParam.type()) - .isEqualTo(PromptCachingBetaImageBlockParam.Type.IMAGE) - assertThat(promptCachingBetaImageBlockParam.cacheControl()) - .contains( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaMessageParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaMessageParamTest.kt deleted file mode 100644 index 1fe4b26..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaMessageParamTest.kt +++ /dev/null @@ -1,23 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaMessageParamTest { - - @Test - fun createPromptCachingBetaMessageParam() { - val promptCachingBetaMessageParam = - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) - .build() - assertThat(promptCachingBetaMessageParam).isNotNull - assertThat(promptCachingBetaMessageParam.content()) - .isEqualTo(PromptCachingBetaMessageParam.Content.ofString("string")) - assertThat(promptCachingBetaMessageParam.role()) - .isEqualTo(PromptCachingBetaMessageParam.Role.USER) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaMessageTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaMessageTest.kt deleted file mode 100644 index e0e908d..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaMessageTest.kt +++ /dev/null @@ -1,65 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaMessageTest { - - @Test - fun createPromptCachingBetaMessage() { - val promptCachingBetaMessage = - PromptCachingBetaMessage.builder() - .id("msg_013Zva2CMHLNnXjNJJKqJ2EF") - .content( - listOf( - ContentBlock.ofTextBlock( - TextBlock.builder() - .text("Hi! My name is Claude.") - .type(TextBlock.Type.TEXT) - .build() - ) - ) - ) - .model(Model.CLAUDE_3_5_HAIKU_LATEST) - .role(PromptCachingBetaMessage.Role.ASSISTANT) - .stopReason(PromptCachingBetaMessage.StopReason.END_TURN) - .type(PromptCachingBetaMessage.Type.MESSAGE) - .usage( - PromptCachingBetaUsage.builder() - .cacheCreationInputTokens(2051L) - .cacheReadInputTokens(2051L) - .inputTokens(2095L) - .outputTokens(503L) - .build() - ) - .build() - assertThat(promptCachingBetaMessage).isNotNull - assertThat(promptCachingBetaMessage.id()).isEqualTo("msg_013Zva2CMHLNnXjNJJKqJ2EF") - assertThat(promptCachingBetaMessage.content()) - .containsExactly( - ContentBlock.ofTextBlock( - TextBlock.builder() - .text("Hi! My name is Claude.") - .type(TextBlock.Type.TEXT) - .build() - ) - ) - assertThat(promptCachingBetaMessage.model()).isEqualTo(Model.CLAUDE_3_5_HAIKU_LATEST) - assertThat(promptCachingBetaMessage.role()) - .isEqualTo(PromptCachingBetaMessage.Role.ASSISTANT) - assertThat(promptCachingBetaMessage.stopReason()) - .contains(PromptCachingBetaMessage.StopReason.END_TURN) - assertThat(promptCachingBetaMessage.type()).isEqualTo(PromptCachingBetaMessage.Type.MESSAGE) - assertThat(promptCachingBetaMessage.usage()) - .isEqualTo( - PromptCachingBetaUsage.builder() - .cacheCreationInputTokens(2051L) - .cacheReadInputTokens(2051L) - .inputTokens(2095L) - .outputTokens(503L) - .build() - ) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaTextBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaTextBlockParamTest.kt deleted file mode 100644 index ea0d040..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaTextBlockParamTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaTextBlockParamTest { - - @Test - fun createPromptCachingBetaTextBlockParam() { - val promptCachingBetaTextBlockParam = - PromptCachingBetaTextBlockParam.builder() - .text("x") - .type(PromptCachingBetaTextBlockParam.Type.TEXT) - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - .build() - assertThat(promptCachingBetaTextBlockParam).isNotNull - assertThat(promptCachingBetaTextBlockParam.text()).isEqualTo("x") - assertThat(promptCachingBetaTextBlockParam.type()) - .isEqualTo(PromptCachingBetaTextBlockParam.Type.TEXT) - assertThat(promptCachingBetaTextBlockParam.cacheControl()) - .contains( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolResultBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolResultBlockParamTest.kt deleted file mode 100644 index 6613e49..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolResultBlockParamTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaToolResultBlockParamTest { - - @Test - fun createPromptCachingBetaToolResultBlockParam() { - val promptCachingBetaToolResultBlockParam = - PromptCachingBetaToolResultBlockParam.builder() - .toolUseId("tool_use_id") - .type(PromptCachingBetaToolResultBlockParam.Type.TOOL_RESULT) - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - .content(PromptCachingBetaToolResultBlockParam.Content.ofString("string")) - .isError(true) - .build() - assertThat(promptCachingBetaToolResultBlockParam).isNotNull - assertThat(promptCachingBetaToolResultBlockParam.toolUseId()).isEqualTo("tool_use_id") - assertThat(promptCachingBetaToolResultBlockParam.type()) - .isEqualTo(PromptCachingBetaToolResultBlockParam.Type.TOOL_RESULT) - assertThat(promptCachingBetaToolResultBlockParam.cacheControl()) - .contains( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - assertThat(promptCachingBetaToolResultBlockParam.content()) - .contains(PromptCachingBetaToolResultBlockParam.Content.ofString("string")) - assertThat(promptCachingBetaToolResultBlockParam.isError()).contains(true) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolTest.kt deleted file mode 100644 index d815325..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolTest.kt +++ /dev/null @@ -1,81 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.JsonValue -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaToolTest { - - @Test - fun createPromptCachingBetaTool() { - val promptCachingBetaTool = - PromptCachingBetaTool.builder() - .inputSchema( - PromptCachingBetaTool.InputSchema.builder() - .type(PromptCachingBetaTool.InputSchema.Type.OBJECT) - .properties( - JsonValue.from( - mapOf( - "location" to - mapOf( - "description" to - "The city and state, e.g. San Francisco, CA", - "type" to "string" - ), - "unit" to - mapOf( - "description" to - "Unit for the output - one of (celsius, fahrenheit)", - "type" to "string" - ) - ) - ) - ) - .build() - ) - .name("x") - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - .description("Get the current weather in a given location") - .build() - assertThat(promptCachingBetaTool).isNotNull - assertThat(promptCachingBetaTool.inputSchema()) - .isEqualTo( - PromptCachingBetaTool.InputSchema.builder() - .type(PromptCachingBetaTool.InputSchema.Type.OBJECT) - .properties( - JsonValue.from( - mapOf( - "location" to - mapOf( - "description" to - "The city and state, e.g. San Francisco, CA", - "type" to "string" - ), - "unit" to - mapOf( - "description" to - "Unit for the output - one of (celsius, fahrenheit)", - "type" to "string" - ) - ) - ) - ) - .build() - ) - assertThat(promptCachingBetaTool.name()).isEqualTo("x") - assertThat(promptCachingBetaTool.cacheControl()) - .contains( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - assertThat(promptCachingBetaTool.description()) - .contains("Get the current weather in a given location") - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolUseBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolUseBlockParamTest.kt deleted file mode 100644 index ca7fc45..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaToolUseBlockParamTest.kt +++ /dev/null @@ -1,39 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import com.anthropic.core.JsonValue -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaToolUseBlockParamTest { - - @Test - fun createPromptCachingBetaToolUseBlockParam() { - val promptCachingBetaToolUseBlockParam = - PromptCachingBetaToolUseBlockParam.builder() - .id("id") - .input(JsonValue.from(mapOf())) - .name("x") - .type(PromptCachingBetaToolUseBlockParam.Type.TOOL_USE) - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - .build() - assertThat(promptCachingBetaToolUseBlockParam).isNotNull - assertThat(promptCachingBetaToolUseBlockParam.id()).isEqualTo("id") - assertThat(promptCachingBetaToolUseBlockParam._input()) - .isEqualTo(JsonValue.from(mapOf())) - assertThat(promptCachingBetaToolUseBlockParam.name()).isEqualTo("x") - assertThat(promptCachingBetaToolUseBlockParam.type()) - .isEqualTo(PromptCachingBetaToolUseBlockParam.Type.TOOL_USE) - assertThat(promptCachingBetaToolUseBlockParam.cacheControl()) - .contains( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaUsageTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaUsageTest.kt deleted file mode 100644 index f573655..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/PromptCachingBetaUsageTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.models - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class PromptCachingBetaUsageTest { - - @Test - fun createPromptCachingBetaUsage() { - val promptCachingBetaUsage = - PromptCachingBetaUsage.builder() - .cacheCreationInputTokens(2051L) - .cacheReadInputTokens(2051L) - .inputTokens(2095L) - .outputTokens(503L) - .build() - assertThat(promptCachingBetaUsage).isNotNull - assertThat(promptCachingBetaUsage.cacheCreationInputTokens()).contains(2051L) - assertThat(promptCachingBetaUsage.cacheReadInputTokens()).contains(2051L) - assertThat(promptCachingBetaUsage.inputTokens()).isEqualTo(2095L) - assertThat(promptCachingBetaUsage.outputTokens()).isEqualTo(503L) - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/RateLimitErrorTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/RateLimitErrorTest.kt new file mode 100644 index 0000000..b0023dd --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/RateLimitErrorTest.kt @@ -0,0 +1,21 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class RateLimitErrorTest { + + @Test + fun createRateLimitError() { + val rateLimitError = + RateLimitError.builder() + .message("message") + .type(RateLimitError.Type.RATE_LIMIT_ERROR) + .build() + assertThat(rateLimitError).isNotNull + assertThat(rateLimitError.message()).isEqualTo("message") + assertThat(rateLimitError.type()).isEqualTo(RateLimitError.Type.RATE_LIMIT_ERROR) + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/RawMessageStartEventTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/RawMessageStartEventTest.kt index bb19cd9..25c0023 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/RawMessageStartEventTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/RawMessageStartEventTest.kt @@ -28,7 +28,14 @@ class RawMessageStartEventTest { .role(Message.Role.ASSISTANT) .stopReason(Message.StopReason.END_TURN) .type(Message.Type.MESSAGE) - .usage(Usage.builder().inputTokens(2095L).outputTokens(503L).build()) + .usage( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) .build() ) .type(RawMessageStartEvent.Type.MESSAGE_START) @@ -52,7 +59,14 @@ class RawMessageStartEventTest { .role(Message.Role.ASSISTANT) .stopReason(Message.StopReason.END_TURN) .type(Message.Type.MESSAGE) - .usage(Usage.builder().inputTokens(2095L).outputTokens(503L).build()) + .usage( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) .build() ) assertThat(rawMessageStartEvent.type()).isEqualTo(RawMessageStartEvent.Type.MESSAGE_START) diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/TextBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/TextBlockParamTest.kt index 80b1987..ea1711a 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/TextBlockParamTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/TextBlockParamTest.kt @@ -10,9 +10,21 @@ class TextBlockParamTest { @Test fun createTextBlockParam() { val textBlockParam = - TextBlockParam.builder().text("x").type(TextBlockParam.Type.TEXT).build() + TextBlockParam.builder() + .text("x") + .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) + .build() assertThat(textBlockParam).isNotNull assertThat(textBlockParam.text()).isEqualTo("x") assertThat(textBlockParam.type()).isEqualTo(TextBlockParam.Type.TEXT) + assertThat(textBlockParam.cacheControl()) + .contains( + CacheControlEphemeral.builder().type(CacheControlEphemeral.Type.EPHEMERAL).build() + ) } } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolResultBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolResultBlockParamTest.kt index 1231447..70005da 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolResultBlockParamTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolResultBlockParamTest.kt @@ -13,12 +13,21 @@ class ToolResultBlockParamTest { ToolResultBlockParam.builder() .toolUseId("tool_use_id") .type(ToolResultBlockParam.Type.TOOL_RESULT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .content(ToolResultBlockParam.Content.ofString("string")) .isError(true) .build() assertThat(toolResultBlockParam).isNotNull assertThat(toolResultBlockParam.toolUseId()).isEqualTo("tool_use_id") assertThat(toolResultBlockParam.type()).isEqualTo(ToolResultBlockParam.Type.TOOL_RESULT) + assertThat(toolResultBlockParam.cacheControl()) + .contains( + CacheControlEphemeral.builder().type(CacheControlEphemeral.Type.EPHEMERAL).build() + ) assertThat(toolResultBlockParam.content()) .contains(ToolResultBlockParam.Content.ofString("string")) assertThat(toolResultBlockParam.isError()).contains(true) diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolTest.kt index 55b41e3..74579a7 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolTest.kt @@ -36,6 +36,11 @@ class ToolTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() assertThat(tool).isNotNull @@ -64,6 +69,10 @@ class ToolTest { .build() ) assertThat(tool.name()).isEqualTo("x") + assertThat(tool.cacheControl()) + .contains( + CacheControlEphemeral.builder().type(CacheControlEphemeral.Type.EPHEMERAL).build() + ) assertThat(tool.description()).contains("Get the current weather in a given location") } } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolUseBlockParamTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolUseBlockParamTest.kt index 871227f..a8e0532 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolUseBlockParamTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/ToolUseBlockParamTest.kt @@ -16,11 +16,20 @@ class ToolUseBlockParamTest { .input(JsonValue.from(mapOf())) .name("x") .type(ToolUseBlockParam.Type.TOOL_USE) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() assertThat(toolUseBlockParam).isNotNull assertThat(toolUseBlockParam.id()).isEqualTo("id") assertThat(toolUseBlockParam._input()).isEqualTo(JsonValue.from(mapOf())) assertThat(toolUseBlockParam.name()).isEqualTo("x") assertThat(toolUseBlockParam.type()).isEqualTo(ToolUseBlockParam.Type.TOOL_USE) + assertThat(toolUseBlockParam.cacheControl()) + .contains( + CacheControlEphemeral.builder().type(CacheControlEphemeral.Type.EPHEMERAL).build() + ) } } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/models/UsageTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/models/UsageTest.kt index bcedd49..9d74fb8 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/models/UsageTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/models/UsageTest.kt @@ -9,8 +9,16 @@ class UsageTest { @Test fun createUsage() { - val usage = Usage.builder().inputTokens(2095L).outputTokens(503L).build() + val usage = + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() assertThat(usage).isNotNull + assertThat(usage.cacheCreationInputTokens()).contains(2051L) + assertThat(usage.cacheReadInputTokens()).contains(2051L) assertThat(usage.inputTokens()).isEqualTo(2095L) assertThat(usage.outputTokens()).isEqualTo(503L) } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/services/ErrorHandlingTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/services/ErrorHandlingTest.kt index 8732b2c..56dadf8 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/services/ErrorHandlingTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/services/ErrorHandlingTest.kt @@ -17,6 +17,7 @@ import com.anthropic.errors.RateLimitException import com.anthropic.errors.UnauthorizedException import com.anthropic.errors.UnexpectedStatusCodeException import com.anthropic.errors.UnprocessableEntityException +import com.anthropic.models.CacheControlEphemeral import com.anthropic.models.ContentBlock import com.anthropic.models.Message import com.anthropic.models.MessageCreateParams @@ -85,6 +86,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -125,6 +131,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -150,7 +161,14 @@ class ErrorHandlingTest { .role(Message.Role.ASSISTANT) .stopReason(Message.StopReason.END_TURN) .type(Message.Type.MESSAGE) - .usage(Usage.builder().inputTokens(2095L).outputTokens(503L).build()) + .usage( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) .build() stubFor(post(anyUrl()).willReturn(ok().withBody(toJson(expected)))) @@ -180,6 +198,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -220,6 +243,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -261,6 +289,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -301,6 +334,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -342,6 +380,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -382,6 +425,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -427,6 +475,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -467,6 +520,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -508,6 +566,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -548,6 +611,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -593,6 +661,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -633,6 +706,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -674,6 +752,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -714,6 +797,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -759,6 +847,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -799,6 +892,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -845,6 +943,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -885,6 +988,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -925,6 +1033,11 @@ class ErrorHandlingTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -965,6 +1078,11 @@ class ErrorHandlingTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/services/ServiceParamsTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/services/ServiceParamsTest.kt index 1eb8388..689a839 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/services/ServiceParamsTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/services/ServiceParamsTest.kt @@ -6,6 +6,7 @@ import com.anthropic.client.AnthropicClient import com.anthropic.client.okhttp.AnthropicOkHttpClient import com.anthropic.core.JsonValue import com.anthropic.core.jsonMapper +import com.anthropic.models.CacheControlEphemeral import com.anthropic.models.ContentBlock import com.anthropic.models.Message import com.anthropic.models.MessageCreateParams @@ -83,6 +84,11 @@ class ServiceParamsTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -123,6 +129,11 @@ class ServiceParamsTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -151,7 +162,14 @@ class ServiceParamsTest { .role(Message.Role.ASSISTANT) .stopReason(Message.StopReason.END_TURN) .type(Message.Type.MESSAGE) - .usage(Usage.builder().inputTokens(2095L).outputTokens(503L).build()) + .usage( + Usage.builder() + .cacheCreationInputTokens(2051L) + .cacheReadInputTokens(2051L) + .inputTokens(2095L) + .outputTokens(503L) + .build() + ) .build() stubFor( diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/MessageServiceTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/MessageServiceTest.kt index d6147d0..15c66a5 100644 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/MessageServiceTest.kt +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/MessageServiceTest.kt @@ -5,6 +5,8 @@ package com.anthropic.services.blocking import com.anthropic.TestServerExtension import com.anthropic.client.okhttp.AnthropicOkHttpClient import com.anthropic.core.JsonValue +import com.anthropic.models.CacheControlEphemeral +import com.anthropic.models.MessageCountTokensParams import com.anthropic.models.MessageCreateParams import com.anthropic.models.MessageParam import com.anthropic.models.Metadata @@ -50,6 +52,11 @@ class MessageServiceTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -90,6 +97,11 @@ class MessageServiceTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -134,6 +146,11 @@ class MessageServiceTest { TextBlockParam.builder() .text("Today's date is 2024-06-01.") .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .build() ) ) @@ -174,6 +191,11 @@ class MessageServiceTest { .build() ) .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) .description("Get the current weather in a given location") .build() ) @@ -190,4 +212,89 @@ class MessageServiceTest { } } } + + @Test + fun callCountTokens() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val messageService = client.messages() + val messageTokensCount = + messageService.countTokens( + MessageCountTokensParams.builder() + .messages( + listOf( + MessageParam.builder() + .content(MessageParam.Content.ofString("string")) + .role(MessageParam.Role.USER) + .build() + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .system( + MessageCountTokensParams.System.ofTextBlockParams( + listOf( + TextBlockParam.builder() + .text("Today's date is 2024-06-01.") + .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) + .build() + ) + ) + ) + .toolChoice( + ToolChoice.ofToolChoiceAuto( + ToolChoiceAuto.builder() + .type(ToolChoiceAuto.Type.AUTO) + .disableParallelToolUse(true) + .build() + ) + ) + .tools( + listOf( + Tool.builder() + .inputSchema( + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) + .properties( + JsonValue.from( + mapOf( + "location" to + mapOf( + "description" to + "The city and state, e.g. San Francisco, CA", + "type" to "string" + ), + "unit" to + mapOf( + "description" to + "Unit for the output - one of (celsius, fahrenheit)", + "type" to "string" + ) + ) + ) + ) + .build() + ) + .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type(CacheControlEphemeral.Type.EPHEMERAL) + .build() + ) + .description("Get the current weather in a given location") + .build() + ) + ) + .build() + ) + println(messageTokensCount) + messageTokensCount.validate() + } } diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/ModelServiceTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/ModelServiceTest.kt new file mode 100644 index 0000000..1d4e72a --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/ModelServiceTest.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.blocking + +import com.anthropic.TestServerExtension +import com.anthropic.client.okhttp.AnthropicOkHttpClient +import com.anthropic.models.ModelListParams +import com.anthropic.models.ModelRetrieveParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +class ModelServiceTest { + + @Test + fun callRetrieve() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val modelService = client.models() + val modelInfo = + modelService.retrieve(ModelRetrieveParams.builder().modelId("model_id").build()) + println(modelInfo) + modelInfo.validate() + } + + @Test + fun callList() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val modelService = client.models() + val listResponseModelResponse = modelService.list(ModelListParams.builder().build()) + println(listResponseModelResponse) + listResponseModelResponse.data().forEach { it.validate() } + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/beta/ModelServiceTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/beta/ModelServiceTest.kt new file mode 100644 index 0000000..70e60f7 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/beta/ModelServiceTest.kt @@ -0,0 +1,41 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.blocking.beta + +import com.anthropic.TestServerExtension +import com.anthropic.client.okhttp.AnthropicOkHttpClient +import com.anthropic.models.BetaModelListParams +import com.anthropic.models.BetaModelRetrieveParams +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +class ModelServiceTest { + + @Test + fun callRetrieve() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val modelService = client.beta().models() + val betaModelInfo = + modelService.retrieve(BetaModelRetrieveParams.builder().modelId("model_id").build()) + println(betaModelInfo) + betaModelInfo.validate() + } + + @Test + fun callList() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val modelService = client.beta().models() + val betaListResponseModelResponse = modelService.list(BetaModelListParams.builder().build()) + println(betaListResponseModelResponse) + betaListResponseModelResponse.data().forEach { it.validate() } + } +} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageServiceTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageServiceTest.kt deleted file mode 100644 index bc58d9b..0000000 --- a/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/beta/promptCaching/MessageServiceTest.kt +++ /dev/null @@ -1,225 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. - -package com.anthropic.services.blocking.beta.promptCaching - -import com.anthropic.TestServerExtension -import com.anthropic.client.okhttp.AnthropicOkHttpClient -import com.anthropic.core.JsonValue -import com.anthropic.models.AnthropicBeta -import com.anthropic.models.BetaPromptCachingMessageCreateParams -import com.anthropic.models.Metadata -import com.anthropic.models.Model -import com.anthropic.models.PromptCachingBetaCacheControlEphemeral -import com.anthropic.models.PromptCachingBetaMessageParam -import com.anthropic.models.PromptCachingBetaTextBlockParam -import com.anthropic.models.PromptCachingBetaTool -import com.anthropic.models.ToolChoice -import com.anthropic.models.ToolChoiceAuto -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith - -@ExtendWith(TestServerExtension::class) -class MessageServiceTest { - - @Test - fun callCreate() { - val client = - AnthropicOkHttpClient.builder() - .baseUrl(TestServerExtension.BASE_URL) - .apiKey("my-anthropic-api-key") - .build() - val messageService = client.beta().promptCaching().messages() - val promptCachingBetaMessage = - messageService.create( - BetaPromptCachingMessageCreateParams.builder() - .maxTokens(1024L) - .messages( - listOf( - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) - .build() - ) - ) - .model(Model.CLAUDE_3_5_HAIKU_LATEST) - .metadata( - Metadata.builder().userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b").build() - ) - .stopSequences(listOf("string")) - .system( - BetaPromptCachingMessageCreateParams.System - .ofPromptCachingBetaTextBlockParams( - listOf( - PromptCachingBetaTextBlockParam.builder() - .text("Today's date is 2024-06-01.") - .type(PromptCachingBetaTextBlockParam.Type.TEXT) - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type( - PromptCachingBetaCacheControlEphemeral.Type - .EPHEMERAL - ) - .build() - ) - .build() - ) - ) - ) - .temperature(1.0) - .toolChoice( - ToolChoice.ofToolChoiceAuto( - ToolChoiceAuto.builder() - .type(ToolChoiceAuto.Type.AUTO) - .disableParallelToolUse(true) - .build() - ) - ) - .tools( - listOf( - PromptCachingBetaTool.builder() - .inputSchema( - PromptCachingBetaTool.InputSchema.builder() - .type(PromptCachingBetaTool.InputSchema.Type.OBJECT) - .properties( - JsonValue.from( - mapOf( - "location" to - mapOf( - "description" to - "The city and state, e.g. San Francisco, CA", - "type" to "string" - ), - "unit" to - mapOf( - "description" to - "Unit for the output - one of (celsius, fahrenheit)", - "type" to "string" - ) - ) - ) - ) - .build() - ) - .name("x") - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - .description("Get the current weather in a given location") - .build() - ) - ) - .topK(5L) - .topP(0.7) - .betas(listOf(AnthropicBeta.MESSAGE_BATCHES_2024_09_24)) - .build() - ) - println(promptCachingBetaMessage) - promptCachingBetaMessage.validate() - } - - @Test - fun callCreateStreaming() { - val client = - AnthropicOkHttpClient.builder() - .baseUrl(TestServerExtension.BASE_URL) - .apiKey("my-anthropic-api-key") - .build() - val messageService = client.beta().promptCaching().messages() - - val promptCachingBetaMessageStream = - messageService.createStreaming( - BetaPromptCachingMessageCreateParams.builder() - .maxTokens(1024L) - .messages( - listOf( - PromptCachingBetaMessageParam.builder() - .content(PromptCachingBetaMessageParam.Content.ofString("string")) - .role(PromptCachingBetaMessageParam.Role.USER) - .build() - ) - ) - .model(Model.CLAUDE_3_5_HAIKU_LATEST) - .metadata( - Metadata.builder().userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b").build() - ) - .stopSequences(listOf("string")) - .system( - BetaPromptCachingMessageCreateParams.System - .ofPromptCachingBetaTextBlockParams( - listOf( - PromptCachingBetaTextBlockParam.builder() - .text("Today's date is 2024-06-01.") - .type(PromptCachingBetaTextBlockParam.Type.TEXT) - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type( - PromptCachingBetaCacheControlEphemeral.Type - .EPHEMERAL - ) - .build() - ) - .build() - ) - ) - ) - .temperature(1.0) - .toolChoice( - ToolChoice.ofToolChoiceAuto( - ToolChoiceAuto.builder() - .type(ToolChoiceAuto.Type.AUTO) - .disableParallelToolUse(true) - .build() - ) - ) - .tools( - listOf( - PromptCachingBetaTool.builder() - .inputSchema( - PromptCachingBetaTool.InputSchema.builder() - .type(PromptCachingBetaTool.InputSchema.Type.OBJECT) - .properties( - JsonValue.from( - mapOf( - "location" to - mapOf( - "description" to - "The city and state, e.g. San Francisco, CA", - "type" to "string" - ), - "unit" to - mapOf( - "description" to - "Unit for the output - one of (celsius, fahrenheit)", - "type" to "string" - ) - ) - ) - ) - .build() - ) - .name("x") - .cacheControl( - PromptCachingBetaCacheControlEphemeral.builder() - .type(PromptCachingBetaCacheControlEphemeral.Type.EPHEMERAL) - .build() - ) - .description("Get the current weather in a given location") - .build() - ) - ) - .topK(5L) - .topP(0.7) - .betas(listOf(AnthropicBeta.MESSAGE_BATCHES_2024_09_24)) - .build() - ) - - promptCachingBetaMessageStream.use { - promptCachingBetaMessageStream.stream().forEach { - println(it) - it.validate() - } - } - } -} diff --git a/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/messages/BatchServiceTest.kt b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/messages/BatchServiceTest.kt new file mode 100644 index 0000000..df36cc3 --- /dev/null +++ b/anthropic-java-core/src/test/kotlin/com/anthropic/services/blocking/messages/BatchServiceTest.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.anthropic.services.blocking.messages + +import com.anthropic.TestServerExtension +import com.anthropic.client.okhttp.AnthropicOkHttpClient +import com.anthropic.core.JsonValue +import com.anthropic.models.CacheControlEphemeral +import com.anthropic.models.MessageBatchCancelParams +import com.anthropic.models.MessageBatchCreateParams +import com.anthropic.models.MessageBatchListParams +import com.anthropic.models.MessageBatchRetrieveParams +import com.anthropic.models.MessageParam +import com.anthropic.models.Metadata +import com.anthropic.models.Model +import com.anthropic.models.TextBlockParam +import com.anthropic.models.Tool +import com.anthropic.models.ToolChoice +import com.anthropic.models.ToolChoiceAuto +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith + +@ExtendWith(TestServerExtension::class) +class BatchServiceTest { + + @Test + fun callCreate() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val batchService = client.messages().batches() + val messageBatch = + batchService.create( + MessageBatchCreateParams.builder() + .requests( + listOf( + MessageBatchCreateParams.Request.builder() + .customId("my-custom-id-1") + .params( + MessageBatchCreateParams.Request.Params.builder() + .maxTokens(1024L) + .messages( + listOf( + MessageParam.builder() + .content( + MessageParam.Content.ofString( + "Hello, world" + ) + ) + .role(MessageParam.Role.USER) + .build() + ) + ) + .model(Model.CLAUDE_3_5_HAIKU_LATEST) + .metadata( + Metadata.builder() + .userId("13803d75-b4b5-4c3e-b2a2-6f21399b021b") + .build() + ) + .stopSequences(listOf("string")) + .stream(true) + .system( + MessageBatchCreateParams.Request.Params.System + .ofTextBlockParams( + listOf( + TextBlockParam.builder() + .text("Today's date is 2024-06-01.") + .type(TextBlockParam.Type.TEXT) + .cacheControl( + CacheControlEphemeral.builder() + .type( + CacheControlEphemeral.Type + .EPHEMERAL + ) + .build() + ) + .build() + ) + ) + ) + .temperature(1.0) + .toolChoice( + ToolChoice.ofToolChoiceAuto( + ToolChoiceAuto.builder() + .type(ToolChoiceAuto.Type.AUTO) + .disableParallelToolUse(true) + .build() + ) + ) + .tools( + listOf( + Tool.builder() + .inputSchema( + Tool.InputSchema.builder() + .type(Tool.InputSchema.Type.OBJECT) + .properties( + JsonValue.from( + mapOf( + "location" to + mapOf( + "description" to + "The city and state, e.g. San Francisco, CA", + "type" to "string" + ), + "unit" to + mapOf( + "description" to + "Unit for the output - one of (celsius, fahrenheit)", + "type" to "string" + ) + ) + ) + ) + .build() + ) + .name("x") + .cacheControl( + CacheControlEphemeral.builder() + .type( + CacheControlEphemeral.Type.EPHEMERAL + ) + .build() + ) + .description( + "Get the current weather in a given location" + ) + .build() + ) + ) + .topK(5L) + .topP(0.7) + .build() + ) + .build() + ) + ) + .build() + ) + println(messageBatch) + messageBatch.validate() + } + + @Test + fun callRetrieve() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val batchService = client.messages().batches() + val messageBatch = + batchService.retrieve( + MessageBatchRetrieveParams.builder().messageBatchId("message_batch_id").build() + ) + println(messageBatch) + messageBatch.validate() + } + + @Test + fun callList() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val batchService = client.messages().batches() + val listResponseMessageBatch = batchService.list(MessageBatchListParams.builder().build()) + println(listResponseMessageBatch) + listResponseMessageBatch.data().forEach { it.validate() } + } + + @Test + fun callCancel() { + val client = + AnthropicOkHttpClient.builder() + .baseUrl(TestServerExtension.BASE_URL) + .apiKey("my-anthropic-api-key") + .build() + val batchService = client.messages().batches() + val messageBatch = + batchService.cancel( + MessageBatchCancelParams.builder().messageBatchId("message_batch_id").build() + ) + println(messageBatch) + messageBatch.validate() + } +}