in anthropic-java-bedrock/src/main/kotlin/com/anthropic/bedrock/backends/BedrockBackend.kt [126:190]
override fun prepareRequest(request: HttpRequest): HttpRequest {
val pathSegments = request.pathSegments
if (pathSegments.isEmpty()) {
throw AnthropicInvalidDataException("Request missing all path segments.")
}
require(pathSegments[0] != "model") { "Request already prepared for Bedrock." }
if (pathSegments[0] != "v1") {
throw AnthropicInvalidDataException("Expected first 'v1' path segment.")
}
if (pathSegments.size <= 1) {
throw AnthropicInvalidDataException("Missing service name from request URL.")
}
when (pathSegments[1]) {
"messages" -> {
if (pathSegments.size > 2) {
when (pathSegments[2]) {
"batches" ->
throw AnthropicException("Batch API is not supported for Bedrock.")
"count_tokens" ->
throw AnthropicException("Token counting is not supported for Bedrock.")
} // For now, ignore any other path segments.
}
}
"complete" -> {
// Do nothing special.
}
else ->
throw AnthropicException(
"Service is not supported for Bedrock: ${pathSegments[1]}."
)
}
val jsonBody: ObjectNode =
bodyToJson(jsonMapper, request.body)
?: throw AnthropicInvalidDataException("Request has no body")
jsonBody.put("anthropic_version", ANTHROPIC_VERSION)
val betaVersions =
request.headers.values(HEADER_ANTHROPIC_BETA).flatMap { it.split(",") }.distinct()
if (betaVersions.isNotEmpty()) {
jsonBody.replace("anthropic_beta", jsonMapper.valueToTree(betaVersions))
}
val model =
jsonBody.remove("model")
?: throw AnthropicInvalidDataException("No model found in body.")
val modelId = model.asText()
// For Bedrock, the "stream" property must be removed from the body.
// This differs from Vertex where the property is retained.
val isStream = jsonBody.remove("stream")?.asBoolean() ?: false
return request
.toBuilder()
.replaceAllPathSegments("model", modelId)
.addPathSegment(if (isStream) "invoke-with-response-stream" else "invoke")
.body(json(jsonMapper, jsonBody))
.build()
}