From 30db535f2ec2299ce662e637ed145ada08ef5254 Mon Sep 17 00:00:00 2001 From: Niels Kootstra <545768+nkootstra@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:02:41 +0100 Subject: [PATCH] feat(bedrock): list and get foundation models and system-defined inference profiles (#7675) * feat(bedrock): list and get foundation models and system-defined inference profiles fix(bedrock): resolve only ARNs that name the catalog resource in the calling Region, and report on-demand inference only where a model is served in-Region fix(bedrock): accept SPEECH and VIDEO output modalities and refuse an unserved model with ValidationException fix(bedrock): report enum violations and read the model catalog through the shared helpers An invalid ListFoundationModels or ListInferenceProfiles enum value now answers with the "1 validation error detected:" prefix AWS sends and lists the allowed values in the model's order. * fix(bedrock): answer an unresolvable model or profile identifier with the error AWS returns GetFoundationModel answers an unknown model id or an ARN that names no foundation model in the calling Region with ValidationException. GetInferenceProfile answers an ARN of another service or without an account with ValidationException, and one of another account with AccessDeniedException; one of another Region stays ResourceNotFoundException. --- README.md | 2 +- docs/services/bedrock.md | 59 +++- docs/services/index.md | 2 +- .../services/bedrock/BedrockController.java | 99 ++++++ .../services/bedrock/BedrockModelCatalog.java | 116 +++++++ .../aws/services/bedrock/BedrockService.java | 133 ++++++++ src/main/resources/application.yml | 4 +- src/main/resources/bedrock/model-catalog.yaml | 141 ++++++++ .../BedrockModelCatalogIntegrationTest.java | 301 ++++++++++++++++++ 9 files changed, 849 insertions(+), 8 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/bedrock/BedrockModelCatalog.java create mode 100644 src/main/resources/bedrock/model-catalog.yaml create mode 100644 src/test/java/io/floci/aws/services/bedrock/BedrockModelCatalogIntegrationTest.java diff --git a/README.md b/README.md index f447e0a05b..7f08070c3b 100644 --- a/README.md +++ b/README.md @@ -366,7 +366,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | OpenSearch | Real Docker | Domain CRUD, tags, versions, instance types, upgrade stubs | | AppConfig | In-process | Applications, environments, profiles, hosted versions, deployments | | AppConfigData | In-process | Configuration sessions and dynamic configuration retrieval | -| Bedrock | In-process | Guardrail lifecycle, versions, and tags on the control plane | +| Bedrock | In-process | Guardrail lifecycle, versions, and tags, plus a seeded foundation model and inference profile catalog, on the control plane | | Bedrock Runtime | In-process stub | Dummy Converse and InvokeModel responses for local development | | Bedrock AgentCore | In-process stub | Stateful control plane (agent runtimes, gateways, memory, workload identity); canned InvokeAgentRuntime responses | | EKS | Real Docker, mock mode available | k3s clusters with live Kubernetes API server | diff --git a/docs/services/bedrock.md b/docs/services/bedrock.md index b1f2bb1fa6..b5254714d5 100644 --- a/docs/services/bedrock.md +++ b/docs/services/bedrock.md @@ -1,7 +1,7 @@ # Amazon Bedrock (control plane) **Protocol:** REST-JSON -**Endpoint:** `http://localhost:4566/guardrails` (SigV4 service `bedrock`) +**Endpoint:** `http://localhost:4566/guardrails`, `/foundation-models`, `/inference-profiles` (SigV4 service `bedrock`) This page covers the Bedrock control plane. Model invocation is a separate service that shares the same signing name: see [Bedrock Runtime](bedrock-runtime.md). @@ -17,6 +17,10 @@ that shares the same signing name: see [Bedrock Runtime](bedrock-runtime.md). | `CreateGuardrailVersion` | Snapshot the `DRAFT` under the next numerical version | | `DeleteGuardrail` | Delete one numerical version, or the guardrail and all its versions | | `ListGuardrails` | List every guardrail's `DRAFT`, or every version of one guardrail | +| `ListFoundationModels` | List the catalog's foundation models served in the calling Region, filtered by provider and output modality | +| `GetFoundationModel` | Read one foundation model by id or ARN | +| `ListInferenceProfiles` | List the system-defined inference profiles the calling Region can use, with `type`, `maxResults` and `nextToken` | +| `GetInferenceProfile` | Read one system-defined inference profile by id or ARN, with its destination Regions | | `PutResourcePolicy` | Attach a resource-based policy to a guardrail or a guardrail profile (`POST /resource-policy`) | | `GetResourcePolicy` | Read the resource-based policy of a guardrail or a guardrail profile | | `DeleteResourcePolicy` | Remove the resource-based policy of a guardrail or a guardrail profile | @@ -102,18 +106,57 @@ Guardrails are listed by the Resource Groups Tagging API (resource type `bedrock and Resource Explorer with their own tags, and `TagResources` / `UntagResources` there change those tags, as `TagResource` and `UntagResource` do. +## Foundation models and inference profiles + +`ListFoundationModels`, `GetFoundationModel`, `ListInferenceProfiles` and +`GetInferenceProfile` read a fixed catalog, `bedrock/model-catalog.yaml`. It is a seed +rather than a mirror of AWS: a few real models (Amazon Nova Micro and Nova Lite, Titan Text +Embeddings V2, Llama 3.1 8B Instruct and Claude Sonnet 4.5) with the modalities, streaming +support, lifecycle status and Regional availability their +[model cards](https://docs.aws.amazon.com/bedrock/latest/userguide/model-cards.html) publish, +and their US and EU system-defined inference profiles. + +The answers depend on the calling Region, as on AWS: + +- A model is listed when its card shows it served in that Region, or when one of its + inference profiles can be called from it. `GetFoundationModel` answers a catalog model + the Region does not serve, an unknown model id, and an ARN that does not name a + foundation model in the calling Region and partition with `ValidationException`, as AWS + does. +- `byOutputModality` accepts `SPEECH` and `VIDEO` as well as the published `TEXT`, + `IMAGE` and `EMBEDDING`, as AWS does. No catalog model produces speech or video, so + those filters return an empty list. +- An inference profile is listed only in its source Regions, and its `models` are the + foundation models in the destination Regions the card gives for the calling Region, so + `us.amazon.nova-lite-v1:0` called from `us-west-1` routes to four Regions and from + `us-east-1` to three. `GetInferenceProfile` on a profile the Region cannot use returns + `ResourceNotFoundException`. +- `inferenceTypesSupported` is `ON_DEMAND` only where the model is served in the Region + itself, and empty where it is reachable only through an inference profile, so + `byInferenceType=ON_DEMAND` leaves those out. +- `modelArn` is `arn::bedrock:::foundation-model/`, and + `inferenceProfileArn` carries the calling Region and account. `GetInferenceProfile` + answers an ARN of another service or without an account with `ValidationException`, + one of another account with `AccessDeniedException`, and one of another Region, + partition or resource type with `ResourceNotFoundException`. +- The error codes and statuses follow AWS; the message text is Floci's own. + +Deviations: models that are not in the catalog are not listed, provisioned throughput is +never reported, and `customizationsSupported` is always empty, so `byCustomizationType` +and `byInferenceType=PROVISIONED` return no models. Application inference profiles cannot +be created yet, so `type=APPLICATION` returns an empty list. `ListInferenceProfiles` pages +up to 1000 profiles; `maxResults` outside 1 to 1000 is rejected with `ValidationException`. + ## Not implemented The rest of the Bedrock control plane is absent rather than stubbed, because emulating it faithfully would require behaviour Floci has no way to model: -- `ListFoundationModels` and `GetFoundationModel`. The AWS service model carries no - enumeration of foundation model ids, so any catalogue would be invented data. - Custom model, model customization, model import and distillation jobs. These depend on real training runs. - Model evaluation and evaluation jobs. These depend on real inference. -- Provisioned throughput, inference profiles and prompt routers. These describe real - capacity reservations and routing. +- Provisioned throughput, application inference profiles and prompt routers. These + describe real capacity reservations and routing. - Model invocation logging, batch inference and async invoke. These are data-plane operations backed by real model execution. @@ -152,4 +195,10 @@ aws bedrock get-resource-policy \ --resource-arn arn:aws:bedrock:us-east-1:000000000000:guardrail/abc123def456 aws bedrock delete-guardrail --guardrail-identifier abc123def456 + +aws bedrock list-foundation-models --by-output-modality EMBEDDING + +aws bedrock list-inference-profiles --type-equals SYSTEM_DEFINED + +aws bedrock get-inference-profile --inference-profile-identifier us.amazon.nova-lite-v1:0 ``` diff --git a/docs/services/index.md b/docs/services/index.md index aaf2d3acc2..4212a97a22 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -101,7 +101,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AppConfig](appconfig.md) | `/applications/...`, `/deploymentstrategies/...` | REST JSON | 16 | | [AppConfigData](appconfig.md#data-plane) | `/configurationsessions`, `/configuration` | REST JSON | 2 | | [AppSync](appsync.md) | `/v1/apis/...` | REST JSON | 33 | -| [Amazon Bedrock](bedrock.md) | `/guardrails`, `/guardrails/{guardrailIdentifier}`, `/resource-policy`, `/resource-policy/{resourceArn}`, `/tagResource`, `/untagResource`, `/listTagsForResource` | REST JSON | 12 | +| [Amazon Bedrock](bedrock.md) | `/guardrails`, `/guardrails/{guardrailIdentifier}`, `/foundation-models`, `/foundation-models/{modelIdentifier}`, `/inference-profiles`, `/inference-profiles/{inferenceProfileIdentifier}`, `/resource-policy`, `/resource-policy/{resourceArn}`, `/tagResource`, `/untagResource`, `/listTagsForResource` | REST JSON | 16 | | [Bedrock Runtime](bedrock-runtime.md) | `/model/{modelId}/converse`, `/model/{modelId}/invoke` | REST JSON | 2 (stub; streaming returns 501) | | [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/browsers*`, `/browser-profiles*`, `/code-interpreters*`, `/harnesses*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 71 (+ 3 tagging via shared `/tags/{arn}` route) | | [Bedrock AgentCore](bedrock-agentcore.md#data-plane-invokeagentruntime) | `/runtimes/{agentRuntimeArn}/invocations` | REST JSON (binary payload) | 1 (canned-response stub) | diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockController.java b/src/main/java/io/floci/aws/services/bedrock/BedrockController.java index 726654766d..3aa3d6e30b 100644 --- a/src/main/java/io/floci/aws/services/bedrock/BedrockController.java +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockController.java @@ -142,6 +142,66 @@ public class BedrockController { return Response.ok(response).build(); } + // Foundation models and inference profiles + + @GET + @Path("/foundation-models") + public Response listFoundationModels(@QueryParam("byProvider") String byProvider, + @QueryParam("byOutputModality") String byOutputModality, + @QueryParam("byInferenceType") String byInferenceType, + @QueryParam("byCustomizationType") String byCustomizationType, + @Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode summaries = response.putArray("modelSummaries"); + for (BedrockModelCatalog.FoundationModel model : bedrockService.listFoundationModels(byProvider, + byOutputModality, byInferenceType, byCustomizationType, region)) { + summaries.add(foundationModelNode(model, region)); + } + return Response.ok(response).build(); + } + + @GET + @Path("/foundation-models/{modelIdentifier: .+}") + public Response getFoundationModel(@PathParam("modelIdentifier") String modelIdentifier, + @Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode response = objectMapper.createObjectNode(); + response.set("modelDetails", foundationModelNode(bedrockService.getFoundationModel(modelIdentifier, region), + region)); + return Response.ok(response).build(); + } + + @GET + @Path("/inference-profiles") + public Response listInferenceProfiles(@QueryParam("type") String typeEquals, + @QueryParam("maxResults") String maxResults, + @QueryParam("nextToken") String nextToken, + @Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + PaginatedResult page = bedrockService.listInferenceProfiles(typeEquals, + Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken, region); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode summaries = response.putArray("inferenceProfileSummaries"); + for (BedrockModelCatalog.InferenceProfile profile : page.items()) { + summaries.add(inferenceProfileNode(profile, region)); + } + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + @GET + @Path("/inference-profiles/{inferenceProfileIdentifier: .+}") + public Response getInferenceProfile(@PathParam("inferenceProfileIdentifier") String inferenceProfileIdentifier, + @Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(inferenceProfileNode( + bedrockService.getInferenceProfile(inferenceProfileIdentifier, region), region)).build(); + } + // Resource policies @POST @@ -250,6 +310,45 @@ public class BedrockController { return node; } + private ObjectNode foundationModelNode(BedrockModelCatalog.FoundationModel model, String region) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("modelArn", foundationModelArn(model.modelId(), region)); + node.put("modelId", model.modelId()); + node.put("modelName", model.modelName()); + node.put("providerName", model.providerName()); + model.inputModalities().forEach(node.putArray("inputModalities")::add); + model.outputModalities().forEach(node.putArray("outputModalities")::add); + node.put("responseStreamingSupported", model.responseStreamingSupported()); + node.putArray("customizationsSupported"); + ArrayNode inferenceTypes = node.putArray("inferenceTypesSupported"); + if (model.servedInRegion(region)) { + inferenceTypes.add("ON_DEMAND"); + } + node.putObject("modelLifecycle").put("status", model.lifecycleStatus()); + return node; + } + + private ObjectNode inferenceProfileNode(BedrockModelCatalog.InferenceProfile profile, String region) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("inferenceProfileName", profile.inferenceProfileName()); + node.put("inferenceProfileArn", regionResolver.buildArn("bedrock", region, + "inference-profile/" + profile.inferenceProfileId())); + node.put("inferenceProfileId", profile.inferenceProfileId()); + node.put("createdAt", iso8601(profile.createdAt())); + node.put("updatedAt", iso8601(profile.createdAt())); + ArrayNode models = node.putArray("models"); + for (String destination : profile.routes().get(region)) { + models.addObject().put("modelArn", foundationModelArn(profile.modelId(), destination)); + } + node.put("status", "ACTIVE"); + node.put("type", "SYSTEM_DEFINED"); + return node; + } + + private String foundationModelArn(String modelId, String region) { + return regionResolver.buildArn("bedrock", region, "", "foundation-model/" + modelId); + } + private ObjectNode guardrailSummaryNode(Guardrail guardrail) { ObjectNode node = objectMapper.createObjectNode(); node.put("id", guardrail.getGuardrailId()); diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockModelCatalog.java b/src/main/java/io/floci/aws/services/bedrock/BedrockModelCatalog.java new file mode 100644 index 0000000000..61c4b411aa --- /dev/null +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockModelCatalog.java @@ -0,0 +1,116 @@ +package io.floci.aws.services.bedrock; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.floci.aws.core.common.VendoredResources; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * The foundation models and system-defined inference profiles Bedrock lists, read once from + * {@code bedrock/model-catalog.yaml}. + * + *

The YAML is read through a constant, which Quarkus's native resource analysis cannot follow, + * so it is registered under {@code quarkus.native.resources.includes} in {@code application.yml}. + */ +final class BedrockModelCatalog { + + private static final String CATALOG_RESOURCE_NAME = "bedrock/model-catalog.yaml"; + + record FoundationModel(String modelId, String modelName, String providerName, List inputModalities, + List outputModalities, boolean responseStreamingSupported, + String lifecycleStatus, Set inRegion) { + + /** Whether the model is invoked on demand in the Region itself, rather than only through a profile. */ + boolean servedInRegion(String region) { + return inRegion.contains(region); + } + } + + /** + * @param routes the destination Regions each source Region routes to, in the order the model + * card lists them + */ + record InferenceProfile(String inferenceProfileId, String inferenceProfileName, String modelId, + Instant createdAt, Map> routes) { + } + + static final List MODELS; + static final List PROFILES; + + static { + Catalog catalog = load(); + MODELS = catalog.foundationModels.stream() + .map(entry -> new FoundationModel(entry.modelId, entry.modelName, entry.providerName, + List.copyOf(entry.inputModalities), List.copyOf(entry.outputModalities), + entry.responseStreamingSupported, entry.lifecycleStatus, Set.copyOf(entry.inRegion))) + .toList(); + PROFILES = catalog.inferenceProfiles.stream() + .map(entry -> new InferenceProfile(entry.inferenceProfileId, entry.inferenceProfileName, + entry.modelId, Instant.parse(entry.createdAt), copyRoutes(entry.routes))) + .toList(); + } + + private BedrockModelCatalog() { + } + + /** The models callable from a Region, in their own Region or through one of their profiles. */ + static List modelsIn(String region) { + return MODELS.stream() + .filter(model -> model.servedInRegion(region) || PROFILES.stream() + .anyMatch(profile -> profile.modelId().equals(model.modelId()) + && profile.routes().containsKey(region))) + .toList(); + } + + /** The profiles a Region is a source Region of. */ + static List profilesFrom(String region) { + return PROFILES.stream().filter(profile -> profile.routes().containsKey(region)).toList(); + } + + private static Map> copyRoutes(Map> routes) { + return routes.entrySet().stream() + .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, entry -> List.copyOf(entry.getValue()))); + } + + private static Catalog load() { + return VendoredResources.read(CATALOG_RESOURCE_NAME, "Bedrock model catalog", + in -> new ObjectMapper(new YAMLFactory()).readValue(in, Catalog.class)); + } + + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + static final class Catalog { + public List foundationModels = List.of(); + public List inferenceProfiles = List.of(); + } + + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + static final class ModelEntry { + public String modelId; + public String modelName; + public String providerName; + public List inputModalities = List.of(); + public List outputModalities = List.of(); + public boolean responseStreamingSupported; + public String lifecycleStatus; + public List inRegion = List.of(); + } + + @RegisterForReflection + @JsonIgnoreProperties(ignoreUnknown = true) + static final class ProfileEntry { + public String inferenceProfileId; + public String inferenceProfileName; + public String modelId; + public String createdAt; + public Map> routes = Map.of(); + } +} diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockService.java b/src/main/java/io/floci/aws/services/bedrock/BedrockService.java index d69c8514a9..7638480129 100644 --- a/src/main/java/io/floci/aws/services/bedrock/BedrockService.java +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockService.java @@ -11,6 +11,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.SmithyValidationErrors; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; @@ -30,6 +31,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; @@ -66,6 +68,13 @@ public class BedrockService implements ResourceProvider { /** {@code MaxResults} on {@code ListGuardrails} is capped at 1000 by the AWS model. */ private static final int MAX_PAGE = 1000; + // Wider than the published ModelModality enum: AWS also accepts SPEECH and VIDEO here. + private static final List OUTPUT_MODALITIES = List.of("TEXT", "IMAGE", "EMBEDDING", "SPEECH", "VIDEO"); + private static final List INFERENCE_TYPES = List.of("ON_DEMAND", "PROVISIONED"); + private static final List CUSTOMIZATION_TYPES = List.of("FINE_TUNING", "CONTINUED_PRE_TRAINING", "DISTILLATION"); + private static final String FOUNDATION_MODEL_PREFIX = "foundation-model/"; + private static final String INFERENCE_PROFILE_PREFIX = "inference-profile/"; + private static final List INFERENCE_PROFILE_TYPES = List.of("SYSTEM_DEFINED", "APPLICATION"); /** {@code TagList} from the AWS model: at most 200 items on one request. */ private static final int TAG_LIST_MAX = 200; @@ -265,6 +274,130 @@ public class BedrockService implements ResourceProvider { MAX_PAGE, "ValidationException"); } + // Foundation models and inference profiles + + public List listFoundationModels(String byProvider, String byOutputModality, + String byInferenceType, + String byCustomizationType, String region) { + requireOneOf("byOutputModality", byOutputModality, OUTPUT_MODALITIES); + requireOneOf("byInferenceType", byInferenceType, INFERENCE_TYPES); + requireOneOf("byCustomizationType", byCustomizationType, CUSTOMIZATION_TYPES); + if (byCustomizationType != null || "PROVISIONED".equals(byInferenceType)) { + // The catalog holds no customization or provisioned-throughput support. + return List.of(); + } + return BedrockModelCatalog.modelsIn(region).stream() + .filter(model -> byProvider == null || model.providerName().equalsIgnoreCase(byProvider)) + .filter(model -> byOutputModality == null || model.outputModalities().contains(byOutputModality)) + .filter(model -> byInferenceType == null || model.servedInRegion(region)) + .toList(); + } + + public BedrockModelCatalog.FoundationModel getFoundationModel(String modelIdentifier, String region) { + String modelId = foundationModelIdOf(modelIdentifier, region); + Optional served = BedrockModelCatalog.modelsIn(region).stream() + .filter(model -> model.modelId().equals(modelId)) + .findFirst(); + if (served.isPresent()) { + return served.get(); + } + if (BedrockModelCatalog.MODELS.stream().anyMatch(model -> model.modelId().equals(modelId))) { + throw new AwsException("ValidationException", + "The provided model identifier is not valid in this Region.", 400); + } + throw invalidModelIdentifier(); + } + + public PaginatedResult listInferenceProfiles(String typeEquals, + Integer maxResults, + String nextToken, String region) { + requireOneOf("typeEquals", typeEquals, INFERENCE_PROFILE_TYPES); + // Only system-defined profiles exist: application inference profiles cannot be created yet. + List profiles = "APPLICATION".equals(typeEquals) + ? List.of() + : BedrockModelCatalog.profilesFrom(region); + return Pagination.paginate(profiles, BedrockModelCatalog.InferenceProfile::inferenceProfileId, + maxResults, nextToken, MAX_PAGE, "ValidationException"); + } + + public BedrockModelCatalog.InferenceProfile getInferenceProfile(String inferenceProfileIdentifier, String region) { + String profileId = inferenceProfileIdOf(inferenceProfileIdentifier, region); + return BedrockModelCatalog.profilesFrom(region).stream() + .filter(profile -> profile.inferenceProfileId().equals(profileId)) + .findFirst() + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "The inference profile " + inferenceProfileIdentifier + " was not found.", 404)); + } + + /** + * The model id an identifier names. AWS answers every identifier it cannot resolve to a model, + * an unknown id or an ARN of another Region, service or account, with a validation error. + */ + private String foundationModelIdOf(String identifier, String region) { + AwsArnUtils.Arn arn = arnOf(identifier); + if (arn == null) { + return identifier; + } + if (!isBedrockArnIn(arn, region) || !arn.accountId().isEmpty() + || !arn.resource().startsWith(FOUNDATION_MODEL_PREFIX)) { + throw invalidModelIdentifier(); + } + return arn.resource().substring(FOUNDATION_MODEL_PREFIX.length()); + } + + /** + * The profile id an identifier names. As AWS does, an ARN of another service or without an + * account is invalid, one of another account is denied, and one of another Region names nothing. + */ + private String inferenceProfileIdOf(String identifier, String region) { + AwsArnUtils.Arn arn = arnOf(identifier); + if (arn == null) { + return identifier; + } + if (!"bedrock".equals(arn.service()) || arn.accountId().isEmpty()) { + throw new AwsException("ValidationException", + "The provided inference profile identifier " + identifier + " is invalid.", 400); + } + if (!arn.accountId().equals(regionResolver.getAccountId())) { + throw new AwsException("AccessDeniedException", + "You don't have access to the inference profile " + identifier + ".", 403); + } + if (!isBedrockArnIn(arn, region) || !arn.resource().startsWith(INFERENCE_PROFILE_PREFIX)) { + throw new AwsException("ResourceNotFoundException", "Resource " + identifier + " does not exist.", 404); + } + return arn.resource().substring(INFERENCE_PROFILE_PREFIX.length()); + } + + /** The ARN an identifier is, or {@code null} for a plain id. */ + private static AwsArnUtils.Arn arnOf(String identifier) { + if (identifier == null || identifier.isBlank()) { + throw new AwsException("ValidationException", "The identifier is required.", 400); + } + if (!AwsArnUtils.looksLikeArn(identifier)) { + return null; + } + try { + return AwsArnUtils.parse(identifier); + } catch (IllegalArgumentException e) { + throw new AwsException("ValidationException", "The identifier " + identifier + " is not a valid ARN.", 400); + } + } + + private boolean isBedrockArnIn(AwsArnUtils.Arn arn, String region) { + return "bedrock".equals(arn.service()) && region.equals(arn.region()) + && regionResolver.partitionForRegion(region).equals(arn.partition()); + } + + private static AwsException invalidModelIdentifier() { + return new AwsException("ValidationException", "The provided model identifier is invalid.", 400); + } + + private static void requireOneOf(String parameter, String value, List allowed) { + if (value != null && !allowed.contains(value)) { + throw SmithyValidationErrors.validationException(SmithyValidationErrors.notInEnum(value, parameter, allowed)); + } + } + public Guardrail createGuardrailVersion(String identifier, String description, String region) { Guardrail draft = getGuardrail(identifier, DRAFT_VERSION, region); String guardrailId = draft.getGuardrailId(); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 0c2db84297..d7d1904997 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -64,7 +64,8 @@ quarkus: # The Pricing service reads its bundled snapshot, EC2 reads its image # catalog (ec2/image-catalog.yaml), SageMaker reads its instance type # catalog (sagemaker/instance-type-catalog.yaml), KMS reads its AWS managed - # key catalog (kms/aws-managed-keys.yaml), AppSync's GraphQL + # key catalog (kms/aws-managed-keys.yaml), Bedrock reads its model catalog + # (bedrock/model-catalog.yaml), AppSync's GraphQL # parser reads its message bundles, Lambda Web Functions copy their # runtime (lambdaweb/index.mjs) into each environment, EMR writes its S3DistCp program # (emr/s3-dist-cp.py) into a step's container, EC2 security group enforcement builds @@ -88,6 +89,7 @@ quarkus: - docker/*.Dockerfile - sagemaker/*.yaml - kms/*.yaml + - bedrock/*.yaml - eks/*.json - aws/*.json - iam/service-linked-roles.tsv diff --git a/src/main/resources/bedrock/model-catalog.yaml b/src/main/resources/bedrock/model-catalog.yaml new file mode 100644 index 0000000000..588ddd977a --- /dev/null +++ b/src/main/resources/bedrock/model-catalog.yaml @@ -0,0 +1,141 @@ +# Amazon Bedrock foundation models and system-defined (cross-Region) inference profiles. +# +# Served by ListFoundationModels, GetFoundationModel, ListInferenceProfiles and +# GetInferenceProfile. This is a seed, not a mirror of AWS: it holds a few real models with the +# attributes and Regional availability their model cards publish +# (https://docs.aws.amazon.com/bedrock/latest/userguide/model-cards.html). Add a model by copying +# its card; do not invent values a card does not show. +# +# A model is listed in a Region when the card shows it In-Region there (inRegion) or when one of +# its inference profiles can be called from that Region. A profile is listed in a Region only +# when that Region is one of its source Regions, and its models are the foundation models in the +# destination Regions the card gives for that source Region. Commercial Regions only. + +foundationModels: + - modelId: amazon.nova-micro-v1:0 + modelName: Nova Micro + providerName: Amazon + inputModalities: [TEXT] + outputModalities: [TEXT] + responseStreamingSupported: true + lifecycleStatus: ACTIVE + inRegion: [us-east-1, eu-west-2, ap-southeast-2] + + - modelId: amazon.nova-lite-v1:0 + modelName: Nova Lite + providerName: Amazon + inputModalities: [TEXT, IMAGE] + outputModalities: [TEXT] + responseStreamingSupported: true + lifecycleStatus: ACTIVE + inRegion: [us-east-1, us-east-2, us-west-2, eu-north-1, eu-west-2, ap-northeast-1, ap-southeast-2, + ap-southeast-3, me-central-1] + + - modelId: amazon.titan-embed-text-v2:0 + modelName: Titan Text Embeddings V2 + providerName: Amazon + inputModalities: [TEXT] + outputModalities: [EMBEDDING] + responseStreamingSupported: false + lifecycleStatus: ACTIVE + inRegion: [us-east-1, us-east-2, us-west-2, ca-central-1, eu-central-1, eu-central-2, eu-north-1, + eu-south-1, eu-south-2, eu-west-1, eu-west-2, eu-west-3, ap-northeast-1, ap-northeast-2, + ap-northeast-3, ap-south-1, ap-south-2, ap-southeast-2, sa-east-1] + + - modelId: meta.llama3-1-8b-instruct-v1:0 + modelName: Llama 3.1 8B Instruct + providerName: Meta + inputModalities: [TEXT] + outputModalities: [TEXT] + responseStreamingSupported: true + lifecycleStatus: LEGACY + inRegion: [us-west-2] + + - modelId: anthropic.claude-sonnet-4-5-20250929-v1:0 + modelName: Claude Sonnet 4.5 + providerName: Anthropic + inputModalities: [TEXT, IMAGE] + outputModalities: [TEXT] + responseStreamingSupported: true + lifecycleStatus: LEGACY + inRegion: [] + +inferenceProfiles: + - inferenceProfileId: us.amazon.nova-micro-v1:0 + inferenceProfileName: US Nova Micro + modelId: amazon.nova-micro-v1:0 + createdAt: 2024-12-05T00:00:00Z + routes: + us-east-1: [us-east-1, us-east-2, us-west-2] + us-east-2: [us-east-1, us-east-2, us-west-2] + us-west-2: [us-east-1, us-east-2, us-west-2] + + - inferenceProfileId: eu.amazon.nova-micro-v1:0 + inferenceProfileName: EU Nova Micro + modelId: amazon.nova-micro-v1:0 + createdAt: 2024-12-05T00:00:00Z + routes: + eu-central-1: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + eu-north-1: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + eu-south-1: [eu-central-1, eu-north-1, eu-south-1, eu-west-1, eu-west-3] + eu-south-2: [eu-central-1, eu-north-1, eu-south-2, eu-west-1, eu-west-3] + eu-west-1: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + eu-west-3: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + il-central-1: [eu-central-1, eu-north-1, eu-south-1, eu-west-1, eu-west-3, il-central-1] + + - inferenceProfileId: us.amazon.nova-lite-v1:0 + inferenceProfileName: US Nova Lite + modelId: amazon.nova-lite-v1:0 + createdAt: 2024-12-05T00:00:00Z + routes: + us-east-1: [us-east-1, us-east-2, us-west-2] + us-east-2: [us-east-1, us-east-2, us-west-2] + us-west-1: [us-east-1, us-east-2, us-west-1, us-west-2] + us-west-2: [us-east-1, us-east-2, us-west-2] + + - inferenceProfileId: eu.amazon.nova-lite-v1:0 + inferenceProfileName: EU Nova Lite + modelId: amazon.nova-lite-v1:0 + createdAt: 2024-12-05T00:00:00Z + routes: + eu-central-1: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + eu-north-1: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + eu-south-1: [eu-central-1, eu-north-1, eu-south-1, eu-west-1, eu-west-3] + eu-south-2: [eu-central-1, eu-north-1, eu-south-2, eu-west-1, eu-west-3] + eu-west-1: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + eu-west-3: [eu-central-1, eu-north-1, eu-west-1, eu-west-3] + il-central-1: [eu-central-1, eu-north-1, eu-south-1, eu-west-1, eu-west-3, il-central-1] + + - inferenceProfileId: us.meta.llama3-1-8b-instruct-v1:0 + inferenceProfileName: US Llama 3.1 8B Instruct + modelId: meta.llama3-1-8b-instruct-v1:0 + createdAt: 2024-07-23T00:00:00Z + routes: + us-east-1: [us-east-1, us-east-2, us-west-2] + us-east-2: [us-east-1, us-east-2, us-west-2] + us-west-2: [us-east-1, us-east-2, us-west-2] + + - inferenceProfileId: us.anthropic.claude-sonnet-4-5-20250929-v1:0 + inferenceProfileName: US Claude Sonnet 4.5 + modelId: anthropic.claude-sonnet-4-5-20250929-v1:0 + createdAt: 2025-09-30T00:00:00Z + routes: + us-east-1: [us-east-1, us-east-2, us-west-2] + us-east-2: [us-east-1, us-east-2, us-west-2] + us-west-1: [us-east-1, us-east-2, us-west-1, us-west-2] + us-west-2: [us-east-1, us-east-2, us-west-2] + ca-central-1: [ca-central-1, us-east-1, us-east-2, us-west-2] + + - inferenceProfileId: eu.anthropic.claude-sonnet-4-5-20250929-v1:0 + inferenceProfileName: EU Claude Sonnet 4.5 + modelId: anthropic.claude-sonnet-4-5-20250929-v1:0 + createdAt: 2025-09-30T00:00:00Z + routes: + eu-central-1: [eu-central-1, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-3] + eu-central-2: [eu-central-1, eu-central-2, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-3] + eu-north-1: [eu-central-1, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-3] + eu-south-1: [eu-central-1, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-3] + eu-south-2: [eu-central-1, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-3] + eu-west-1: [eu-central-1, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-3] + eu-west-2: [eu-central-1, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-2, eu-west-3] + eu-west-3: [eu-central-1, eu-north-1, eu-south-1, eu-south-2, eu-west-1, eu-west-3] diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockModelCatalogIntegrationTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockModelCatalogIntegrationTest.java new file mode 100644 index 0000000000..10f30bb631 --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockModelCatalogIntegrationTest.java @@ -0,0 +1,301 @@ +package io.floci.aws.services.bedrock; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.bedrock.BedrockClient; +import software.amazon.awssdk.services.bedrock.model.AccessDeniedException; +import software.amazon.awssdk.services.bedrock.model.FoundationModelDetails; +import software.amazon.awssdk.services.bedrock.model.FoundationModelSummary; +import software.amazon.awssdk.services.bedrock.model.GetInferenceProfileResponse; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileModel; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileStatus; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileSummary; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileType; +import software.amazon.awssdk.services.bedrock.model.InferenceType; +import software.amazon.awssdk.services.bedrock.model.ListInferenceProfilesResponse; +import software.amazon.awssdk.services.bedrock.model.ModelModality; +import software.amazon.awssdk.services.bedrock.model.ResourceNotFoundException; +import software.amazon.awssdk.services.bedrock.model.ValidationException; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class BedrockModelCatalogIntegrationTest { + + private static final String ACCOUNT = "741623800003"; + private static final String NOVA_MICRO = "amazon.nova-micro-v1:0"; + private static final String NOVA_LITE = "amazon.nova-lite-v1:0"; + private static final String TITAN_EMBED = "amazon.titan-embed-text-v2:0"; + private static final String LLAMA = "meta.llama3-1-8b-instruct-v1:0"; + + @Test + void listFoundationModelsFiltersByProviderAndOutputModality() { + try (BedrockClient client = client("us-east-1")) { + List models = client.listFoundationModels(request -> request + .byProvider("Amazon").byOutputModality(ModelModality.EMBEDDING)).modelSummaries(); + + assertEquals(List.of(TITAN_EMBED), models.stream().map(FoundationModelSummary::modelId).toList()); + FoundationModelSummary titan = models.getFirst(); + assertEquals("arn:aws:bedrock:us-east-1::foundation-model/" + TITAN_EMBED, titan.modelArn()); + assertEquals("Amazon", titan.providerName()); + assertEquals(List.of(ModelModality.TEXT), titan.inputModalities()); + assertFalse(titan.responseStreamingSupported()); + } + } + + @Test + void listFoundationModelsOnlyListsModelsServedInTheRegion() { + try (BedrockClient us = client("us-east-1"); BedrockClient eu = client("eu-west-1")) { + assertTrue(modelIds(us).contains(LLAMA)); + List euModels = modelIds(eu); + assertFalse(euModels.contains(LLAMA), "Llama 3.1 8B is served from US Regions only"); + assertTrue(euModels.contains(NOVA_MICRO)); + } + } + + @Test + void getFoundationModelAcceptsTheIdAndTheArn() { + try (BedrockClient client = client("eu-west-1")) { + FoundationModelDetails byId = client.getFoundationModel(request -> request.modelIdentifier(NOVA_MICRO)) + .modelDetails(); + FoundationModelDetails byArn = client.getFoundationModel(request -> request + .modelIdentifier("arn:aws:bedrock:eu-west-1::foundation-model/" + NOVA_MICRO)).modelDetails(); + + assertEquals(byId, byArn); + assertEquals("Nova Micro", byId.modelName()); + assertEquals("arn:aws:bedrock:eu-west-1::foundation-model/" + NOVA_MICRO, byId.modelArn()); + } + } + + @Test + void getFoundationModelRefusesAnUnknownModelAsInvalid() { + try (BedrockClient client = client("eu-west-1")) { + ValidationException unknown = assertThrows(ValidationException.class, + () -> client.getFoundationModel(request -> request.modelIdentifier("amazon.no-such-model-v1:0"))); + assertEquals(400, unknown.statusCode()); + } + } + + @Test + void getFoundationModelRefusesAKnownModelTheRegionDoesNotServe() { + try (BedrockClient us = client("us-east-1"); BedrockClient usWest = client("us-west-1"); + BedrockClient osaka = client("ap-northeast-3"); BedrockClient eu = client("eu-west-1")) { + assertEquals(NOVA_LITE, us.getFoundationModel(request -> request.modelIdentifier(NOVA_LITE)) + .modelDetails().modelId()); + assertEquals(NOVA_LITE, usWest.getFoundationModel(request -> request.modelIdentifier(NOVA_LITE)) + .modelDetails().modelId()); + + ValidationException unserved = assertThrows(ValidationException.class, + () -> osaka.getFoundationModel(request -> request.modelIdentifier(NOVA_LITE))); + assertEquals(400, unserved.statusCode()); + assertThrows(ValidationException.class, () -> eu.getFoundationModel(request -> request.modelIdentifier(LLAMA))); + } + } + + @ParameterizedTest + @CsvSource({"us-east-1,SPEECH", "us-east-1,VIDEO", "ap-northeast-3,SPEECH", "ap-northeast-3,VIDEO"}) + void listFoundationModelsAcceptsAnOutputModalityNoCatalogModelProduces(String region, String modality) { + try (BedrockClient client = client(region)) { + assertTrue(client.listFoundationModels(request -> request.byOutputModality(modality)) + .modelSummaries().isEmpty()); + } + } + + @Test + void listFoundationModelsRefusesAnOutputModalityOutsideTheEnum() { + try (BedrockClient client = client("us-east-1")) { + ValidationException error = assertThrows(ValidationException.class, + () -> client.listFoundationModels(request -> request.byOutputModality("AUDIO"))); + assertEquals("1 validation error detected: Value 'AUDIO' at 'byOutputModality' failed to satisfy " + + "constraint: Member must satisfy enum value set: [TEXT, IMAGE, EMBEDDING, SPEECH, VIDEO]", + error.awsErrorDetails().errorMessage()); + } + } + + @Test + void aModelServedOnlyThroughAProfileIsNotListedAsOnDemand() { + try (BedrockClient client = client("eu-central-1")) { + FoundationModelSummary novaMicro = client.listFoundationModels(request -> { }).modelSummaries().stream() + .filter(model -> model.modelId().equals(NOVA_MICRO)).findFirst().orElseThrow(); + assertTrue(novaMicro.inferenceTypesSupported().isEmpty(), + "Nova Micro is reachable from eu-central-1 only through eu." + NOVA_MICRO); + + List onDemand = client.listFoundationModels(request -> request + .byInferenceType(InferenceType.ON_DEMAND)).modelSummaries().stream() + .map(FoundationModelSummary::modelId).toList(); + assertFalse(onDemand.contains(NOVA_MICRO)); + assertTrue(onDemand.contains(TITAN_EMBED)); + } + } + + @ParameterizedTest + @ValueSource(strings = { + "arn:aws:bedrock-runtime:eu-west-1::foundation-model/" + NOVA_MICRO, + "arn:aws:bedrock:us-east-1::foundation-model/" + NOVA_MICRO, + "arn:aws-cn:bedrock:eu-west-1::foundation-model/" + NOVA_MICRO, + "arn:aws:bedrock:eu-west-1:" + ACCOUNT + ":foundation-model/" + NOVA_MICRO, + "arn:aws:bedrock:eu-west-1::custom-model/" + NOVA_MICRO}) + void getFoundationModelRefusesAnArnThatDoesNotNameTheModelInTheRegion(String arn) { + try (BedrockClient client = client("eu-west-1")) { + ValidationException error = assertThrows(ValidationException.class, + () -> client.getFoundationModel(request -> request.modelIdentifier(arn))); + assertEquals(400, error.statusCode()); + } + } + + @ParameterizedTest + @ValueSource(strings = { + "arn:aws:bedrock:us-east-1:" + ACCOUNT + ":inference-profile/us.amazon.nova-lite-v1:0", + "arn:aws-cn:bedrock:us-west-1:" + ACCOUNT + ":inference-profile/us.amazon.nova-lite-v1:0", + "arn:aws:bedrock:us-west-1:" + ACCOUNT + ":application-inference-profile/us.amazon.nova-lite-v1:0"}) + void getInferenceProfileRefusesAnArnThatDoesNotNameTheProfileInTheRegion(String arn) { + try (BedrockClient client = client("us-west-1")) { + ResourceNotFoundException error = assertThrows(ResourceNotFoundException.class, + () -> client.getInferenceProfile(request -> request.inferenceProfileIdentifier(arn))); + assertEquals(404, error.statusCode()); + } + } + + @ParameterizedTest + @ValueSource(strings = { + "arn:aws:bedrock-runtime:us-west-1:" + ACCOUNT + ":inference-profile/us.amazon.nova-lite-v1:0", + "arn:aws:bedrock:us-west-1::inference-profile/us.amazon.nova-lite-v1:0"}) + void getInferenceProfileRefusesAnArnOfAnotherServiceOrWithoutAnAccountAsInvalid(String arn) { + try (BedrockClient client = client("us-west-1")) { + ValidationException error = assertThrows(ValidationException.class, + () -> client.getInferenceProfile(request -> request.inferenceProfileIdentifier(arn))); + assertEquals(400, error.statusCode()); + } + } + + @Test + void getInferenceProfileRefusesAnArnOfAnotherAccountAsAccessDenied() { + try (BedrockClient client = client("us-west-1")) { + AccessDeniedException error = assertThrows(AccessDeniedException.class, + () -> client.getInferenceProfile(request -> request + .inferenceProfileIdentifier("arn:aws:bedrock:us-west-1:741623800004:inference-profile/" + + "us.amazon.nova-lite-v1:0"))); + assertEquals(403, error.statusCode()); + } + } + + @Test + void listInferenceProfilesReturnsTheProfilesTheSourceRegionCanUse() { + try (BedrockClient us = client("us-east-1"); BedrockClient eu = client("eu-west-1")) { + List usProfiles = profileIds(us); + assertTrue(usProfiles.contains("us." + NOVA_MICRO)); + assertFalse(usProfiles.contains("eu." + NOVA_MICRO)); + + List euProfiles = profileIds(eu); + assertTrue(euProfiles.contains("eu." + NOVA_MICRO)); + assertFalse(euProfiles.contains("us." + NOVA_MICRO)); + } + } + + @Test + void getInferenceProfileListsTheDestinationRegionsOfTheSourceRegion() { + try (BedrockClient client = client("us-west-1")) { + GetInferenceProfileResponse profile = client.getInferenceProfile(request -> request + .inferenceProfileIdentifier("us.amazon.nova-lite-v1:0")); + + assertEquals("arn:aws:bedrock:us-west-1:" + ACCOUNT + ":inference-profile/us.amazon.nova-lite-v1:0", + profile.inferenceProfileArn()); + assertEquals(InferenceProfileType.SYSTEM_DEFINED, profile.type()); + assertEquals(InferenceProfileStatus.ACTIVE, profile.status()); + assertEquals(List.of( + "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0", + "arn:aws:bedrock:us-east-2::foundation-model/amazon.nova-lite-v1:0", + "arn:aws:bedrock:us-west-1::foundation-model/amazon.nova-lite-v1:0", + "arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-lite-v1:0"), + profile.models().stream().map(InferenceProfileModel::modelArn).toList()); + + GetInferenceProfileResponse byArn = client.getInferenceProfile(request -> request + .inferenceProfileIdentifier(profile.inferenceProfileArn())); + assertEquals(profile.inferenceProfileId(), byArn.inferenceProfileId()); + } + } + + @Test + void getInferenceProfileRefusesAProfileTheSourceRegionCannotUse() { + try (BedrockClient client = client("us-east-1")) { + ResourceNotFoundException error = assertThrows(ResourceNotFoundException.class, + () -> client.getInferenceProfile(request -> request.inferenceProfileIdentifier("eu." + NOVA_MICRO))); + assertEquals(404, error.statusCode()); + } + } + + @Test + void listInferenceProfilesPagesThroughEveryProfile() { + try (BedrockClient client = client("us-east-1")) { + List all = profileIds(client); + List paged = new ArrayList<>(); + String token = null; + do { + String current = token; + ListInferenceProfilesResponse page = client.listInferenceProfiles(request -> request + .maxResults(1).nextToken(current)); + assertTrue(page.inferenceProfileSummaries().size() <= 1); + page.inferenceProfileSummaries().forEach(summary -> paged.add(summary.inferenceProfileId())); + token = page.nextToken(); + } while (token != null); + + assertTrue(all.size() > 1); + assertEquals(all, paged); + } + } + + @Test + void listInferenceProfilesFiltersByType() { + try (BedrockClient client = client("us-east-1")) { + ListInferenceProfilesResponse application = client.listInferenceProfiles(request -> request + .typeEquals(InferenceProfileType.APPLICATION)); + assertTrue(application.inferenceProfileSummaries().isEmpty()); + assertNull(application.nextToken()); + + assertTrue(client.listInferenceProfiles(request -> request.typeEquals(InferenceProfileType.SYSTEM_DEFINED)) + .inferenceProfileSummaries().stream() + .allMatch(summary -> summary.type() == InferenceProfileType.SYSTEM_DEFINED)); + } + } + + @Test + void listInferenceProfilesRefusesAnOutOfRangePageSize() { + try (BedrockClient client = client("us-east-1")) { + assertThrows(ValidationException.class, () -> client.listInferenceProfiles(request -> request.maxResults(0))); + assertThrows(ValidationException.class, () -> client.listInferenceProfiles(request -> request.maxResults(1001))); + } + } + + private static List modelIds(BedrockClient client) { + return client.listFoundationModels(request -> { }).modelSummaries().stream() + .map(FoundationModelSummary::modelId).toList(); + } + + private static List profileIds(BedrockClient client) { + return client.listInferenceProfiles(request -> request.maxResults(1000)).inferenceProfileSummaries().stream() + .map(InferenceProfileSummary::inferenceProfileId).toList(); + } + + private static BedrockClient client(String region) { + return BedrockClient.builder().endpointOverride(URI.create("http://localhost:" + RestAssured.port)) + .httpClientBuilder(UrlConnectionHttpClient.builder()).region(Region.of(region)) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(ACCOUNT, "test"))) + .build(); + } +}