Light, fluffy, and always free - The AWS Local Emulator alternative
fix(bedrock-runtime): preserve structured output and reasoning effort (#5512)
david leed0c7bd1f6f48
diff --git a/docs/services/bedrock-runtime.md b/docs/services/bedrock-runtime.mdindex 00a7017e63..0cf34c3506 100644--- a/docs/services/bedrock-runtime.md+++ b/docs/services/bedrock-runtime.md@@ -54,6 +54,57 @@ Useful for integration testing: applications that call Bedrock directly don't ne## Examples+### Structured outputs through the proxy++Both `Converse` and `ConverseStream` translate+`outputConfig.textFormat` with `type: "json_schema"` into OpenAI+`response_format.json_schema`. The Bedrock+`structure.jsonSchema.schema` value is a JSON string; the proxy parses it into+the schema object expected by the backend, without rewriting its properties.+Optional `name` and `description` are preserved. If the name is omitted, the+proxy uses `response`, since the OpenAI wire shape requires a name.++```python+import json++response = client.converse(+ modelId="your-mapped-model-id",+ messages=[{"role": "user", "content": [{"text": "Return a readiness label."}]}],+ outputConfig={"textFormat": {+ "type": "json_schema",+ "structure": {"jsonSchema": {+ "name": "readiness",+ "schema": json.dumps({+ "type": "object",+ "properties": {"ready": {"type": "boolean"}},+ "required": ["ready"],+ "additionalProperties": False,+ }),+ }},+ }},+)+```++The backend and model must support this response format and the supplied schema.+The proxy does not inject OpenAI's `strict` flag: that mode imposes extra schema+restrictions, such as requiring every property, that valid Bedrock schemas need+not satisfy. Schema enforcement therefore follows the backend's behavior; Floci+does not emulate Bedrock's guaranteed schema adherence. Callers should validate+returned data when testing through the proxy.+The proxy rejects malformed configuration or a schema that is not a JSON object+with `400 ValidationException`; it does not implement a JSON Schema validator or+validate generated responses. Requests without a text format keep their existing+behavior. The `stub` backend still ignores output constraints.++`outputConfig.effort` is translated to OpenAI `reasoning_effort` on both operations,+with or without `textFormat`. The supported Bedrock levels are `low`, `medium`,+`high`, `xhigh`, and `max`; the requested value is preserved without downgrading it.+The configured backend and model must support the requested effort level. In+particular, `max` is not a standard OpenAI Chat Completions level and requires a+backend that accepts it. A backend rejection is returned as `ModelErrorException`.+Malformed or unrecognized effort values produce a+`400 ValidationException` before contacting the backend.+### Inline images through the proxyBoth `Converse` and `ConverseStream` forward inline `image` blocks as OpenAI@@ -76,6 +127,12 @@ with open("image.png", "rb") as image:Supply raw bytes to the AWS SDK; it performs the wire-level Base64 encoding.The proxy rejects unsupported formats, malformed Base64, empty byte sources,and S3 image sources with `400 ValidationException` before contacting the backend.+Only `text` and `json` blocks are supported inside `toolResult.content`, because+OpenAI tool messages accept text and the proxy serializes JSON results to text.+Other content, including images, documents, videos, and search results, is rejected+with `400 ValidationException` before contacting the backend, rather than being+silently discarded.+It does not decode image files or enforce model-specific image dimensions andsize limits; those remain the responsibility of the configured backend.diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockruntime/backend/BedrockOpenAiTranslator.java b/src/main/java/io/github/hectorvent/floci/services/bedrockruntime/backend/BedrockOpenAiTranslator.javaindex f890050a94..ba3d0b4cad 100644--- a/src/main/java/io/github/hectorvent/floci/services/bedrockruntime/backend/BedrockOpenAiTranslator.java+++ b/src/main/java/io/github/hectorvent/floci/services/bedrockruntime/backend/BedrockOpenAiTranslator.java@@ -1,5 +1,7 @@package io.github.hectorvent.floci.services.bedrockruntime.backend;+import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;@@ -107,9 +109,71 @@ final class BedrockOpenAiTranslator {openAi.set("stop", stopSequences.deepCopy());}+ translateOutputConfig(mapper, bedrockRequest.path("outputConfig"), openAi);+return openAi;}+ /**+ * Converts Bedrock output controls to the OpenAI wire shape, rejecting malformed+ * configuration before either Converse operation contacts the backend.+ */+ private static void translateOutputConfig(ObjectMapper mapper, JsonNode outputConfig, ObjectNode openAi) {+ if (outputConfig.isMissingNode()) {+ return;+ }+ if (!outputConfig.isObject()) {+ throw new AwsException("ValidationException", "outputConfig must be an object.", 400);+ }+ // Effort is independent of textFormat, so effort-only requests must survive the return below.+ if (outputConfig.has("effort")) {+ JsonNode effort = outputConfig.path("effort");+ if (!effort.isTextual() || !List.of("low", "medium", "high", "xhigh", "max").contains(effort.asText())) {+ throw new AwsException("ValidationException",+ "outputConfig.effort must be low, medium, high, xhigh, or max.", 400);+ }+ openAi.put("reasoning_effort", effort.asText());+ }+ JsonNode textFormat = outputConfig.path("textFormat");+ if (textFormat.isMissingNode()) {+ return;+ }+ JsonNode structure = textFormat.path("structure");+ JsonNode definition = structure.path("jsonSchema");+ JsonNode schemaString = definition.path("schema");+ // structure is an AWS union: jsonSchema must be its only member.+ if (!"json_schema".equals(textFormat.path("type").asText())+ || !structure.isObject() || structure.size() != 1 || !definition.isObject()+ || !schemaString.isTextual()+ || (definition.has("name") && !definition.path("name").isTextual())+ || (definition.has("description") && !definition.path("description").isTextual())) {+ throw new AwsException("ValidationException",+ "outputConfig.textFormat requires type json_schema and structure.jsonSchema with a schema string"+ + " and optional string name/description.", 400);+ }+ JsonNode schema;+ try {+ // Decimal constraints must retain their precision, and trailing JSON values are malformed input.+ schema = mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)+ .with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)+ .readTree(schemaString.asText());+ } catch (JsonProcessingException e) {+ throw new AwsException("ValidationException", "Structured output schema must be a JSON object.", 400);+ }+ if (schema == null || !schema.isObject()) {+ throw new AwsException("ValidationException", "Structured output schema must be a JSON object.", 400);+ }+ // OpenAI requires a name that Bedrock makes optional, so use a stable default.+ // Leave strict unset: its extra restrictions would reject schemas with optional properties.+ ObjectNode responseFormat = openAi.putObject("response_format").put("type", "json_schema");+ ObjectNode jsonSchema = responseFormat.putObject("json_schema");+ jsonSchema.put("name", definition.path("name").asText("response"));+ jsonSchema.set("schema", schema);+ if (definition.has("description")) {+ jsonSchema.set("description", definition.path("description").deepCopy());+ }+ }+/** Builds the OpenAI {@code {type: "function", function: {name}}} shape shared by tools[] entries and tool_choice. */private static ObjectNode putFunctionRef(ObjectNode target, String name) {target.put("type", "function");@@ -222,6 +286,11 @@ final class BedrockOpenAiTranslator {}StringBuilder sb = new StringBuilder();for (JsonNode part : toolResultContent) {+ if (!part.isObject() || part.size() != 1 || (!part.has("text") && !part.has("json"))) {+ throw new AwsException("ValidationException",+ "The proxy supports only text or json blocks in toolResult.content.",+ 400);+ }String text = part.path("text").asText(null);if (text == null && part.has("json")) {text = part.path("json").toString();diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockruntime/BedrockProxyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockruntime/BedrockProxyIntegrationTest.javaindex d42a3c9762..fa50995b6a 100644--- a/src/test/java/io/github/hectorvent/floci/services/bedrockruntime/BedrockProxyIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/bedrockruntime/BedrockProxyIntegrationTest.java@@ -1,7 +1,9 @@package io.github.hectorvent.floci.services.bedrockruntime;+import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;import com.sun.net.httpserver.Headers;import com.sun.net.httpserver.HttpServer;import io.quarkus.test.junit.QuarkusTest;@@ -106,6 +108,198 @@ class BedrockProxyIntegrationTest {.body("usage.totalTokens", equalTo(16));}+ @ParameterizedTest+ @ValueSource(strings = {"low", "medium", "high", "xhigh", "max"})+ void effortReachesProxyWithAndWithoutTextFormat(String effort) throws IOException {+ for (String operation : new String[]{"converse", "converse-stream"}) {+ nextResponseBody.set(operation.equals("converse")+ ? """+ {"choices":[{"finish_reason":"stop","message":{"content":"{}"}}]}+ """+ : """+ data: {"choices":[{"delta":{"content":"{}"},"finish_reason":"stop"}]}++ data: [DONE]+ """);+ for (boolean withTextFormat : new boolean[]{false, true}) {+ ObjectNode request = (ObjectNode) objectMapper.readTree("""+ {"messages":[{"role":"user","content":[{"text":"Return a label"}]}]}+ """);+ ObjectNode outputConfig = request.putObject("outputConfig").put("effort", effort);+ if (withTextFormat) {+ outputConfig.putObject("textFormat").put("type", "json_schema")+ .putObject("structure").putObject("jsonSchema").put("schema", "{\"type\":\"object\"}");+ }+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body(request.toString())+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/" + operation)+ .then()+ .statusCode(200);+ JsonNode sent = objectMapper.readTree(received.get().body());+ assertEquals(effort, sent.path("reasoning_effort").asText());+ assertEquals(withTextFormat, sent.has("response_format"));+ assertFalse(sent.has("outputConfig"));+ assertFalse(sent.has("effort"));+ }+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"converse", "converse-stream"})+ void structuredOutputSchemaReachesProxy(String operation) throws IOException {+ nextResponseBody.set(operation.equals("converse")+ ? """+ {"choices":[{"finish_reason":"stop","message":{"content":"{}"}}]}+ """+ : """+ data: {"choices":[{"delta":{"content":"{}"},"finish_reason":"stop"}]}++ data: [DONE]+ """);+ ObjectNode request = (ObjectNode) objectMapper.readTree("""+ {"messages":[{"role":"user","content":[{"text":"Extract a label"}]}]}+ """);+ JsonNode schema = objectMapper.readTree("""+ {"type":"object","properties":{"label":{"$ref":"#/$defs/label"}},+ "additionalProperties":false,+ "$defs":{"label":{"type":"string","enum":["ready","pending"]}}}+ """);+ ObjectNode definition = request.putObject("outputConfig").putObject("textFormat")+ .put("type", "json_schema").putObject("structure").putObject("jsonSchema");+ definition.put("name", "label_response");+ definition.put("description", "A readiness label");+ definition.put("schema", schema.toString());++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body(request.toString())+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/" + operation)+ .then()+ .statusCode(200);++ JsonNode responseFormat = objectMapper.readTree(received.get().body()).path("response_format");+ assertEquals("json_schema", responseFormat.path("type").asText());+ JsonNode forwarded = responseFormat.path("json_schema");+ assertEquals("label_response", forwarded.path("name").asText());+ assertEquals("A readiness label", forwarded.path("description").asText());+ assertFalse(forwarded.has("strict"), "Bedrock schemas must not acquire OpenAI-only strict restrictions");+ assertEquals(schema, forwarded.path("schema"));+ }++ @Test+ void structuredOutputPreservesDecimalConstraints() throws IOException {+ nextResponseBody.set("""+ {"choices":[{"finish_reason":"stop","message":{"content":"{}"}}]}+ """);+ ObjectNode request = (ObjectNode) objectMapper.readTree("""+ {"messages":[{"role":"user","content":[{"text":"Return a number"}]}]}+ """);+ String schema = """+ {"type":"object","properties":{"value":{"const":0.1234567890123456789}}}+ """;+ request.putObject("outputConfig").putObject("textFormat").put("type", "json_schema")+ .putObject("structure").putObject("jsonSchema").put("schema", schema);+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body(request.toString())+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/converse")+ .then()+ .statusCode(200);+ JsonNode sent = objectMapper.reader().with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)+ .readTree(received.get().body());+ assertEquals("0.1234567890123456789", sent.path("response_format").path("json_schema")+ .path("schema").path("properties").path("value").path("const").asText());+ }++ @Test+ void structuredOutputMetadataIsOptional() throws IOException {+ nextResponseBody.set("""+ {"choices":[{"finish_reason":"stop","message":{"content":"{}"}}]}+ """);+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"messages":[{"role":"user","content":[{"text":"hi"}]}],+ "outputConfig":{"textFormat":{"type":"json_schema","structure":{+ "jsonSchema":{"schema":"{\\"type\\":\\"object\\"}"}}}}}+ """)+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/converse")+ .then()+ .statusCode(200);+ JsonNode format = objectMapper.readTree(received.get().body()).path("response_format").path("json_schema");+ assertEquals("response", format.path("name").asText());+ assertFalse(format.has("description"));+ assertEquals("object", format.path("schema").path("type").asText());+ }++ @ParameterizedTest+ @ValueSource(strings = {"{}", "{\"outputConfig\":{}}"})+ void absentTextFormatDoesNotConstrainResponse(String extras) throws IOException {+ nextResponseBody.set("""+ {"choices":[{"finish_reason":"stop","message":{"content":"hi"}}]}+ """);+ ObjectNode request = (ObjectNode) objectMapper.readTree(extras);+ request.set("messages", objectMapper.readTree("""+ [{"role":"user","content":[{"text":"hi"}]}]+ """));+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body(request.toString())+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/converse")+ .then()+ .statusCode(200);+ JsonNode sent = objectMapper.readTree(received.get().body());+ assertFalse(sent.has("response_format"));+ assertFalse(sent.has("reasoning_effort"));+ }++ @ParameterizedTest+ @ValueSource(strings = {+ "null", "[]", "{\"effort\":null}", "{\"effort\":42}", "{\"effort\":{}}",+ "{\"effort\":\"\"}", "{\"effort\":\"unknown\"}", "{\"textFormat\":null}", "{\"textFormat\":{}}",+ "{\"textFormat\":{\"type\":\"json_object\",\"structure\":{\"jsonSchema\":{\"schema\":\"{}\"}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":{}}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"\"}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"not json\"}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"[]\"}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"true\"}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"{} {}\"}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"{}\",\"name\":42}}}}",+ "{\"textFormat\":{\"type\":\"json_schema\",\"structure\":{\"jsonSchema\":{\"schema\":\"{}\",\"description\":false}}}}"+ })+ void invalidOutputConfigFailsBeforeCallingProxy(String outputConfig) {+ nextResponseBody.set("""+ {"choices":[{"finish_reason":"stop","message":{"content":"unexpected"}}]}+ """);+ for (String operation : new String[]{"converse", "converse-stream"}) {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"messages":[{"role":"user","content":[{"text":"hi"}]}],"outputConfig":%s}+ """.formatted(outputConfig))+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/" + operation)+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ assertNull(received.get());+ }+ }+@ParameterizedTest@ValueSource(strings = {"converse", "converse-stream"})void imagesAndTextReachProxyInOriginalOrder(String operation) throws IOException {@@ -248,6 +442,76 @@ class BedrockProxyIntegrationTest {}}+ @ParameterizedTest+ @ValueSource(strings = {+ "[{\"image\":{\"format\":\"png\",\"source\":{\"bytes\":\"AQID\"}}}]",+ "[{\"text\":\"result\"},{\"image\":{\"format\":\"png\",\"source\":{\"bytes\":\"AQID\"}}},{\"json\":{\"ok\":true}}]",+ "[{\"image\":{\"format\":\"png\",\"source\":{\"s3Location\":{\"uri\":\"s3://bucket/image.png\"}}}}]",+ "[{\"document\":{\"format\":\"txt\",\"name\":\"note\",\"source\":{\"bytes\":\"AQID\"}}}]",+ "[{\"video\":{\"format\":\"mp4\",\"source\":{\"bytes\":\"AQID\"}}}]",+ "[{\"searchResult\":{\"source\":\"https://example.com\",\"title\":\"result\",\"content\":[{\"text\":\"result\"}]}}]",+ "[{\"futureMember\":{}}]",+ "[{}]",+ "[null]",+ "[{\"text\":\"result\",\"json\":{\"ok\":true}}]"+ })+ void unsupportedToolResultContentFailsBeforeCallingProxy(String content) {+ nextResponseBody.set("""+ {"choices":[{"finish_reason":"stop","message":{"content":"unexpected"}}]}+ """);+ for (String operation : new String[]{"converse", "converse-stream"}) {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"messages":[+ {"role":"assistant","content":[{"toolUse":{"toolUseId":"call_1","name":"get_image","input":{}}}]},+ {"role":"user","content":[{"toolResult":{"toolUseId":"call_1","content":%s}}]}+ ]}+ """.formatted(content))+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/" + operation)+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", containsString("toolResult"));+ assertNull(received.get());+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"converse", "converse-stream"})+ void textAndJsonToolResultsReachProxy(String operation) throws IOException {+ nextResponseBody.set(operation.equals("converse")+ ? """+ {"choices":[{"finish_reason":"stop","message":{"content":"result received"}}]}+ """+ : """+ data: {"choices":[{"delta":{"content":"result received"},"finish_reason":"stop"}]}++ data: [DONE]+ """);+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("""+ {"messages":[+ {"role":"assistant","content":[{"toolUse":{"toolUseId":"call_1","name":"get_result","input":{}}}]},+ {"role":"user","content":[{"toolResult":{"toolUseId":"call_1","content":[+ {"text":"result"},{"json":{"ok":true}},{"text":"done"}+ ]}}]}+ ]}+ """)+ .when()+ .post("/model/" + MAPPED_MODEL_ID + "/" + operation)+ .then()+ .statusCode(200);+ JsonNode toolMessage = objectMapper.readTree(received.get().body()).path("messages").get(1);+ assertEquals("tool", toolMessage.path("role").asText());+ assertEquals("call_1", toolMessage.path("tool_call_id").asText());+ assertEquals("result\n{\"ok\":true}\ndone", toolMessage.path("content").asText());+ }+@Testvoid converse_toolCallsTranslateToToolUse() throws IOException {nextResponseBody.set("""