crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] Bedrock document blocks use raw file names that the Converse API rejects (e.g. q3_report.pdf, file_0)

Open ninglinLiu opened this issue 1 month ago • 1 comments

Description

BedrockFormatter passes the file name straight through as the Converse API DocumentBlock.name:

# lib/crewai-files/src/crewai_files/formatting/bedrock.py
"document": {
    "name": name or "document",
    ...
}

The Converse API only accepts alphanumeric characters, single whitespace characters, hyphens, parentheses and square brackets in that field (max 200 characters). The names crewai-files generates usually break that rule:

  • normalize_input_files() keys files by filename (e.g. q3_report.pdf) or by the stem, and falls back to file_0, file_1, ...
  • users commonly key input_files with snake_case names like {"annual_report": PDFFile(...)}.

Each of these makes Bedrock reject the whole request with a ValidationException (the . and _ characters are not allowed), so PDF / text / CSV attachments do not work with Bedrock models unless the name happens to be purely alphanumeric.

Steps to Reproduce

from crewai_files import PDFFile
from crewai_files.core.resolved import InlineBytes
from crewai_files.formatting.bedrock import BedrockFormatter

pdf = b"%PDF-1.4 test"
block = BedrockFormatter().format_block(
    PDFFile(source=pdf), InlineBytes(content_type="application/pdf", data=pdf), name="q3_report.pdf"
)
print(block["document"]["name"])  # 'q3_report.pdf' -> rejected by bedrock-runtime Converse

Expected behavior

The formatter should turn the file name into a valid document name (e.g. q3 report pdf), falling back to document when nothing usable is left, for both inline bytes and S3 sources.

Proposed fix

Sanitize the name in BedrockFormatter: replace disallowed characters with spaces, collapse whitespace runs, trim to 200 characters. I have a fix with tests ready and will open a PR.

AI disclosure

This issue was prepared with an AI coding assistant. I cannot add labels, so a maintainer may want to apply llm-generated.

ninglinLiu avatar Oct 26 '26 10:10 ninglinLiu

Thanks for the clear write-up and for already folding Bugbot's collision note into #8614.

Live Converse (us-east-1) reproduces this on main bc36a4d, and #8614 (c13fc11) fixes it through LLM.call():

files key main bc36a4d #8614 c13fc11
"q3_report.pdf" ❌ ValidationException (name charset) ✅
"annual_report" ✅ ✅
"report" on two user turns ❌ duplicate document names ❌ duplicate document names

Two notes, neither blocking:

  • _ is accepted (file_0, annual_report pass); ., double spaces and non-ASCII fail, so mostly keys that keep the extension break. Following the documented rule, as the PR does, still looks safer.
  • Converse checks duplicates across the whole request (case-sensitive), but the dedupe runs per message (base_llm.py:1144), so the last row fails as on main. One pass at the end of _format_messages_for_converse fixed it here (sketch below; the import needs a guard like HAS_CREWAI_FILES). Fine as a follow-up.

Happy to leave it with you.

Scripts and output

Raw Converse (us.amazon.nova-lite-v1:0 gave the same):

import boto3
from botocore.exceptions import ClientError

rt = boto3.client("bedrock-runtime", region_name="us-east-1")
ask = {"text": "Secret word?"}


def doc(name):
    return {"document": {"name": name, "format": "txt", "source": {"bytes": b"The secret word is kiwi."}}}


def send(label, messages):
    try:
        rt.converse(modelId="us.anthropic.claude-haiku-4-5-20251001-v1:0", messages=messages, inferenceConfig={"maxTokens": 5})
        print(f"{label:32} OK")
    except ClientError as e:
        print(f"{label:32} {e.response['Error']['Message'][:90]}")


for name in ["q3_report.pdf", "q3.report", "file_0", "annual_report", "a  b", "rapport été"]:
    send(repr(name), [{"role": "user", "content": [ask, doc(name)]}])
send("'notes' + 'Notes', one message", [{"role": "user", "content": [ask, doc("notes"), doc("Notes")]}])
send("'notes' on two user turns", [
    {"role": "user", "content": [ask, doc("notes")]},
    {"role": "assistant", "content": [{"text": "kiwi"}]},
    {"role": "user", "content": [ask, doc("notes")]},
])
'q3_report.pdf'                  The document file name can only contain alphanumeric characters, whitespace characters, hy
'q3.report'                      The document file name can only contain alphanumeric characters, whitespace characters, hy
'file_0'                         OK
'annual_report'                  OK
'a  b'                           The document file name can only contain alphanumeric characters, whitespace characters, hy
'rapport été'                    The document file name can only contain alphanumeric characters, whitespace characters, hy
'notes' + 'Notes', one message   OK
'notes' on two user turns        Messages can’t contain duplicate document names. Rename the document and retry your reques

crewAI, from the repo root (#8614 only touches crewai-files, so that row runs it on main):

from crewai import LLM
from crewai_files import PDFFile

llm = LLM(model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0", max_tokens=5)
pdf = PDFFile(source="lib/crewai-files/tests/fixtures/agents.pdf")


def turn(key):
    return {"role": "user", "content": "One word: topic?", "files": {key: pdf}}


cases = {
    '"q3_report.pdf"': [turn("q3_report.pdf")],
    '"annual_report"': [turn("annual_report")],
    '"report" on two user turns': [turn("report"), {"role": "assistant", "content": "Agents"}, turn("report")],
}
for label, messages in cases.items():
    try:
        llm.call(messages)
        print(f"{label:28} OK")
    except Exception as e:
        print(f"{label:28} {type(e).__name__}: {str(e)[:100]}")
## main bc36a4d
"q3_report.pdf"              ValueError: Request validation failed: The document file name can only contain alphanumeric characters, whitespa
"annual_report"              OK
"report" on two user turns   ValueError: Request validation failed: Messages can’t contain duplicate document names. Rename the document and
## main bc36a4d + lib/crewai-files from #8614 (c13fc11)
"q3_report.pdf"              OK
"annual_report"              OK
"report" on two user turns   ValueError: Request validation failed: Messages can’t contain duplicate document names. Rename the document and
## #8614 c13fc11 + sketch
"q3_report.pdf"              OK
"annual_report"              OK
"report" on two user turns   OK

Sketch (on #8614):

--- a/lib/crewai/src/crewai/llms/providers/bedrock/completion.py
+++ b/lib/crewai/src/crewai/llms/providers/bedrock/completion.py
@@ -2057,6 +2057,11 @@ class BedrockCompletion(BaseLLM):
                 },
             )
 
+        from crewai_files.formatting.bedrock import dedupe_document_names
+
+        dedupe_document_names(
+            [b for m in converse_messages for b in m["content"] if isinstance(b, dict)]
+        )
         return converse_messages, system_message

kimnamu avatar Nov 13 '26 23:11 kimnamu