mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API (#1789)
* feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API * fix(bedrock): preserve leading text when a tool call response also has content OpenAI-compatible backends can return assistant text alongside tool_calls in the same response (e.g. a preamble before invoking a tool). The Converse translation only emitted the toolUse block in that case, silently dropping the text. * fix(bedrock): use InternalServerException for proxy serialization failures InternalFailure isn't a bedrock-runtime error shape in botocore/the Java SDK, so clients couldn't map it; InternalServerException is the declared 500 for this API. * fix(bedrock): map proxy backend timeouts to ModelTimeoutException (408) HttpTimeoutException (connect or request timeout) was falling into the generic catch and surfacing as ModelErrorException/424, which the AWS SDKs treat as terminal. Bedrock's dedicated 408 shape is retryable under the default SDK retry strategy, so this distinction is load-bearing, not cosmetic. Also makes the request timeout configurable (proxy.request-timeout-seconds, default 60s) since larger models on CPU-backed backends may need more headroom than the default. * fix(bedrock): fail fast on InvokeModel under the proxy backend Falling back to StubBackend's canned response meant a caller who configured a real proxy backend and called InvokeModel got a plausible-looking, entirely fabricated completion with no signal beyond a server-side log line. That's inconsistent with Converse, which already fails loudly on misconfiguration, and worse: InvokeModel is still the default entry point for many SDK wrappers, so this could silently mask a broken integration. Also fixes the streaming-endpoint error messages, which blamed "the Floci stub" for a limitation that's actually unconditional (streaming isn't implemented for any backend).
This commit is contained in:
1 parent
e048e52ce0
commit
875e0f2d3b
13 files changed
+1622
-67
No files matched your search
@@ -1164,6 +1164,58 @@ public interface EmulatorConfig {
|
||||
interface BedrockRuntimeServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
/**
|
||||
* Converse/InvokeModel backend: "stub" (default, hardcoded response, no
|
||||
* external calls) or "proxy" (forwards Converse to an OpenAI-compatible
|
||||
* /chat/completions endpoint; see {@link BedrockProxyConfig}).
|
||||
*/
|
||||
@WithDefault("stub")
|
||||
String backend();
|
||||
|
||||
BedrockProxyConfig proxy();
|
||||
}
|
||||
|
||||
interface BedrockProxyConfig {
|
||||
/**
|
||||
* Base URL of the OpenAI-compatible backend (Ollama, OpenRouter, LiteLLM,
|
||||
* vLLM), e.g. "http://localhost:11434/v1". Required when backend=proxy;
|
||||
* requests are POSTed to "{url}/chat/completions".
|
||||
*/
|
||||
Optional<String> url();
|
||||
|
||||
/** Sent as "Authorization: Bearer {apiKey}" when present. */
|
||||
Optional<String> apiKey();
|
||||
|
||||
/**
|
||||
* Fallback OpenAI-side model id used when no explicit mapping matches
|
||||
* and passthrough is disabled.
|
||||
*/
|
||||
Optional<String> defaultModel();
|
||||
|
||||
/**
|
||||
* Comma-separated {@code bedrockModelId=openaiModelId} pairs, e.g.
|
||||
* {@code "anthropic.claude-3-sonnet-20240229-v1:0=claude-3-sonnet"}.
|
||||
* A delimited string rather than a native Map config property: Bedrock
|
||||
* model ids contain '.' and ':', which collide with SmallRye's per-key
|
||||
* env-var naming convention for maps.
|
||||
*/
|
||||
Optional<String> modelMapping();
|
||||
|
||||
/**
|
||||
* When true, and no explicit mapping matches, forward the raw Bedrock
|
||||
* model id as-is instead of requiring a mapping or defaultModel.
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean passthrough();
|
||||
|
||||
/**
|
||||
* How long to wait for the backend to finish generating a response before
|
||||
* failing the request with ModelTimeoutException. Larger models on
|
||||
* CPU-backed backends (e.g. Ollama) may need more than the default.
|
||||
*/
|
||||
@WithDefault("60")
|
||||
int requestTimeoutSeconds();
|
||||
}
|
||||
|
||||
interface TextractServiceConfig {
|
||||
|
||||
+7
-4
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.smallrye.common.annotation.Blocking;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.POST;
|
||||
@@ -41,6 +42,7 @@ public class BedrockRuntimeController {
|
||||
}
|
||||
|
||||
@POST
|
||||
@Blocking
|
||||
@Path("/{modelId:.+}/converse")
|
||||
public Response converse(@PathParam("modelId") String modelId, String body) {
|
||||
if (modelId == null || modelId.isBlank()) {
|
||||
@@ -62,12 +64,13 @@ public class BedrockRuntimeController {
|
||||
"messages is required and must be a non-empty array.", 400);
|
||||
}
|
||||
|
||||
ObjectNode response = service.buildConverseResponse(modelId);
|
||||
ObjectNode response = service.buildConverseResponse(modelId, (ObjectNode) request);
|
||||
LOG.debugv("Bedrock Converse: modelId={0}, messages={1}", modelId, messages.size());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Blocking
|
||||
@Path("/{modelId:.+}/invoke")
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response invokeModel(@PathParam("modelId") String modelId, byte[] body) {
|
||||
@@ -75,7 +78,7 @@ public class BedrockRuntimeController {
|
||||
throw new AwsException("ValidationException", "modelId is required.", 400);
|
||||
}
|
||||
// Bedrock InvokeModel bodies are model-specific opaque blobs; do not parse.
|
||||
byte[] response = service.buildInvokeModelResponse(modelId);
|
||||
byte[] response = service.buildInvokeModelResponse(modelId, body);
|
||||
LOG.debugv("Bedrock InvokeModel: modelId={0}, bodyBytes={1}",
|
||||
modelId, body == null ? 0 : body.length);
|
||||
return Response.ok(response, MediaType.APPLICATION_JSON).build();
|
||||
@@ -86,7 +89,7 @@ public class BedrockRuntimeController {
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response invokeModelWithResponseStream(@PathParam("modelId") String modelId) {
|
||||
throw new AwsException("UnsupportedOperationException",
|
||||
"InvokeModelWithResponseStream is not supported by the Floci stub. "
|
||||
"InvokeModelWithResponseStream is not supported by Floci yet. "
|
||||
+ "Use InvokeModel or Converse instead.", 501);
|
||||
}
|
||||
|
||||
@@ -95,7 +98,7 @@ public class BedrockRuntimeController {
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response converseStream(@PathParam("modelId") String modelId) {
|
||||
throw new AwsException("UnsupportedOperationException",
|
||||
"ConverseStream is not supported by the Floci stub. "
|
||||
"ConverseStream is not supported by Floci yet. "
|
||||
+ "Use Converse instead.", 501);
|
||||
}
|
||||
}
|
||||
+30
-54
@@ -1,75 +1,51 @@
|
||||
package io.github.hectorvent.floci.services.bedrockruntime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.bedrockruntime.backend.BedrockBackend;
|
||||
import io.github.hectorvent.floci.services.bedrockruntime.backend.ProxyBackend;
|
||||
import io.github.hectorvent.floci.services.bedrockruntime.backend.StubBackend;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Dummy response builder for Bedrock Runtime. Stateless.
|
||||
* No real model inference: returns a fixed assistant turn plus token usage metadata.
|
||||
* Thin orchestration layer for Bedrock Runtime: delegates Converse/InvokeModel to the
|
||||
* backend selected by {@code floci.services.bedrock-runtime.backend}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class BedrockRuntimeService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private static final Logger LOG = Logger.getLogger(BedrockRuntimeService.class);
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final StubBackend stubBackend;
|
||||
private final ProxyBackend proxyBackend;
|
||||
|
||||
@Inject
|
||||
public BedrockRuntimeService(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
public BedrockRuntimeService(EmulatorConfig config, StubBackend stubBackend, ProxyBackend proxyBackend) {
|
||||
this.config = config;
|
||||
this.stubBackend = stubBackend;
|
||||
this.proxyBackend = proxyBackend;
|
||||
}
|
||||
|
||||
public ObjectNode buildConverseResponse(String modelId) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
|
||||
ObjectNode output = root.putObject("output");
|
||||
ObjectNode message = output.putObject("message");
|
||||
message.put("role", "assistant");
|
||||
ArrayNode content = message.putArray("content");
|
||||
ObjectNode textBlock = content.addObject();
|
||||
textBlock.put("text", "Floci stub response for model=" + modelId);
|
||||
|
||||
root.put("stopReason", "end_turn");
|
||||
|
||||
ObjectNode usage = root.putObject("usage");
|
||||
usage.put("inputTokens", 10);
|
||||
usage.put("outputTokens", 12);
|
||||
usage.put("totalTokens", 22);
|
||||
|
||||
ObjectNode metrics = root.putObject("metrics");
|
||||
metrics.put("latencyMs", 1);
|
||||
|
||||
return root;
|
||||
public ObjectNode buildConverseResponse(String modelId, ObjectNode bedrockRequest) {
|
||||
return backend().converse(modelId, bedrockRequest);
|
||||
}
|
||||
|
||||
public byte[] buildInvokeModelResponse(String modelId) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
String lower = modelId == null ? "" : modelId.toLowerCase();
|
||||
if (lower.startsWith("anthropic.") || lower.contains(".anthropic.")) {
|
||||
root.put("id", "msg_stub");
|
||||
root.put("type", "message");
|
||||
root.put("role", "assistant");
|
||||
ArrayNode content = root.putArray("content");
|
||||
ObjectNode block = content.addObject();
|
||||
block.put("type", "text");
|
||||
block.put("text", "Floci stub response");
|
||||
root.put("model", modelId);
|
||||
root.put("stop_reason", "end_turn");
|
||||
ObjectNode usage = root.putObject("usage");
|
||||
usage.put("input_tokens", 10);
|
||||
usage.put("output_tokens", 12);
|
||||
} else {
|
||||
// Generic minimal shape for Meta, Mistral, Titan and others.
|
||||
// Bedrock returns provider-specific bodies; callers parse by model family.
|
||||
ArrayNode outputs = root.putArray("outputs");
|
||||
ObjectNode item = outputs.addObject();
|
||||
item.put("text", "Floci stub response");
|
||||
public byte[] buildInvokeModelResponse(String modelId, byte[] body) {
|
||||
return backend().invokeModel(modelId, body);
|
||||
}
|
||||
|
||||
private BedrockBackend backend() {
|
||||
String backend = config.services().bedrockRuntime().backend();
|
||||
if ("proxy".equalsIgnoreCase(backend)) {
|
||||
return proxyBackend;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsBytes(root);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize InvokeModel response", e);
|
||||
if (!"stub".equalsIgnoreCase(backend)) {
|
||||
LOG.warnv("Unrecognized floci.services.bedrock-runtime.backend value \"{0}\"; falling back to stub. "
|
||||
+ "Expected \"stub\" or \"proxy\".", backend);
|
||||
}
|
||||
return stubBackend;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.bedrockruntime.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* Executes Bedrock Runtime Converse/InvokeModel requests against a concrete backend
|
||||
* (a hardcoded stub, or a proxy to a real OpenAI-compatible model endpoint).
|
||||
*/
|
||||
public interface BedrockBackend {
|
||||
|
||||
ObjectNode converse(String modelId, ObjectNode bedrockRequest);
|
||||
|
||||
byte[] invokeModel(String modelId, byte[] body);
|
||||
}
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
package io.github.hectorvent.floci.services.bedrockruntime.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Translates between the Bedrock Runtime Converse wire shape and the OpenAI
|
||||
* Chat Completions wire shape used by Ollama, OpenRouter, LiteLLM, vLLM, etc.
|
||||
*/
|
||||
final class BedrockOpenAiTranslator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(BedrockOpenAiTranslator.class);
|
||||
|
||||
private BedrockOpenAiTranslator() {
|
||||
}
|
||||
|
||||
static ObjectNode toOpenAiRequest(ObjectMapper mapper, ObjectNode bedrockRequest, String resolvedModel) {
|
||||
ObjectNode openAi = mapper.createObjectNode();
|
||||
openAi.put("model", resolvedModel);
|
||||
openAi.put("stream", false);
|
||||
ArrayNode openAiMessages = openAi.putArray("messages");
|
||||
|
||||
JsonNode system = bedrockRequest.path("system");
|
||||
if (system.isArray()) {
|
||||
for (JsonNode block : system) {
|
||||
String text = block.path("text").asText(null);
|
||||
if (text != null) {
|
||||
ObjectNode msg = openAiMessages.addObject();
|
||||
msg.put("role", "system");
|
||||
msg.put("content", text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
JsonNode messages = bedrockRequest.path("messages");
|
||||
if (messages.isArray()) {
|
||||
for (JsonNode message : messages) {
|
||||
translateMessage(mapper, openAiMessages, message);
|
||||
}
|
||||
}
|
||||
|
||||
JsonNode toolConfig = bedrockRequest.path("toolConfig");
|
||||
JsonNode tools = toolConfig.path("tools");
|
||||
if (tools.isArray() && !tools.isEmpty()) {
|
||||
ArrayNode openAiTools = openAi.putArray("tools");
|
||||
for (JsonNode tool : tools) {
|
||||
JsonNode toolSpec = tool.path("toolSpec");
|
||||
if (!toolSpec.isObject()) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode function = putFunctionRef(openAiTools.addObject(), toolSpec.path("name").asText(""));
|
||||
if (toolSpec.hasNonNull("description")) {
|
||||
function.put("description", toolSpec.path("description").asText());
|
||||
}
|
||||
JsonNode schema = toolSpec.path("inputSchema").path("json");
|
||||
if (schema.isObject()) {
|
||||
function.set("parameters", schema.deepCopy());
|
||||
}
|
||||
}
|
||||
|
||||
// "auto" needs no explicit output: it's OpenAI's default whenever tools are present.
|
||||
JsonNode toolChoice = toolConfig.path("toolChoice");
|
||||
if (toolChoice.hasNonNull("any")) {
|
||||
openAi.put("tool_choice", "required");
|
||||
} else if (toolChoice.hasNonNull("tool")) {
|
||||
String toolName = toolChoice.path("tool").path("name").asText("");
|
||||
if (!toolName.isBlank()) {
|
||||
putFunctionRef(openAi.putObject("tool_choice"), toolName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
JsonNode inferenceConfig = bedrockRequest.path("inferenceConfig");
|
||||
JsonNode maxTokens = inferenceConfig.path("maxTokens");
|
||||
if (maxTokens.isNumber()) {
|
||||
openAi.put("max_tokens", maxTokens.asInt());
|
||||
}
|
||||
JsonNode temperature = inferenceConfig.path("temperature");
|
||||
if (temperature.isNumber()) {
|
||||
openAi.put("temperature", temperature.asDouble());
|
||||
}
|
||||
JsonNode topP = inferenceConfig.path("topP");
|
||||
if (topP.isNumber()) {
|
||||
openAi.put("top_p", topP.asDouble());
|
||||
}
|
||||
JsonNode stopSequences = inferenceConfig.path("stopSequences");
|
||||
if (stopSequences.isArray() && !stopSequences.isEmpty()) {
|
||||
openAi.set("stop", stopSequences.deepCopy());
|
||||
}
|
||||
|
||||
return openAi;
|
||||
}
|
||||
|
||||
/** 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");
|
||||
return target.putObject("function").put("name", name);
|
||||
}
|
||||
|
||||
/**
|
||||
* A Bedrock message's content[] blocks map to OpenAI in three different ways:
|
||||
* plain text accumulates into the message's content string, toolUse blocks become
|
||||
* entries in that same message's tool_calls[], and toolResult blocks become their
|
||||
* own standalone OpenAI message with role=tool — so one Bedrock message can expand
|
||||
* into zero, one, or several OpenAI messages.
|
||||
*/
|
||||
private static void translateMessage(ObjectMapper mapper, ArrayNode openAiMessages, JsonNode message) {
|
||||
String role = message.path("role").asText("user");
|
||||
JsonNode content = message.path("content");
|
||||
StringBuilder text = new StringBuilder();
|
||||
ArrayNode toolCalls = null;
|
||||
|
||||
if (content.isArray()) {
|
||||
for (JsonNode block : content) {
|
||||
if (block.has("toolResult")) {
|
||||
JsonNode toolResult = block.path("toolResult");
|
||||
ObjectNode toolMsg = openAiMessages.addObject();
|
||||
toolMsg.put("role", "tool");
|
||||
toolMsg.put("tool_call_id", toolResult.path("toolUseId").asText(""));
|
||||
toolMsg.put("content", extractToolResultText(toolResult.path("content")));
|
||||
continue;
|
||||
}
|
||||
if (block.has("toolUse")) {
|
||||
JsonNode toolUse = block.path("toolUse");
|
||||
if (toolCalls == null) {
|
||||
toolCalls = mapper.createArrayNode();
|
||||
}
|
||||
ObjectNode toolCall = toolCalls.addObject();
|
||||
toolCall.put("id", toolUse.path("toolUseId").asText(""));
|
||||
toolCall.put("type", "function");
|
||||
ObjectNode function = toolCall.putObject("function");
|
||||
function.put("name", toolUse.path("name").asText(""));
|
||||
function.put("arguments", toJsonString(mapper, toolUse.path("input")));
|
||||
continue;
|
||||
}
|
||||
String blockText = block.path("text").asText(null);
|
||||
if (blockText != null) {
|
||||
if (text.length() > 0) {
|
||||
text.append('\n');
|
||||
}
|
||||
text.append(blockText);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (text.length() > 0 || toolCalls != null) {
|
||||
ObjectNode msg = openAiMessages.addObject();
|
||||
msg.put("role", role);
|
||||
if (text.length() > 0) {
|
||||
msg.put("content", text.toString());
|
||||
} else {
|
||||
// OpenAI's spec treats content as optional when tool_calls is present; some
|
||||
// strict backends reject an empty string here instead of null.
|
||||
msg.putNull("content");
|
||||
}
|
||||
if (toolCalls != null) {
|
||||
msg.set("tool_calls", toolCalls);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String extractToolResultText(JsonNode toolResultContent) {
|
||||
if (!toolResultContent.isArray()) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (JsonNode part : toolResultContent) {
|
||||
String text = part.path("text").asText(null);
|
||||
if (text == null && part.has("json")) {
|
||||
text = part.path("json").toString();
|
||||
}
|
||||
if (text != null) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append('\n');
|
||||
}
|
||||
sb.append(text);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String toJsonString(ObjectMapper mapper, JsonNode node) {
|
||||
try {
|
||||
return mapper.writeValueAsString(node);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to serialize toolUse input as JSON: {0}", e.getMessage());
|
||||
return "{}";
|
||||
}
|
||||
}
|
||||
|
||||
static ObjectNode toBedrockResponse(ObjectMapper mapper, JsonNode openAiResponse, long latencyMs) {
|
||||
JsonNode choice = openAiResponse.path("choices").path(0);
|
||||
JsonNode message = choice.path("message");
|
||||
String finishReason = choice.path("finish_reason").asText("stop");
|
||||
JsonNode toolCallsNode = message.path("tool_calls");
|
||||
boolean hasToolCalls = toolCallsNode.isArray() && !toolCallsNode.isEmpty();
|
||||
|
||||
ObjectNode root = mapper.createObjectNode();
|
||||
ObjectNode output = root.putObject("output");
|
||||
ObjectNode outMessage = output.putObject("message");
|
||||
outMessage.put("role", "assistant");
|
||||
ArrayNode content = outMessage.putArray("content");
|
||||
|
||||
if (hasToolCalls) {
|
||||
// Some OpenAI-compatible backends emit assistant text alongside tool_calls (e.g. a
|
||||
// preamble like "Let me check that for you") — preserve it as a leading text block
|
||||
// instead of dropping it.
|
||||
String leadingText = extractMessageText(message);
|
||||
if (!leadingText.isBlank()) {
|
||||
content.addObject().put("text", leadingText);
|
||||
}
|
||||
for (JsonNode toolCall : toolCallsNode) {
|
||||
ObjectNode toolUse = content.addObject().putObject("toolUse");
|
||||
toolUse.put("toolUseId", toolCall.path("id").asText(""));
|
||||
JsonNode function = toolCall.path("function");
|
||||
toolUse.put("name", function.path("name").asText(""));
|
||||
toolUse.set("input", parseToolArguments(mapper, function.path("arguments").asText("{}")));
|
||||
}
|
||||
} else {
|
||||
content.addObject().put("text", extractMessageText(message));
|
||||
}
|
||||
|
||||
// stopReason is derived from whether we actually emitted toolUse content, not from
|
||||
// finish_reason alone: a backend can report finish_reason=tool_calls without a usable
|
||||
// tool_calls array, which must not produce a Converse response claiming tool_use with
|
||||
// no toolUse blocks in it.
|
||||
root.put("stopReason", hasToolCalls ? "tool_use" : mapFinishReason(finishReason));
|
||||
|
||||
JsonNode usage = openAiResponse.path("usage");
|
||||
ObjectNode usageOut = root.putObject("usage");
|
||||
usageOut.put("inputTokens", usage.path("prompt_tokens").asInt(0));
|
||||
usageOut.put("outputTokens", usage.path("completion_tokens").asInt(0));
|
||||
usageOut.put("totalTokens", usage.path("total_tokens").asInt(0));
|
||||
|
||||
root.putObject("metrics").put("latencyMs", latencyMs);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
private static String extractMessageText(JsonNode message) {
|
||||
JsonNode content = message.path("content");
|
||||
if (content.isTextual()) {
|
||||
return content.asText("");
|
||||
}
|
||||
if (content.isArray()) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (JsonNode part : content) {
|
||||
String text = part.path("text").asText(null);
|
||||
if (text != null) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append('\n');
|
||||
}
|
||||
sb.append(text);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static ObjectNode parseToolArguments(ObjectMapper mapper, String argumentsJson) {
|
||||
try {
|
||||
JsonNode parsed = mapper.readTree(argumentsJson);
|
||||
if (parsed.isObject()) {
|
||||
return (ObjectNode) parsed;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse tool_call arguments as JSON: {0}", e.getMessage());
|
||||
}
|
||||
return mapper.createObjectNode();
|
||||
}
|
||||
|
||||
private static String mapFinishReason(String finishReason) {
|
||||
return "length".equals(finishReason) ? "max_tokens" : "end_turn";
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package io.github.hectorvent.floci.services.bedrockruntime.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpTimeoutException;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Forwards Bedrock Converse requests to any OpenAI-compatible {@code /chat/completions}
|
||||
* endpoint (Ollama, OpenRouter, LiteLLM, vLLM, ...). InvokeModel is not yet supported and
|
||||
* fails fast rather than returning a fabricated response.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ProxyBackend implements BedrockBackend {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ProxyBackend.class);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
// Config is immutable for the process's lifetime, so the mapping string is parsed
|
||||
// once here rather than on every Converse request.
|
||||
private final Map<String, String> modelMapping;
|
||||
|
||||
private final HttpClient httpClient = HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.build();
|
||||
|
||||
@Inject
|
||||
public ProxyBackend(ObjectMapper objectMapper, EmulatorConfig config) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.config = config;
|
||||
this.modelMapping = parseModelMapping(config.services().bedrockRuntime().proxy().modelMapping().orElse(""));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObjectNode converse(String modelId, ObjectNode bedrockRequest) {
|
||||
EmulatorConfig.BedrockProxyConfig proxyConfig = config.services().bedrockRuntime().proxy();
|
||||
String resolvedModel = resolveModel(modelId, proxyConfig);
|
||||
String baseUrl = proxyConfig.url()
|
||||
.filter(url -> !url.isBlank())
|
||||
.orElseThrow(() -> new AwsException("ValidationException",
|
||||
"floci.services.bedrock-runtime.proxy.url is required when backend=proxy.", 400));
|
||||
|
||||
ObjectNode openAiRequest = BedrockOpenAiTranslator.toOpenAiRequest(objectMapper, bedrockRequest, resolvedModel);
|
||||
|
||||
URI uri;
|
||||
HttpRequest.Builder builder;
|
||||
try {
|
||||
uri = URI.create(stripTrailingSlash(baseUrl) + "/chat/completions");
|
||||
builder = HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.timeout(Duration.ofSeconds(proxyConfig.requestTimeoutSeconds()))
|
||||
.header("Content-Type", "application/json");
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationException",
|
||||
"floci.services.bedrock-runtime.proxy.url is not a valid URL: " + e.getMessage(), 400);
|
||||
}
|
||||
proxyConfig.apiKey()
|
||||
.filter(key -> !key.isBlank())
|
||||
.ifPresent(key -> builder.header("Authorization", "Bearer " + key));
|
||||
|
||||
String requestBody;
|
||||
try {
|
||||
requestBody = objectMapper.writeValueAsString(openAiRequest);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalServerException", "Failed to serialize proxy request: " + e.getMessage(), 500);
|
||||
}
|
||||
builder.POST(HttpRequest.BodyPublishers.ofString(requestBody));
|
||||
|
||||
long start = System.nanoTime();
|
||||
HttpResponse<String> response;
|
||||
try {
|
||||
response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
|
||||
} catch (HttpTimeoutException e) {
|
||||
LOG.warnv("Bedrock proxy backend timed out: modelId={0}, url={1}, error={2}", modelId, uri, e.getMessage());
|
||||
throw new AwsException("ModelTimeoutException", "Proxy backend timed out: " + e.getMessage(), 408);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Bedrock proxy backend call failed: modelId={0}, url={1}, error={2}", modelId, uri, e.getMessage());
|
||||
throw new AwsException("ModelErrorException", "Failed to reach proxy backend: " + e.getMessage(), 424);
|
||||
}
|
||||
long latencyMs = (System.nanoTime() - start) / 1_000_000;
|
||||
|
||||
if (response.statusCode() >= 300) {
|
||||
LOG.warnv("Bedrock proxy backend returned HTTP {0}: {1}", response.statusCode(), response.body());
|
||||
throw new AwsException("ModelErrorException",
|
||||
"Proxy backend returned HTTP " + response.statusCode() + ": " + truncate(response.body(), 512),
|
||||
424);
|
||||
}
|
||||
|
||||
JsonNode openAiResponse;
|
||||
try {
|
||||
openAiResponse = objectMapper.readTree(response.body());
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("ModelErrorException", "Proxy backend returned malformed JSON: " + e.getMessage(), 424);
|
||||
}
|
||||
|
||||
return BedrockOpenAiTranslator.toBedrockResponse(objectMapper, openAiResponse, latencyMs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] invokeModel(String modelId, byte[] body) {
|
||||
throw new AwsException("ValidationException",
|
||||
"InvokeModel is not supported by the bedrock-runtime proxy backend; use Converse.", 400);
|
||||
}
|
||||
|
||||
String resolveModel(String bedrockModelId, EmulatorConfig.BedrockProxyConfig proxyConfig) {
|
||||
String mapped = modelMapping.get(bedrockModelId);
|
||||
if (mapped != null) {
|
||||
return mapped;
|
||||
}
|
||||
if (proxyConfig.passthrough()) {
|
||||
return bedrockModelId;
|
||||
}
|
||||
if (proxyConfig.defaultModel().isPresent()) {
|
||||
return proxyConfig.defaultModel().get();
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"No model mapping found for: " + bedrockModelId
|
||||
+ ". Set FLOCI_SERVICES_BEDROCK_RUNTIME_PROXY_MODEL_MAPPING or "
|
||||
+ "FLOCI_SERVICES_BEDROCK_RUNTIME_PROXY_DEFAULT_MODEL", 400);
|
||||
}
|
||||
|
||||
static Map<String, String> parseModelMapping(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
for (String pair : raw.split(",")) {
|
||||
String trimmed = pair.trim();
|
||||
if (trimmed.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
int eq = trimmed.indexOf('=');
|
||||
if (eq <= 0 || eq == trimmed.length() - 1) {
|
||||
LOG.warnv("Ignoring malformed bedrock-runtime proxy model-mapping entry: {0}", trimmed);
|
||||
continue;
|
||||
}
|
||||
result.put(trimmed.substring(0, eq).trim(), trimmed.substring(eq + 1).trim());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String stripTrailingSlash(String url) {
|
||||
return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
|
||||
}
|
||||
|
||||
private static String truncate(String value, int maxLength) {
|
||||
return value != null && value.length() > maxLength ? value.substring(0, maxLength) + "…" : value;
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package io.github.hectorvent.floci.services.bedrockruntime.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
/**
|
||||
* Dummy response builder for Bedrock Runtime. Stateless.
|
||||
* No real model inference: returns a fixed assistant turn plus token usage metadata.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class StubBackend implements BedrockBackend {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public StubBackend(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObjectNode converse(String modelId, ObjectNode bedrockRequest) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
|
||||
ObjectNode output = root.putObject("output");
|
||||
ObjectNode message = output.putObject("message");
|
||||
message.put("role", "assistant");
|
||||
ArrayNode content = message.putArray("content");
|
||||
ObjectNode textBlock = content.addObject();
|
||||
textBlock.put("text", "Floci stub response for model=" + modelId);
|
||||
|
||||
root.put("stopReason", "end_turn");
|
||||
|
||||
ObjectNode usage = root.putObject("usage");
|
||||
usage.put("inputTokens", 10);
|
||||
usage.put("outputTokens", 12);
|
||||
usage.put("totalTokens", 22);
|
||||
|
||||
ObjectNode metrics = root.putObject("metrics");
|
||||
metrics.put("latencyMs", 1);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] invokeModel(String modelId, byte[] body) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
String lower = modelId == null ? "" : modelId.toLowerCase();
|
||||
if (lower.startsWith("anthropic.") || lower.contains(".anthropic.")) {
|
||||
root.put("id", "msg_stub");
|
||||
root.put("type", "message");
|
||||
root.put("role", "assistant");
|
||||
ArrayNode content = root.putArray("content");
|
||||
ObjectNode block = content.addObject();
|
||||
block.put("type", "text");
|
||||
block.put("text", "Floci stub response");
|
||||
root.put("model", modelId);
|
||||
root.put("stop_reason", "end_turn");
|
||||
ObjectNode usage = root.putObject("usage");
|
||||
usage.put("input_tokens", 10);
|
||||
usage.put("output_tokens", 12);
|
||||
} else {
|
||||
// Generic minimal shape for Meta, Mistral, Titan and others.
|
||||
// Bedrock returns provider-specific bodies; callers parse by model family.
|
||||
ArrayNode outputs = root.putArray("outputs");
|
||||
ObjectNode item = outputs.addObject();
|
||||
item.put("text", "Floci stub response");
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsBytes(root);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize InvokeModel response", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user