[PR #3714] [MERGED] Refactor AWS Bedrock Provider for Multi-modal Support & Correct Token Limits #4369

Closed
opened 2026-02-22 18:35:41 -05:00 by yindo · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Mintplex-Labs/anything-llm/pull/3714
Author: @tristan-stahnke-GPS
Created: 4/24/2025
Status: Merged
Merged: 5/6/2025
Merged by: @timothycarambat

Base: masterHead: fix-aws-bedrock


📝 Commits (10+)

  • 12b5e03 Fixed two primary issues discovered while using AWS Bedrock with Anthropic Claude Sonnet models:
  • 828d218 Merge remote-tracking branch 'origin/master' into fix-aws-bedrock
  • 78a6ce3 Ran yarn lint
  • b17c69c Updated .env.example to have aws bedrock examples too
  • 33872db Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock
  • fb00508 Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock
  • ce64a1e Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock
  • 060c4c4 Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock
  • b389b0d Merge branch 'master' into fix-aws-bedrock
  • b54b229 Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock

📊 Changes

7 files changed (+624 additions, -224 deletions)

View changed files

📝 docker/.env.example (+3 -0)
📝 frontend/src/components/LLMSelection/AwsBedrockLLMOptions/index.jsx (+17 -1)
📝 server/.env.example (+10 -0)
📝 server/models/systemSettings.js (+4 -1)
📝 server/utils/AiProviders/bedrock/index.js (+518 -222)
server/utils/AiProviders/bedrock/utils.js (+68 -0)
📝 server/utils/helpers/updateENV.js (+4 -0)

📄 Description

Pull Request Type

  • 🐛 fix
  • ♻️ refactor

What is in this change?

This PR significantly refactors the AWSBedrockLLM provider (server/utils/AiProviders/bedrock/index.js) to:

  • Enable Multi-modal Input: Correctly implement support for sending image attachments alongside text prompts to compatible Bedrock models using the Converse API.
  • Fix Max Tokens Error: Address the ValidationException caused by incorrectly using the total context window limit for the maximum output tokens parameter in API calls.
  • Improve Code Quality: Enhance clarity, maintainability, and error handling.

Additional Information

The previous version of the Bedrock provider had two major issues:

No Multi-modal Support: The #generateContent function responsible for handling message attachments was unimplemented or commented out. This prevented users from sending images to multi-modal Bedrock models (like Claude 3).

Incorrect maxTokens Usage: The promptWindowLimit() function (reading AWS_BEDROCK_LLM_MODEL_TOKEN_LIMIT) was used to set the inferenceConfig.maxTokens parameter in API calls. This value represents the total context window, which is often much larger than the maximum number of tokens a model can generate in a single output. This led to ValidationException errors when the configured context window exceeded the model's specific output limit (e.g., sending 131k when the model's output limit was 8192).

Detailed Changes:

