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.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-08 05:02:41 -04:00
1 parent d51729143b
commit 30db535f2e
9 files changed
+849 -8

No files matched your search

@@ -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<BedrockModelCatalog.InferenceProfile> 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());
@@ -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}.
*
* <p>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<String> inputModalities,
List<String> outputModalities, boolean responseStreamingSupported,
String lifecycleStatus, Set<String> 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<String, List<String>> routes) {
}
static final List<FoundationModel> MODELS;
static final List<InferenceProfile> 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<FoundationModel> 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<InferenceProfile> profilesFrom(String region) {
return PROFILES.stream().filter(profile -> profile.routes().containsKey(region)).toList();
}
private static Map<String, List<String>> copyRoutes(Map<String, List<String>> 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<ModelEntry> foundationModels = List.of();
public List<ProfileEntry> inferenceProfiles = List.of();
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
static final class ModelEntry {
public String modelId;
public String modelName;
public String providerName;
public List<String> inputModalities = List.of();
public List<String> outputModalities = List.of();
public boolean responseStreamingSupported;
public String lifecycleStatus;
public List<String> 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<String, List<String>> routes = Map.of();
}
}
@@ -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<String> OUTPUT_MODALITIES = List.of("TEXT", "IMAGE", "EMBEDDING", "SPEECH", "VIDEO");
private static final List<String> INFERENCE_TYPES = List.of("ON_DEMAND", "PROVISIONED");
private static final List<String> 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<String> 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<BedrockModelCatalog.FoundationModel> 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<BedrockModelCatalog.FoundationModel> 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<BedrockModelCatalog.InferenceProfile> 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<BedrockModelCatalog.InferenceProfile> 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<String> 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();