You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "avichaym (via GitHub)" <gi...@apache.org> on 2026/02/10 16:30:32 UTC
[PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
avichaym opened a new pull request, #534:
URL: https://github.com/apache/flink-agents/pull/534
Linked issue: #523
### Purpose of change
Add Amazon Bedrock as a chat model and embedding model provider for Flink Agents.
- `BedrockChatModelConnection` — Converse API with native tool calling, SigV4 auth
- `BedrockChatModelSetup` — model, temperature, max_tokens configuration
- `BedrockEmbeddingModelConnection` — Titan Text Embeddings V2 with parallel batch embedding
- `BedrockEmbeddingModelSetup` — model, dimensions configuration
New modules: `integrations/chat-models/bedrock/`, `integrations/embedding-models/bedrock/`
### Tests
- Unit tests: `BedrockChatModelConnectionTest` (4), `BedrockChatModelSetupTest` (3), `BedrockEmbeddingModelTest` (4)
- End-to-end validated against real Bedrock with 6 demo applications (single-agent, ReAct tool calling, multi-agent pipeline, RAG, long-term memory, MCP)
### API
No public API changes. New integration modules only.
### Documentation
- [ ] `doc-needed`
- [x] `doc-not-needed`
- [ ] `doc-included`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "wenjin272 (via GitHub)" <gi...@apache.org>.
wenjin272 commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2875758557
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,428 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.RetryExecutor;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+ private final RetryExecutor retryExecutor;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ this.retryExecutor =
+ RetryExecutor.builder()
+ .maxRetries(5)
Review Comment:
Should this be configurable?
##########
integrations/embedding-models/bedrock/src/main/java/org/apache/flink/agents/integrations/embeddingmodels/bedrock/BedrockEmbeddingModelConnection.java:
##########
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.embeddingmodels.bedrock;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.apache.flink.agents.api.RetryExecutor;
+import org.apache.flink.agents.api.embedding.model.BaseEmbeddingModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.function.BiFunction;
+
+/**
+ * Bedrock embedding model connection using Amazon Titan Text Embeddings V2.
+ *
+ * <p>Uses the InvokeModel API to generate embeddings. Supports configurable dimensions (256, 512,
+ * or 1024) and normalization. Since Titan V2 processes one text per API call, batch embedding is
+ * parallelized via a configurable thread pool.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region, defaults to us-east-1
+ * <li><b>model</b> (optional): default model ID, defaults to amazon.titan-embed-text-v2:0
+ * <li><b>embed_concurrency</b> (optional): thread pool size for parallel embedding (default: 4)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @EmbeddingModelConnection
+ * public static ResourceDescriptor bedrockEmbedding() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockEmbeddingModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "amazon.titan-embed-text-v2:0")
+ * .addInitialArgument("embed_concurrency", 8)
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockEmbeddingModelConnection extends BaseEmbeddingModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final String DEFAULT_MODEL = "amazon.titan-embed-text-v2:0";
+
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+ private final ExecutorService embedPool;
+ private final RetryExecutor retryExecutor;
+
+ public BedrockEmbeddingModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ String model = descriptor.getArgument("model");
+ this.defaultModel = (model != null && !model.isBlank()) ? model : DEFAULT_MODEL;
+
+ Integer concurrency = descriptor.getArgument("embed_concurrency");
+ int threads = concurrency != null ? concurrency : 4;
+ this.embedPool = Executors.newFixedThreadPool(threads);
+
+ this.retryExecutor =
+ RetryExecutor.builder()
+ .maxRetries(5)
Review Comment:
ditto
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "avichaym (via GitHub)" <gi...@apache.org>.
avichaym commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2876664541
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,428 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.RetryExecutor;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+ private final RetryExecutor retryExecutor;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ this.retryExecutor =
+ RetryExecutor.builder()
+ .maxRetries(5)
Review Comment:
Made max_retries configurable via the descriptor's initialArguments map, defaulting to 5. Applied to both BedrockChatModelConnection and BedrockEmbeddingModelConnection. See 007b8f3.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "weiqingy (via GitHub)" <gi...@apache.org>.
weiqingy commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2825730461
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ }
+
+ @Override
+ public ChatMessage chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) {
+ try {
+ String modelId = resolveModel(arguments);
+
+ List<ChatMessage> systemMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() == MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+ List<ChatMessage> conversationMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() != MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+
+ ConverseRequest.Builder requestBuilder =
+ ConverseRequest.builder()
+ .modelId(modelId)
+ .messages(mergeMessages(conversationMsgs));
+
+ if (!systemMsgs.isEmpty()) {
+ requestBuilder.system(
+ systemMsgs.stream()
+ .map(m -> SystemContentBlock.builder().text(m.getContent()).build())
+ .collect(Collectors.toList()));
+ }
+
+ if (tools != null && !tools.isEmpty()) {
+ requestBuilder.toolConfig(
+ ToolConfiguration.builder()
+ .tools(
+ tools.stream()
+ .map(this::toBedrockTool)
+ .collect(Collectors.toList()))
+ .build());
+ }
+
+ // Inference config: temperature and max_tokens
+ if (arguments != null) {
+ InferenceConfiguration.Builder inferenceBuilder = null;
+ Object temp = arguments.get("temperature");
+ if (temp instanceof Number) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ inferenceBuilder.temperature(((Number) temp).floatValue());
+ }
+ Object maxTokens = arguments.get("max_tokens");
+ if (maxTokens instanceof Number) {
+ if (inferenceBuilder == null) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ }
+ inferenceBuilder.maxTokens(((Number) maxTokens).intValue());
+ }
+ if (inferenceBuilder != null) {
+ requestBuilder.inferenceConfig(inferenceBuilder.build());
+ }
+ }
+
+ ConverseResponse response = client.converse(requestBuilder.build());
+
+ if (response.usage() != null) {
+ recordTokenMetrics(
+ modelId, response.usage().inputTokens(), response.usage().outputTokens());
+ }
+
+ return convertResponse(response);
+ } catch (Exception e) {
Review Comment:
Bedrock frequently returns ThrottlingException under load. The current code wraps all exceptions into a RuntimeException without retry. It might be worth handling ThrottlingException and ServiceUnavailableException with retry here - or at minimum, preserving the original exception type so callers can distinguish transient from permanent failures. (PR #531 is adding similar retry logic to MCPServer for the same reason.)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "weiqingy (via GitHub)" <gi...@apache.org>.
weiqingy commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2825715040
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ }
+
+ @Override
+ public ChatMessage chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) {
+ try {
+ String modelId = resolveModel(arguments);
+
+ List<ChatMessage> systemMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() == MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+ List<ChatMessage> conversationMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() != MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+
+ ConverseRequest.Builder requestBuilder =
+ ConverseRequest.builder()
+ .modelId(modelId)
+ .messages(mergeMessages(conversationMsgs));
+
+ if (!systemMsgs.isEmpty()) {
+ requestBuilder.system(
+ systemMsgs.stream()
+ .map(m -> SystemContentBlock.builder().text(m.getContent()).build())
+ .collect(Collectors.toList()));
+ }
+
+ if (tools != null && !tools.isEmpty()) {
+ requestBuilder.toolConfig(
+ ToolConfiguration.builder()
+ .tools(
+ tools.stream()
+ .map(this::toBedrockTool)
+ .collect(Collectors.toList()))
+ .build());
+ }
+
+ // Inference config: temperature and max_tokens
+ if (arguments != null) {
+ InferenceConfiguration.Builder inferenceBuilder = null;
+ Object temp = arguments.get("temperature");
+ if (temp instanceof Number) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ inferenceBuilder.temperature(((Number) temp).floatValue());
+ }
+ Object maxTokens = arguments.get("max_tokens");
+ if (maxTokens instanceof Number) {
+ if (inferenceBuilder == null) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ }
+ inferenceBuilder.maxTokens(((Number) maxTokens).intValue());
+ }
+ if (inferenceBuilder != null) {
+ requestBuilder.inferenceConfig(inferenceBuilder.build());
+ }
+ }
+
+ ConverseResponse response = client.converse(requestBuilder.build());
+
+ if (response.usage() != null) {
+ recordTokenMetrics(
+ modelId, response.usage().inputTokens(), response.usage().outputTokens());
+ }
+
+ return convertResponse(response);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to call Bedrock Converse API.", e);
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ this.client.close();
+ }
+
+ private String resolveModel(Map<String, Object> arguments) {
+ String model = arguments != null ? (String) arguments.get("model") : null;
+ if (model == null || model.isBlank()) {
+ model = this.defaultModel;
+ }
+ if (model == null || model.isBlank()) {
+ throw new IllegalArgumentException("No model specified for Bedrock.");
+ }
+ return model;
+ }
+
+ /**
+ * Merge consecutive TOOL messages into a single USER message with multiple toolResult content
+ * blocks, as required by Bedrock Converse API.
+ */
+ private List<Message> mergeMessages(List<ChatMessage> msgs) {
+ List<Message> result = new ArrayList<>();
+ int i = 0;
+ while (i < msgs.size()) {
+ ChatMessage msg = msgs.get(i);
+ if (msg.getRole() == MessageRole.TOOL) {
+ List<ContentBlock> toolResultBlocks = new ArrayList<>();
+ while (i < msgs.size() && msgs.get(i).getRole() == MessageRole.TOOL) {
+ ChatMessage toolMsg = msgs.get(i);
+ String toolCallId = (String) toolMsg.getExtraArgs().get("externalId");
+ toolResultBlocks.add(
+ ContentBlock.fromToolResult(
+ ToolResultBlock.builder()
+ .toolUseId(toolCallId)
+ .content(
+ ToolResultContentBlock.builder()
+ .text(toolMsg.getContent())
+ .build())
+ .build()));
+ i++;
+ }
+ result.add(
+ Message.builder()
+ .role(ConversationRole.USER)
+ .content(toolResultBlocks)
+ .build());
+ } else {
+ result.add(toBedrockMessage(msg));
+ i++;
+ }
+ }
+ return result;
+ }
+
+ private Message toBedrockMessage(ChatMessage msg) {
+ switch (msg.getRole()) {
+ case USER:
+ return Message.builder()
+ .role(ConversationRole.USER)
+ .content(ContentBlock.fromText(msg.getContent()))
+ .build();
+ case ASSISTANT:
+ List<ContentBlock> blocks = new ArrayList<>();
+ if (msg.getContent() != null && !msg.getContent().isEmpty()) {
+ blocks.add(ContentBlock.fromText(msg.getContent()));
+ }
+ if (msg.getToolCalls() != null && !msg.getToolCalls().isEmpty()) {
+ for (Map<String, Object> call : msg.getToolCalls()) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> fn = (Map<String, Object>) call.get("function");
+ String toolUseId = (String) call.get("id");
+ String name = (String) fn.get("name");
+ Object args = fn.get("arguments");
+ blocks.add(
+ ContentBlock.fromToolUse(
+ ToolUseBlock.builder()
+ .toolUseId(toolUseId)
+ .name(name)
+ .input(toDocument(args))
+ .build()));
+ }
+ }
+ return Message.builder().role(ConversationRole.ASSISTANT).content(blocks).build();
+ case TOOL:
+ String toolCallId = (String) msg.getExtraArgs().get("externalId");
+ return Message.builder()
+ .role(ConversationRole.USER)
+ .content(
+ ContentBlock.fromToolResult(
+ ToolResultBlock.builder()
+ .toolUseId(toolCallId)
+ .content(
+ ToolResultContentBlock.builder()
+ .text(msg.getContent())
+ .build())
+ .build()))
+ .build();
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported role for Bedrock: " + msg.getRole());
+ }
+ }
+
+ private software.amazon.awssdk.services.bedrockruntime.model.Tool toBedrockTool(Tool tool) {
+ ToolMetadata meta = tool.getMetadata();
+ ToolSpecification.Builder specBuilder =
+ ToolSpecification.builder().name(meta.getName()).description(meta.getDescription());
+
+ String schema = meta.getInputSchema();
+ if (schema != null && !schema.isBlank()) {
+ try {
+ Map<String, Object> schemaMap =
+ MAPPER.readValue(schema, new TypeReference<Map<String, Object>>() {});
+ specBuilder.inputSchema(ToolInputSchema.fromJson(toDocument(schemaMap)));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to parse tool schema.", e);
+ }
+ }
+
+ return software.amazon.awssdk.services.bedrockruntime.model.Tool.builder()
+ .toolSpec(specBuilder.build())
+ .build();
+ }
+
+ private ChatMessage convertResponse(ConverseResponse response) {
+ List<ContentBlock> outputBlocks = response.output().message().content();
+ StringBuilder textContent = new StringBuilder();
+ List<Map<String, Object>> toolCalls = new ArrayList<>();
+
+ for (ContentBlock block : outputBlocks) {
+ if (block.text() != null) {
+ textContent.append(block.text());
+ }
+ if (block.toolUse() != null) {
+ ToolUseBlock toolUse = block.toolUse();
+ Map<String, Object> callMap = new LinkedHashMap<>();
+ callMap.put("id", toolUse.toolUseId());
+ callMap.put("type", "function");
+ Map<String, Object> fnMap = new LinkedHashMap<>();
+ fnMap.put("name", toolUse.name());
+ fnMap.put("arguments", documentToMap(toolUse.input()));
+ callMap.put("function", fnMap);
+ callMap.put("original_id", toolUse.toolUseId());
+ toolCalls.add(callMap);
+ }
+ }
+
+ ChatMessage result = ChatMessage.assistant(stripMarkdownFences(textContent.toString()));
+ if (!toolCalls.isEmpty()) {
+ result.setToolCalls(toolCalls);
+ }
+ return result;
+ }
+
+ /**
+ * Strip markdown code fences and extract JSON from mixed text responses. Some Bedrock models
+ * wrap JSON output in markdown fences or add prose around it.
+ *
+ * <p>Note: Unlike OpenAI's strict mode, Bedrock models do not guarantee pure JSON output. The
+ * flink-agents framework's {@code ChatModelAction.generateStructuredOutput} expects clean JSON,
+ * so this extraction is necessary at the connection layer.
+ */
+ private static String stripMarkdownFences(String text) {
+ if (text == null) return null;
+ String trimmed = text.trim();
+ if (trimmed.startsWith("```")) {
+ int firstNewline = trimmed.indexOf('\n');
+ if (firstNewline >= 0) {
+ trimmed = trimmed.substring(firstNewline + 1);
+ }
+ if (trimmed.endsWith("```")) {
+ trimmed = trimmed.substring(0, trimmed.length() - 3).trim();
+ }
+ return trimmed;
+ }
+ int start = trimmed.indexOf('{');
Review Comment:
Question: This fallback path extracts the substring between the first '{'and last '}' from any response. If the model returns a normal text response that happens to contain braces (e.g., "Use the format {key: value} for config"), this would discard everything outside the braces.
Should this extraction only apply when structured output is expected (i.e., when an outputSchema is provided), rather than on every response? The other integrations (OpenAI, Anthropic) don't modify the text content at the connection layer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "avichaym (via GitHub)" <gi...@apache.org>.
avichaym commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2826164308
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ }
+
+ @Override
+ public ChatMessage chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) {
+ try {
+ String modelId = resolveModel(arguments);
+
+ List<ChatMessage> systemMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() == MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+ List<ChatMessage> conversationMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() != MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+
+ ConverseRequest.Builder requestBuilder =
+ ConverseRequest.builder()
+ .modelId(modelId)
+ .messages(mergeMessages(conversationMsgs));
+
+ if (!systemMsgs.isEmpty()) {
+ requestBuilder.system(
+ systemMsgs.stream()
+ .map(m -> SystemContentBlock.builder().text(m.getContent()).build())
+ .collect(Collectors.toList()));
+ }
+
+ if (tools != null && !tools.isEmpty()) {
+ requestBuilder.toolConfig(
+ ToolConfiguration.builder()
+ .tools(
+ tools.stream()
+ .map(this::toBedrockTool)
+ .collect(Collectors.toList()))
+ .build());
+ }
+
+ // Inference config: temperature and max_tokens
+ if (arguments != null) {
+ InferenceConfiguration.Builder inferenceBuilder = null;
+ Object temp = arguments.get("temperature");
+ if (temp instanceof Number) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ inferenceBuilder.temperature(((Number) temp).floatValue());
+ }
+ Object maxTokens = arguments.get("max_tokens");
+ if (maxTokens instanceof Number) {
+ if (inferenceBuilder == null) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ }
+ inferenceBuilder.maxTokens(((Number) maxTokens).intValue());
+ }
+ if (inferenceBuilder != null) {
+ requestBuilder.inferenceConfig(inferenceBuilder.build());
+ }
+ }
+
+ ConverseResponse response = client.converse(requestBuilder.build());
+
+ if (response.usage() != null) {
+ recordTokenMetrics(
+ modelId, response.usage().inputTokens(), response.usage().outputTokens());
+ }
+
+ return convertResponse(response);
+ } catch (Exception e) {
Review Comment:
Added exponential backoff retry around client.converse(), consistent with the retry already in BedrockEmbeddingModelConnection in this same PR.
MAX_RETRIES=5, backoff with jitter (2^attempt 200ms (0.5 + random 0.5)), covering ThrottlingException, ServiceUnavailableException, ModelErrorException, 429, and 503. Non-retryable exceptions still fail immediately with the original exception preserved as the cause.
Fixed in 6d50c47
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "avichaym (via GitHub)" <gi...@apache.org>.
avichaym commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2826159295
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ }
+
+ @Override
+ public ChatMessage chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) {
+ try {
+ String modelId = resolveModel(arguments);
+
+ List<ChatMessage> systemMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() == MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+ List<ChatMessage> conversationMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() != MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+
+ ConverseRequest.Builder requestBuilder =
+ ConverseRequest.builder()
+ .modelId(modelId)
+ .messages(mergeMessages(conversationMsgs));
+
+ if (!systemMsgs.isEmpty()) {
+ requestBuilder.system(
+ systemMsgs.stream()
+ .map(m -> SystemContentBlock.builder().text(m.getContent()).build())
+ .collect(Collectors.toList()));
+ }
+
+ if (tools != null && !tools.isEmpty()) {
+ requestBuilder.toolConfig(
+ ToolConfiguration.builder()
+ .tools(
+ tools.stream()
+ .map(this::toBedrockTool)
+ .collect(Collectors.toList()))
+ .build());
+ }
+
+ // Inference config: temperature and max_tokens
+ if (arguments != null) {
+ InferenceConfiguration.Builder inferenceBuilder = null;
+ Object temp = arguments.get("temperature");
+ if (temp instanceof Number) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ inferenceBuilder.temperature(((Number) temp).floatValue());
+ }
+ Object maxTokens = arguments.get("max_tokens");
+ if (maxTokens instanceof Number) {
+ if (inferenceBuilder == null) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ }
+ inferenceBuilder.maxTokens(((Number) maxTokens).intValue());
+ }
+ if (inferenceBuilder != null) {
+ requestBuilder.inferenceConfig(inferenceBuilder.build());
+ }
+ }
+
+ ConverseResponse response = client.converse(requestBuilder.build());
+
+ if (response.usage() != null) {
+ recordTokenMetrics(
+ modelId, response.usage().inputTokens(), response.usage().outputTokens());
+ }
+
+ return convertResponse(response);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to call Bedrock Converse API.", e);
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ this.client.close();
+ }
+
+ private String resolveModel(Map<String, Object> arguments) {
+ String model = arguments != null ? (String) arguments.get("model") : null;
+ if (model == null || model.isBlank()) {
+ model = this.defaultModel;
+ }
+ if (model == null || model.isBlank()) {
+ throw new IllegalArgumentException("No model specified for Bedrock.");
+ }
+ return model;
+ }
+
+ /**
+ * Merge consecutive TOOL messages into a single USER message with multiple toolResult content
+ * blocks, as required by Bedrock Converse API.
+ */
+ private List<Message> mergeMessages(List<ChatMessage> msgs) {
+ List<Message> result = new ArrayList<>();
+ int i = 0;
+ while (i < msgs.size()) {
+ ChatMessage msg = msgs.get(i);
+ if (msg.getRole() == MessageRole.TOOL) {
+ List<ContentBlock> toolResultBlocks = new ArrayList<>();
+ while (i < msgs.size() && msgs.get(i).getRole() == MessageRole.TOOL) {
+ ChatMessage toolMsg = msgs.get(i);
+ String toolCallId = (String) toolMsg.getExtraArgs().get("externalId");
+ toolResultBlocks.add(
+ ContentBlock.fromToolResult(
+ ToolResultBlock.builder()
+ .toolUseId(toolCallId)
+ .content(
+ ToolResultContentBlock.builder()
+ .text(toolMsg.getContent())
+ .build())
+ .build()));
+ i++;
+ }
+ result.add(
+ Message.builder()
+ .role(ConversationRole.USER)
+ .content(toolResultBlocks)
+ .build());
+ } else {
+ result.add(toBedrockMessage(msg));
+ i++;
+ }
+ }
+ return result;
+ }
+
+ private Message toBedrockMessage(ChatMessage msg) {
+ switch (msg.getRole()) {
+ case USER:
+ return Message.builder()
+ .role(ConversationRole.USER)
+ .content(ContentBlock.fromText(msg.getContent()))
+ .build();
+ case ASSISTANT:
+ List<ContentBlock> blocks = new ArrayList<>();
+ if (msg.getContent() != null && !msg.getContent().isEmpty()) {
+ blocks.add(ContentBlock.fromText(msg.getContent()));
+ }
+ if (msg.getToolCalls() != null && !msg.getToolCalls().isEmpty()) {
+ for (Map<String, Object> call : msg.getToolCalls()) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> fn = (Map<String, Object>) call.get("function");
+ String toolUseId = (String) call.get("id");
+ String name = (String) fn.get("name");
+ Object args = fn.get("arguments");
+ blocks.add(
+ ContentBlock.fromToolUse(
+ ToolUseBlock.builder()
+ .toolUseId(toolUseId)
+ .name(name)
+ .input(toDocument(args))
+ .build()));
+ }
+ }
+ return Message.builder().role(ConversationRole.ASSISTANT).content(blocks).build();
+ case TOOL:
+ String toolCallId = (String) msg.getExtraArgs().get("externalId");
+ return Message.builder()
+ .role(ConversationRole.USER)
+ .content(
+ ContentBlock.fromToolResult(
+ ToolResultBlock.builder()
+ .toolUseId(toolCallId)
+ .content(
+ ToolResultContentBlock.builder()
+ .text(msg.getContent())
+ .build())
+ .build()))
+ .build();
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported role for Bedrock: " + msg.getRole());
+ }
+ }
+
+ private software.amazon.awssdk.services.bedrockruntime.model.Tool toBedrockTool(Tool tool) {
+ ToolMetadata meta = tool.getMetadata();
+ ToolSpecification.Builder specBuilder =
+ ToolSpecification.builder().name(meta.getName()).description(meta.getDescription());
+
+ String schema = meta.getInputSchema();
+ if (schema != null && !schema.isBlank()) {
+ try {
+ Map<String, Object> schemaMap =
+ MAPPER.readValue(schema, new TypeReference<Map<String, Object>>() {});
+ specBuilder.inputSchema(ToolInputSchema.fromJson(toDocument(schemaMap)));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to parse tool schema.", e);
+ }
+ }
+
+ return software.amazon.awssdk.services.bedrockruntime.model.Tool.builder()
+ .toolSpec(specBuilder.build())
+ .build();
+ }
+
+ private ChatMessage convertResponse(ConverseResponse response) {
+ List<ContentBlock> outputBlocks = response.output().message().content();
+ StringBuilder textContent = new StringBuilder();
+ List<Map<String, Object>> toolCalls = new ArrayList<>();
+
+ for (ContentBlock block : outputBlocks) {
+ if (block.text() != null) {
+ textContent.append(block.text());
+ }
+ if (block.toolUse() != null) {
+ ToolUseBlock toolUse = block.toolUse();
+ Map<String, Object> callMap = new LinkedHashMap<>();
+ callMap.put("id", toolUse.toolUseId());
+ callMap.put("type", "function");
+ Map<String, Object> fnMap = new LinkedHashMap<>();
+ fnMap.put("name", toolUse.name());
+ fnMap.put("arguments", documentToMap(toolUse.input()));
+ callMap.put("function", fnMap);
+ callMap.put("original_id", toolUse.toolUseId());
+ toolCalls.add(callMap);
+ }
+ }
+
+ ChatMessage result = ChatMessage.assistant(stripMarkdownFences(textContent.toString()));
+ if (!toolCalls.isEmpty()) {
+ result.setToolCalls(toolCalls);
+ }
+ return result;
+ }
+
+ /**
+ * Strip markdown code fences and extract JSON from mixed text responses. Some Bedrock models
+ * wrap JSON output in markdown fences or add prose around it.
+ *
+ * <p>Note: Unlike OpenAI's strict mode, Bedrock models do not guarantee pure JSON output. The
+ * flink-agents framework's {@code ChatModelAction.generateStructuredOutput} expects clean JSON,
+ * so this extraction is necessary at the connection layer.
+ */
+ private static String stripMarkdownFences(String text) {
+ if (text == null) return null;
+ String trimmed = text.trim();
+ if (trimmed.startsWith("```")) {
+ int firstNewline = trimmed.indexOf('\n');
+ if (firstNewline >= 0) {
+ trimmed = trimmed.substring(firstNewline + 1);
+ }
+ if (trimmed.endsWith("```")) {
+ trimmed = trimmed.substring(0, trimmed.length() - 3).trim();
+ }
+ return trimmed;
+ }
+ int start = trimmed.indexOf('{');
Review Comment:
Good catch. Removed the {...} extraction fallback entirely — stripMarkdownFences now only strips markdown code fences ( json... ), which is a lossless operation. Additionally, fence stripping is now
only applied to non-tool-call responses, since tool-call responses should pass through unmodified.
The connection layer doesn't have visibility into whether outputSchema is set , so scoping it that way would require changing the BaseChatModelConnection interface.
Removing the extraction altogether addresses the core concern — normal text responses containing braces are no longer corrupted.
Also Added 5 unit tests for stripMarkdownFences covering: text with braces preserved, clean JSON passthrough, json fence stripping, plain fence stripping, and null handling.
> Fixed in 6d50c47
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "xintongsong (via GitHub)" <gi...@apache.org>.
xintongsong merged PR #534:
URL: https://github.com/apache/flink-agents/pull/534
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "weiqingy (via GitHub)" <gi...@apache.org>.
weiqingy commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2825715040
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ }
+
+ @Override
+ public ChatMessage chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) {
+ try {
+ String modelId = resolveModel(arguments);
+
+ List<ChatMessage> systemMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() == MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+ List<ChatMessage> conversationMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() != MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+
+ ConverseRequest.Builder requestBuilder =
+ ConverseRequest.builder()
+ .modelId(modelId)
+ .messages(mergeMessages(conversationMsgs));
+
+ if (!systemMsgs.isEmpty()) {
+ requestBuilder.system(
+ systemMsgs.stream()
+ .map(m -> SystemContentBlock.builder().text(m.getContent()).build())
+ .collect(Collectors.toList()));
+ }
+
+ if (tools != null && !tools.isEmpty()) {
+ requestBuilder.toolConfig(
+ ToolConfiguration.builder()
+ .tools(
+ tools.stream()
+ .map(this::toBedrockTool)
+ .collect(Collectors.toList()))
+ .build());
+ }
+
+ // Inference config: temperature and max_tokens
+ if (arguments != null) {
+ InferenceConfiguration.Builder inferenceBuilder = null;
+ Object temp = arguments.get("temperature");
+ if (temp instanceof Number) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ inferenceBuilder.temperature(((Number) temp).floatValue());
+ }
+ Object maxTokens = arguments.get("max_tokens");
+ if (maxTokens instanceof Number) {
+ if (inferenceBuilder == null) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ }
+ inferenceBuilder.maxTokens(((Number) maxTokens).intValue());
+ }
+ if (inferenceBuilder != null) {
+ requestBuilder.inferenceConfig(inferenceBuilder.build());
+ }
+ }
+
+ ConverseResponse response = client.converse(requestBuilder.build());
+
+ if (response.usage() != null) {
+ recordTokenMetrics(
+ modelId, response.usage().inputTokens(), response.usage().outputTokens());
+ }
+
+ return convertResponse(response);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to call Bedrock Converse API.", e);
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ this.client.close();
+ }
+
+ private String resolveModel(Map<String, Object> arguments) {
+ String model = arguments != null ? (String) arguments.get("model") : null;
+ if (model == null || model.isBlank()) {
+ model = this.defaultModel;
+ }
+ if (model == null || model.isBlank()) {
+ throw new IllegalArgumentException("No model specified for Bedrock.");
+ }
+ return model;
+ }
+
+ /**
+ * Merge consecutive TOOL messages into a single USER message with multiple toolResult content
+ * blocks, as required by Bedrock Converse API.
+ */
+ private List<Message> mergeMessages(List<ChatMessage> msgs) {
+ List<Message> result = new ArrayList<>();
+ int i = 0;
+ while (i < msgs.size()) {
+ ChatMessage msg = msgs.get(i);
+ if (msg.getRole() == MessageRole.TOOL) {
+ List<ContentBlock> toolResultBlocks = new ArrayList<>();
+ while (i < msgs.size() && msgs.get(i).getRole() == MessageRole.TOOL) {
+ ChatMessage toolMsg = msgs.get(i);
+ String toolCallId = (String) toolMsg.getExtraArgs().get("externalId");
+ toolResultBlocks.add(
+ ContentBlock.fromToolResult(
+ ToolResultBlock.builder()
+ .toolUseId(toolCallId)
+ .content(
+ ToolResultContentBlock.builder()
+ .text(toolMsg.getContent())
+ .build())
+ .build()));
+ i++;
+ }
+ result.add(
+ Message.builder()
+ .role(ConversationRole.USER)
+ .content(toolResultBlocks)
+ .build());
+ } else {
+ result.add(toBedrockMessage(msg));
+ i++;
+ }
+ }
+ return result;
+ }
+
+ private Message toBedrockMessage(ChatMessage msg) {
+ switch (msg.getRole()) {
+ case USER:
+ return Message.builder()
+ .role(ConversationRole.USER)
+ .content(ContentBlock.fromText(msg.getContent()))
+ .build();
+ case ASSISTANT:
+ List<ContentBlock> blocks = new ArrayList<>();
+ if (msg.getContent() != null && !msg.getContent().isEmpty()) {
+ blocks.add(ContentBlock.fromText(msg.getContent()));
+ }
+ if (msg.getToolCalls() != null && !msg.getToolCalls().isEmpty()) {
+ for (Map<String, Object> call : msg.getToolCalls()) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> fn = (Map<String, Object>) call.get("function");
+ String toolUseId = (String) call.get("id");
+ String name = (String) fn.get("name");
+ Object args = fn.get("arguments");
+ blocks.add(
+ ContentBlock.fromToolUse(
+ ToolUseBlock.builder()
+ .toolUseId(toolUseId)
+ .name(name)
+ .input(toDocument(args))
+ .build()));
+ }
+ }
+ return Message.builder().role(ConversationRole.ASSISTANT).content(blocks).build();
+ case TOOL:
+ String toolCallId = (String) msg.getExtraArgs().get("externalId");
+ return Message.builder()
+ .role(ConversationRole.USER)
+ .content(
+ ContentBlock.fromToolResult(
+ ToolResultBlock.builder()
+ .toolUseId(toolCallId)
+ .content(
+ ToolResultContentBlock.builder()
+ .text(msg.getContent())
+ .build())
+ .build()))
+ .build();
+ default:
+ throw new IllegalArgumentException(
+ "Unsupported role for Bedrock: " + msg.getRole());
+ }
+ }
+
+ private software.amazon.awssdk.services.bedrockruntime.model.Tool toBedrockTool(Tool tool) {
+ ToolMetadata meta = tool.getMetadata();
+ ToolSpecification.Builder specBuilder =
+ ToolSpecification.builder().name(meta.getName()).description(meta.getDescription());
+
+ String schema = meta.getInputSchema();
+ if (schema != null && !schema.isBlank()) {
+ try {
+ Map<String, Object> schemaMap =
+ MAPPER.readValue(schema, new TypeReference<Map<String, Object>>() {});
+ specBuilder.inputSchema(ToolInputSchema.fromJson(toDocument(schemaMap)));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to parse tool schema.", e);
+ }
+ }
+
+ return software.amazon.awssdk.services.bedrockruntime.model.Tool.builder()
+ .toolSpec(specBuilder.build())
+ .build();
+ }
+
+ private ChatMessage convertResponse(ConverseResponse response) {
+ List<ContentBlock> outputBlocks = response.output().message().content();
+ StringBuilder textContent = new StringBuilder();
+ List<Map<String, Object>> toolCalls = new ArrayList<>();
+
+ for (ContentBlock block : outputBlocks) {
+ if (block.text() != null) {
+ textContent.append(block.text());
+ }
+ if (block.toolUse() != null) {
+ ToolUseBlock toolUse = block.toolUse();
+ Map<String, Object> callMap = new LinkedHashMap<>();
+ callMap.put("id", toolUse.toolUseId());
+ callMap.put("type", "function");
+ Map<String, Object> fnMap = new LinkedHashMap<>();
+ fnMap.put("name", toolUse.name());
+ fnMap.put("arguments", documentToMap(toolUse.input()));
+ callMap.put("function", fnMap);
+ callMap.put("original_id", toolUse.toolUseId());
+ toolCalls.add(callMap);
+ }
+ }
+
+ ChatMessage result = ChatMessage.assistant(stripMarkdownFences(textContent.toString()));
+ if (!toolCalls.isEmpty()) {
+ result.setToolCalls(toolCalls);
+ }
+ return result;
+ }
+
+ /**
+ * Strip markdown code fences and extract JSON from mixed text responses. Some Bedrock models
+ * wrap JSON output in markdown fences or add prose around it.
+ *
+ * <p>Note: Unlike OpenAI's strict mode, Bedrock models do not guarantee pure JSON output. The
+ * flink-agents framework's {@code ChatModelAction.generateStructuredOutput} expects clean JSON,
+ * so this extraction is necessary at the connection layer.
+ */
+ private static String stripMarkdownFences(String text) {
+ if (text == null) return null;
+ String trimmed = text.trim();
+ if (trimmed.startsWith("```")) {
+ int firstNewline = trimmed.indexOf('\n');
+ if (firstNewline >= 0) {
+ trimmed = trimmed.substring(firstNewline + 1);
+ }
+ if (trimmed.endsWith("```")) {
+ trimmed = trimmed.substring(0, trimmed.length() - 3).trim();
+ }
+ return trimmed;
+ }
+ int start = trimmed.indexOf('{');
Review Comment:
This fallback path extracts the substring between the first '{'and last '}' from any response. If the model returns a normal text response that happens to contain braces (e.g., "Use the format {key: value} for config"), this would discard everything outside the braces.
Should this extraction only apply when structured output is expected (i.e., when an outputSchema is provided), rather than on every response? The other integrations (OpenAI, Anthropic) don't modify the text content at the connection layer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "weiqingy (via GitHub)" <gi...@apache.org>.
weiqingy commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2825730461
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ }
+
+ @Override
+ public ChatMessage chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) {
+ try {
+ String modelId = resolveModel(arguments);
+
+ List<ChatMessage> systemMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() == MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+ List<ChatMessage> conversationMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() != MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+
+ ConverseRequest.Builder requestBuilder =
+ ConverseRequest.builder()
+ .modelId(modelId)
+ .messages(mergeMessages(conversationMsgs));
+
+ if (!systemMsgs.isEmpty()) {
+ requestBuilder.system(
+ systemMsgs.stream()
+ .map(m -> SystemContentBlock.builder().text(m.getContent()).build())
+ .collect(Collectors.toList()));
+ }
+
+ if (tools != null && !tools.isEmpty()) {
+ requestBuilder.toolConfig(
+ ToolConfiguration.builder()
+ .tools(
+ tools.stream()
+ .map(this::toBedrockTool)
+ .collect(Collectors.toList()))
+ .build());
+ }
+
+ // Inference config: temperature and max_tokens
+ if (arguments != null) {
+ InferenceConfiguration.Builder inferenceBuilder = null;
+ Object temp = arguments.get("temperature");
+ if (temp instanceof Number) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ inferenceBuilder.temperature(((Number) temp).floatValue());
+ }
+ Object maxTokens = arguments.get("max_tokens");
+ if (maxTokens instanceof Number) {
+ if (inferenceBuilder == null) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ }
+ inferenceBuilder.maxTokens(((Number) maxTokens).intValue());
+ }
+ if (inferenceBuilder != null) {
+ requestBuilder.inferenceConfig(inferenceBuilder.build());
+ }
+ }
+
+ ConverseResponse response = client.converse(requestBuilder.build());
+
+ if (response.usage() != null) {
+ recordTokenMetrics(
+ modelId, response.usage().inputTokens(), response.usage().outputTokens());
+ }
+
+ return convertResponse(response);
+ } catch (Exception e) {
Review Comment:
Bedrock frequently returns ThrottlingException under load. The current code wraps all exceptions into a
RuntimeException without retry. It might be worth handling ThrottlingException and ServiceUnavailableException with a similar retry here - or at minimum, preserving the original exception type so callers can distinguish transient from permanent failures. (e.g., Given that PR #531 is adding retry logic to MCPServer for the similar reason)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-AGENTS-523] Add Amazon Bedrock chat model and embedding model integrations [flink-agents]
Posted by "avichaym (via GitHub)" <gi...@apache.org>.
avichaym commented on code in PR #534:
URL: https://github.com/apache/flink-agents/pull/534#discussion_r2872106499
##########
integrations/chat-models/bedrock/src/main/java/org/apache/flink/agents/integrations/chatmodels/bedrock/BedrockChatModelConnection.java:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.integrations.chatmodels.bedrock;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.api.tools.ToolMetadata;
+import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
+import software.amazon.awssdk.core.SdkNumber;
+import software.amazon.awssdk.core.document.Document;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
+import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
+import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
+import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.Message;
+import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolConfiguration;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolInputSchema;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
+import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+
+/**
+ * Bedrock Converse API chat model connection for flink-agents.
+ *
+ * <p>Uses the Converse API which provides a unified interface across all Bedrock models with native
+ * tool calling support. Authentication is handled via SigV4 using the default AWS credentials
+ * chain.
+ *
+ * <p>Future work: support reasoning content blocks (Claude extended thinking), citation blocks, and
+ * image/document content blocks.
+ *
+ * <p>Supported connection parameters:
+ *
+ * <ul>
+ * <li><b>region</b> (optional): AWS region (defaults to us-east-1)
+ * <li><b>model</b> (optional): Default model ID (e.g. us.anthropic.claude-sonnet-4-20250514-v1:0)
+ * </ul>
+ *
+ * <p>Example usage:
+ *
+ * <pre>{@code
+ * @ChatModelConnection
+ * public static ResourceDescriptor bedrockConnection() {
+ * return ResourceDescriptor.Builder.newBuilder(BedrockChatModelConnection.class.getName())
+ * .addInitialArgument("region", "us-east-1")
+ * .addInitialArgument("model", "us.anthropic.claude-sonnet-4-20250514-v1:0")
+ * .build();
+ * }
+ * }</pre>
+ */
+public class BedrockChatModelConnection extends BaseChatModelConnection {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private final BedrockRuntimeClient client;
+ private final String defaultModel;
+
+ public BedrockChatModelConnection(
+ ResourceDescriptor descriptor, BiFunction<String, ResourceType, Resource> getResource) {
+ super(descriptor, getResource);
+
+ String region = descriptor.getArgument("region");
+ if (region == null || region.isBlank()) {
+ region = "us-east-1";
+ }
+
+ this.client =
+ BedrockRuntimeClient.builder()
+ .region(Region.of(region))
+ .credentialsProvider(DefaultCredentialsProvider.create())
+ .build();
+
+ this.defaultModel = descriptor.getArgument("model");
+ }
+
+ @Override
+ public ChatMessage chat(
+ List<ChatMessage> messages, List<Tool> tools, Map<String, Object> arguments) {
+ try {
+ String modelId = resolveModel(arguments);
+
+ List<ChatMessage> systemMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() == MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+ List<ChatMessage> conversationMsgs =
+ messages.stream()
+ .filter(m -> m.getRole() != MessageRole.SYSTEM)
+ .collect(Collectors.toList());
+
+ ConverseRequest.Builder requestBuilder =
+ ConverseRequest.builder()
+ .modelId(modelId)
+ .messages(mergeMessages(conversationMsgs));
+
+ if (!systemMsgs.isEmpty()) {
+ requestBuilder.system(
+ systemMsgs.stream()
+ .map(m -> SystemContentBlock.builder().text(m.getContent()).build())
+ .collect(Collectors.toList()));
+ }
+
+ if (tools != null && !tools.isEmpty()) {
+ requestBuilder.toolConfig(
+ ToolConfiguration.builder()
+ .tools(
+ tools.stream()
+ .map(this::toBedrockTool)
+ .collect(Collectors.toList()))
+ .build());
+ }
+
+ // Inference config: temperature and max_tokens
+ if (arguments != null) {
+ InferenceConfiguration.Builder inferenceBuilder = null;
+ Object temp = arguments.get("temperature");
+ if (temp instanceof Number) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ inferenceBuilder.temperature(((Number) temp).floatValue());
+ }
+ Object maxTokens = arguments.get("max_tokens");
+ if (maxTokens instanceof Number) {
+ if (inferenceBuilder == null) {
+ inferenceBuilder = InferenceConfiguration.builder();
+ }
+ inferenceBuilder.maxTokens(((Number) maxTokens).intValue());
+ }
+ if (inferenceBuilder != null) {
+ requestBuilder.inferenceConfig(inferenceBuilder.build());
+ }
+ }
+
+ ConverseResponse response = client.converse(requestBuilder.build());
+
+ if (response.usage() != null) {
+ recordTokenMetrics(
+ modelId, response.usage().inputTokens(), response.usage().outputTokens());
+ }
+
+ return convertResponse(response);
+ } catch (Exception e) {
Review Comment:
Thank you @wenjin272 and @xintongsong , Adopted the unified RetryExecutor from PR #531. Both BedrockChatModelConnection and BedrockEmbeddingModelConnection now use RetryExecutor.builder() with a Bedrock-specific retryablePredicate covering ThrottlingException, ServiceUnavailableException, ModelErrorException, 429, and 503. The manual retry loops are removed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org