Multi-modal Input Implementation (#generateContent & Helpers)
Implemented #generateContent:

  • This private method now correctly processes both userPrompt (text) and attachments (images).

Added getImageFormatFromMime Helper:

  • Parses MIME types (e.g., image/png) from attachments.
  • Extracts the format (png).
  • Normalizes jpg to jpeg.
  • Validates the format against SUPPORTED_BEDROCK_IMAGE_FORMATS (jpeg, png, gif, webp).

Added Base64 Data URI Stripping:

  • Logic within #generateContent now automatically removes the data:image/...;base64, prefix from attachment.contentString before decoding.

Added base64ToUint8Array Helper:

  • Decodes the pure base64 string into a Uint8Array using atob() and charCodeAt(). This method was chosen to closely match the technique observed in previous Langchain JS implementations.
  • Formatted Image Blocks: #generateContent now constructs image blocks in the precise format required by the Bedrock Converse API: { image: { format: "...", source: { bytes: ... } } }.
  • Robustness: Added checks for invalid attachment objects and handles potential errors during base64 decoding, logging warnings/errors and skipping problematic attachments. Ensures the final content array sent to the API is never empty.

Output Token Limit Correction (getMaxOutputTokens & API Calls)
Introduced DEFAULT_MAX_OUTPUT_TOKENS:

  • Defined a constant (4096) as a safe default for the maximum number of tokens to generate in a response.

Added getMaxOutputTokens Method:

  • Reads the optional AWS_BEDROCK_LLM_MAX_OUTPUT_TOKENS environment variable.
  • If the env var is set and valid, it uses that value.
  • Otherwise, it falls back to DEFAULT_MAX_OUTPUT_TOKENS.
  • This clearly separates the output limit from the total context window limit.

Updated API Calls (getChatCompletion, streamGetChatCompletion):

  • Modified the inferenceConfig in both ConverseCommand and ConverseStreamCommand to use the value returned by this.getMaxOutputTokens() for the maxTokens parameter.
  • This ensures the requested output length respects the specific model's generation capabilities, fixing the ValidationException.
  • Clarified promptWindowLimit: Renamed the static function back to promptWindowLimit (from the temporary getContextWindowLimit) for consistency. Added comments clarifying that this function reads AWS_BEDROCK_LLM_MODEL_TOKEN_LIMIT and represents the total context window, primarily used for calculating input limits (this.limits).

Prompt Construction (constructPrompt)

  • Now correctly utilizes the implemented #generateContent to format messages containing text and/or images for both chat history and the final user prompt.
  • Ensures system prompts (both real and simulated for noSystemPromptModels) are generated without attachments.
  • Improved handling of potentially missing/invalid attachments arrays in history messages.

API Call Structure

  • Correctly separates the system content block from the main messages array (containing only user/assistant turns) when calling ConverseCommand and ConverseStreamCommand, adhering to the API's expected structure.

Code Quality and Refinements

  • Added/improved JSDoc comments for all major functions and helpers, explaining parameters, return values, and logic.
    Introduced constants for better maintainability (SUPPORTED_BEDROCK_IMAGE_FORMATS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_CONTEXT_WINDOW_TOKENS).
  • Refined error messages, particularly for the maxTokens validation error, providing more context to the user.
  • Improved validation of environment variables in the constructor.
  • Minor improvements to logging messages.
  • Added MODEL_MAP import (consistent with other providers, though not yet used for Bedrock limits).

Developer Validations

  • I ran yarn lint from the root of the repo & committed changes
  • Relevant documentation has been updated
  • I have tested my code functionality
  • Docker build succeeds locally

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Mintplex-Labs/anything-llm/pull/3714 **Author:** [@tristan-stahnke-GPS](https://github.com/tristan-stahnke-GPS) **Created:** 4/24/2025 **Status:** ✅ Merged **Merged:** 5/6/2025 **Merged by:** [@timothycarambat](https://github.com/timothycarambat) **Base:** `master` ← **Head:** `fix-aws-bedrock` --- ### 📝 Commits (10+) - [`12b5e03`](https://github.com/Mintplex-Labs/anything-llm/commit/12b5e03a7839ebcb24aebbe58eefa2abdfbc0487) Fixed two primary issues discovered while using AWS Bedrock with Anthropic Claude Sonnet models: - [`828d218`](https://github.com/Mintplex-Labs/anything-llm/commit/828d218e93de50e687753cf57f105bd7c92703c6) Merge remote-tracking branch 'origin/master' into fix-aws-bedrock - [`78a6ce3`](https://github.com/Mintplex-Labs/anything-llm/commit/78a6ce3011d3406150f5a36cf0bc4028be63c87e) Ran `yarn lint` - [`b17c69c`](https://github.com/Mintplex-Labs/anything-llm/commit/b17c69c54f3c6c01b44ef1590eb0f87cddb2e0e1) Updated .env.example to have aws bedrock examples too - [`33872db`](https://github.com/Mintplex-Labs/anything-llm/commit/33872db4ae1f6eaadcd954eb229db4f8554bfb78) Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock - [`fb00508`](https://github.com/Mintplex-Labs/anything-llm/commit/fb005085f009336b9d5e831c034728acff96e638) Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock - [`ce64a1e`](https://github.com/Mintplex-Labs/anything-llm/commit/ce64a1ef2d9d2d26da0d16fe6295d8ab9dbbd89e) Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock - [`060c4c4`](https://github.com/Mintplex-Labs/anything-llm/commit/060c4c4e2bafad16525589557f7e4c57efed7902) Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock - [`b389b0d`](https://github.com/Mintplex-Labs/anything-llm/commit/b389b0dec7708508a321193fad6edf78c7a0dcbc) Merge branch 'master' into fix-aws-bedrock - [`b54b229`](https://github.com/Mintplex-Labs/anything-llm/commit/b54b229ba4c87aa3d3cf7c081a88f306f5b494e3) Merge branch 'Mintplex-Labs:master' into fix-aws-bedrock ### 📊 Changes **7 files changed** (+624 additions, -224 deletions) <details> <summary>View changed files</summary> 📝 `docker/.env.example` (+3 -0) 📝 `frontend/src/components/LLMSelection/AwsBedrockLLMOptions/index.jsx` (+17 -1) 📝 `server/.env.example` (+10 -0) 📝 `server/models/systemSettings.js` (+4 -1) 📝 `server/utils/AiProviders/bedrock/index.js` (+518 -222) ➕ `server/utils/AiProviders/bedrock/utils.js` (+68 -0) 📝 `server/utils/helpers/updateENV.js` (+4 -0) </details> ### 📄 Description ### Pull Request Type - [x] 🐛 fix - [x] ♻️ refactor ### What is in this change? This PR significantly refactors the AWSBedrockLLM provider (server/utils/AiProviders/bedrock/index.js) to: - Enable Multi-modal Input: Correctly implement support for sending image attachments alongside text prompts to compatible Bedrock models using the Converse API. - Fix Max Tokens Error: Address the ValidationException caused by incorrectly using the total context window limit for the maximum output tokens parameter in API calls. - Improve Code Quality: Enhance clarity, maintainability, and error handling. ### Additional Information The previous version of the Bedrock provider had two major issues: **No Multi-modal Support:** The #generateContent function responsible for handling message attachments was unimplemented or commented out. This prevented users from sending images to multi-modal Bedrock models (like Claude 3). **Incorrect maxTokens Usage:** The promptWindowLimit() function (reading AWS_BEDROCK_LLM_MODEL_TOKEN_LIMIT) was used to set the inferenceConfig.maxTokens parameter in API calls. This value represents the total context window, which is often much larger than the maximum number of tokens a model can generate in a single output. This led to ValidationException errors when the configured context window exceeded the model's specific output limit (e.g., sending 131k when the model's output limit was 8192). Detailed Changes: **Multi-modal Input Implementation (#generateContent & Helpers)** Implemented #generateContent: - This private method now correctly processes both userPrompt (text) and attachments (images). Added getImageFormatFromMime Helper: - Parses MIME types (e.g., image/png) from attachments. - Extracts the format (png). - Normalizes jpg to jpeg. - Validates the format against SUPPORTED_BEDROCK_IMAGE_FORMATS (jpeg, png, gif, webp). Added Base64 Data URI Stripping: - Logic within #generateContent now automatically removes the data:image/...;base64, prefix from attachment.contentString before decoding. Added base64ToUint8Array Helper: - Decodes the pure base64 string into a Uint8Array using atob() and charCodeAt(). This method was chosen to closely match the technique observed in previous Langchain JS implementations. - Formatted Image Blocks: #generateContent now constructs image blocks in the precise format required by the Bedrock Converse API: { image: { format: "...", source: { bytes: ... } } }. - Robustness: Added checks for invalid attachment objects and handles potential errors during base64 decoding, logging warnings/errors and skipping problematic attachments. Ensures the final content array sent to the API is never empty. **Output Token Limit Correction (getMaxOutputTokens & API Calls)** Introduced DEFAULT_MAX_OUTPUT_TOKENS: - Defined a constant (4096) as a safe default for the maximum number of tokens to generate in a response. Added getMaxOutputTokens Method: - Reads the optional AWS_BEDROCK_LLM_MAX_OUTPUT_TOKENS environment variable. - If the env var is set and valid, it uses that value. - Otherwise, it falls back to DEFAULT_MAX_OUTPUT_TOKENS. - This clearly separates the output limit from the total context window limit. Updated API Calls (getChatCompletion, streamGetChatCompletion): - Modified the inferenceConfig in both ConverseCommand and ConverseStreamCommand to use the value returned by this.getMaxOutputTokens() for the maxTokens parameter. - This ensures the requested output length respects the specific model's generation capabilities, fixing the ValidationException. - Clarified promptWindowLimit: Renamed the static function back to promptWindowLimit (from the temporary getContextWindowLimit) for consistency. Added comments clarifying that this function reads AWS_BEDROCK_LLM_MODEL_TOKEN_LIMIT and represents the total context window, primarily used for calculating input limits (this.limits). **Prompt Construction (constructPrompt)** - Now correctly utilizes the implemented #generateContent to format messages containing text and/or images for both chat history and the final user prompt. - Ensures system prompts (both real and simulated for noSystemPromptModels) are generated without attachments. - Improved handling of potentially missing/invalid attachments arrays in history messages. **API Call Structure** - Correctly separates the system content block from the main messages array (containing only user/assistant turns) when calling ConverseCommand and ConverseStreamCommand, adhering to the API's expected structure. **Code Quality and Refinements** - Added/improved JSDoc comments for all major functions and helpers, explaining parameters, return values, and logic. Introduced constants for better maintainability (SUPPORTED_BEDROCK_IMAGE_FORMATS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_CONTEXT_WINDOW_TOKENS). - Refined error messages, particularly for the maxTokens validation error, providing more context to the user. - Improved validation of environment variables in the constructor. - Minor improvements to logging messages. - Added MODEL_MAP import (consistent with other providers, though not yet used for Bedrock limits). ### Developer Validations - [x] I ran `yarn lint` from the root of the repo & committed changes - [x] Relevant documentation has been updated - [x] I have tested my code functionality - [x] Docker build succeeds locally --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
yindo added the pull-request label 2026-02-22 18:35:41 -05:00
yindo closed this issue 2026-02-22 18:35:41 -05:00
yindo changed title from [PR #3714] Refactor AWS Bedrock Provider for Multi-modal Support & Correct Token Limits to [PR #3714] [MERGED] Refactor AWS Bedrock Provider for Multi-modal Support & Correct Token Limits 2026-06-05 15:18:13 -04:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: Mintplex-Labs/anything-llm#4369