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

如何使用AWS SDK for JavaScript V3的Bedrock Agent Runtime Client调用Agent并获取有效响应

使用AWS SDK for JavaScript V3调用Bedrock Agent无法获取返回内容的解决办法

我尝试使用AWS SDK for JavaScript V3调用Bedrock Agent,使用的是InvokeAgentCommand接口。以下是我的代码:

const { BedrockAgentRuntimeClient, InvokeAgentCommand } = require("@aws-sdk/client-bedrock-agent-runtime");

const config = {
    accessKeyId: process.env.AWS_BEDROCK_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_BEDROCK_SECRET_ACCESS_KEY,
};

const client = new BedrockAgentRuntimeClient(config);

const input = { 
    agentId: "agentId", 
    agentAliasId: "agentAliasId", 
    sessionId: "abc123", 
    inputText: "Hello",
};

async invokeAgent() {
   return new Promise(async (resolve, reject) => {
      const command = new InvokeAgentCommand(input);
      const response = await client.send(command);
      resolve(response);
   });
}

目前从端点收到的响应为:

{
    "$metadata": {
        "httpStatusCode": 200,
        "requestId": "reqId",
        "attempts": 1,
        "totalRetryDelay": 0
    },
    "contentType": "application/json",
    "sessionId": "abc123",
    "completion": {
        "options": {
            "messageStream": {
                "options": {
                    "inputStream": {},
                    "decoder": {
                        "headerMarshaller": {},
                        "messageBuffer": [],
                        "isEndOfStream": false
                    }
                }
            }
        }
    }
}

SDK没有返回任何错误,但我无法获取到Agent的预期返回内容,该如何解决?


解决方法

  • 处理流式响应:Bedrock Agent的InvokeAgent接口返回的是流式响应,你看到的messageStream是未读取的数据流对象,需要手动遍历读取其中的内容。修改后的调用代码如下:
async function invokeAgent() {
  const command = new InvokeAgentCommand(input);
  const response = await client.send(command);
  
  // 读取流式响应中的数据块
  const stream = response.completion.messageStream;
  let fullResponse = '';

  // 遍历流中的每个数据块
  for await (const chunk of stream) {
    if (chunk.chunk?.bytes) {
      // 将二进制数据解码为字符串
      const textChunk = new TextDecoder().decode(chunk.chunk.bytes);
      fullResponse += textChunk;
    }
  }
  
  // 若响应是JSON格式,可解析为对象返回
  try {
    return JSON.parse(fullResponse);
  } catch (err) {
    // 非JSON格式直接返回字符串
    return fullResponse;
  }
}
  • 验证配置与权限:确认你的AWS访问密钥拥有bedrock-agent:InvokeAgent权限,同时检查agentId、agentAliasId是否正确,且目标Agent已完成部署并处于可用状态。

  • 检查SessionId有效性:确保sessionId唯一且符合格式要求,避免使用已过期或无效的会话ID。

  • 调试数据流:如果仍有问题,可以在读取数据块时打印内容,排查是否有数据传输:

for await (const chunk of stream) {
  console.log("Received chunk:", chunk);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:01:21