You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向AWS Bedrock Agent发送PNG文件时遇ValidationException问题求助

问题描述

已成功搭建AWS Bedrock Agent,纯文本请求可正常交互,但尝试发送PNG文件让Agent识别内容并返回JSON时,触发ValidationException,错误提示为:

The overridden prompt that you provided is incorrectly formatted. Check the format for errors, such as invalid JSON, and retry your request.

移除文件传输相关代码后,函数恢复正常运行。PNG文件来自CloudConvert存储(由PDF转换而来),当前代码如下:

import {
    BedrockAgentRuntimeClient,
    InvokeAgentCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";

import dotenv from "dotenv";
dotenv.config();

import https from "https";

async function getImageData(imageUrl) {
    return new Promise((resolve, reject) => {
        https.get(imageUrl, (res) => {
            const chunks = [];

            res.on("data", (chunk) => {
                chunks.push(chunk);
            });

            res.on("end", () => {
                const imageData = Buffer.concat(chunks);
                resolve(imageData);
            });

            res.on("error", (err) => {
                reject(err);
            });
        });
    });
}

async function invokeBedrockAgent(prompt, sessionId, imageUrl) {
    const client = new BedrockAgentRuntimeClient({
        region: "eu-west-2",
        credentials: {
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        },
    });

    const agentId = process.env.AGENTID;
    const agentAliasId = process.env.AGENTALIASID;

    const imageData = await getImageData(imageUrl);
    const imageUint8Array = new Uint8Array(imageData);

    const input = {
        agentId,
        agentAliasId,
        sessionId,
        sessionState: {
            files: [
                {
                    name: "image-file",
                    source: {
                        sourceType: "BYTE_CONTENT",
                        byteContent: {
                            mediaType: "image/png",
                            //data: imageUint8Array,
                            data: new TextEncoder().encode(imageData.toString('base64')),
                        },
                    },
                    useCase: "CHAT",
                },
            ],
        },
        inputText: prompt,
    };

    const command = new InvokeAgentCommand(input);

    try {
        let completion = "";
        const response = await client.send(command);

        if (!response.completion) {
            throw new Error("Completion is undefined");
        }

        for await (let chunkEvent of response.completion) {
            if (chunkEvent.chunk) {
                const chunk = chunkEvent.chunk;
                const decodedResponse = new TextDecoder("utf-8").decode(chunk.bytes);
                completion += decodedResponse;
            }
        }

        console.log("Final completion response:", completion);
        return { sessionId: sessionId, completion };
    } catch (err) {
        console.error("Error occurred:", err);
        throw err;
    }
}

错误响应详情:

Error occurred: ValidationException: The overridden prompt that you provided is incorrectly formatted. Check the format for errors, such as invalid JSON, and retry your request.
    at de_ValidationExceptionRes (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1683:21)
    at de_ValidationException_event (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1934:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1782:30)
    at async Object.deserializer (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js:127:37)
    at async _SmithyMessageDecoderStream.asyncIterator (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-codec/dist-cjs/index.js:430:28)
    at async invokeBedrockAgent (file:///Users/JG/Desktop/storm%20ai/functions/bedrockTesting.js:81:24) {
  '$fault': 'client',
  '$metadata': {
    httpStatusCode: undefined,
    requestId: undefined,
    extendedRequestId: undefined,
    cfId: undefined
  }
}
node:internal/process/promises:391
    triggerUncaughtException(err, true /* fromPromise */);
    ^

ValidationException: The overridden prompt that you provided is incorrectly formatted. Check the format for errors, such as invalid JSON, and retry your request.
    at de_ValidationExceptionRes (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1683:21)
    at de_ValidationException_event (/Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1934:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /Users/JG/Desktop/storm ai/node_modules/@aws-sdk/client-bedrock-agent-runtime/dist-cjs/index.js:1782:30)
    at async Object.deserializer (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js:127:37)
    at async _SmithyMessageDecoderStream.asyncIterator (/Users/JG/Desktop/storm ai/node_modules/@smithy/eventstream-codec/dist-cjs/index.js:430:28)
    at async invokeBedrockAgent (file:///Users/JG/Desktop/storm%20ai/functions/bedrockTesting.js:81:24) {
  '$fault': 'client',
  '$metadata': {
    httpStatusCode: undefined,
    requestId: undefined,
    extendedRequestId: undefined,
    cfId: undefined
  }
}
问题根源

代码中对图片数据的处理不符合AWS Bedrock Agent Runtime的要求:sessionState.files[].source.byteContent.data需要传入图片的原始二进制Uint8Array,但当前代码将图片转成base64字符串后,再用TextEncoder编码成Uint8Array,导致传入的是base64文本的字节数据,而非图片本身的二进制内容,触发格式验证错误。

修复方案

修改byteContent.data的赋值逻辑,直接使用从URL获取的原始图片二进制Uint8Array,无需base64转换:

修改后的核心代码片段:

const imageData = await getImageData(imageUrl);
const imageUint8Array = new Uint8Array(imageData);

const input = {
    agentId,
    agentAliasId,
    sessionId,
    sessionState: {
        files: [
            {
                name: "image-file",
                source: {
                    sourceType: "BYTE_CONTENT",
                    byteContent: {
                        mediaType: "image/png",
                        data: imageUint8Array, // 直接传入原始二进制数据
                        // 注释掉错误的base64处理逻辑
                        // data: new TextEncoder().encode(imageData.toString('base64')),
                    },
                },
                useCase: "CHAT",
            },
        ],
    },
    inputText: prompt,
};

额外检查项:

  • 确认Bedrock Agent关联的模型支持图像输入(如Claude 3 Opus/Sonnet/Haiku)
  • 确保useCase设置正确(CHAT适用于对话场景下的文件上传)
  • 验证图片URL可正常访问,返回的是有效的PNG二进制数据

内容的提问来源于stack exchange,提问作者MVPJG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:08:15