Amazon Lex 帖子内容错误"Failed to decode Session attributes."



我正在尝试使用适用于 PHP 的 AWS 开发工具包中的 postContent 将我的网页连接到我的 Lex 机器人。

我设置凭据和参数,然后尝试发布内容。以下是相关代码:

$credentials = new AwsCredentialsCredentials('XXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXXXXXX');
$args = array(
'region' => 'us-east-1',
'version' => 'latest',
'debug' => true,
'credentials' => $credentials
);
$lex_client = new AwsLexRuntimeServiceLexRuntimeServiceClient($args);
$lex_response = $lex_client->postContent([
'accept' => 'text/plain; charset=utf-8',
'botAlias' => 'XXXX',
'botName' => 'XXXX',
'contentType' => 'text/plain; charset=utf-8',
'inputStream' => $userInput,
'requestAttributes' => "{}",
'sessionAttributes' => "{}",
'userId' => 'XXXXXXXXXXXX',
]);

此错误显示:

'在"https://runtime.lex.us-east-1.amazonaws.com/bot/XXXX/alias/XXXX/user/XXXXXXXXXX/content"上执行"发布内容"时出错;

AWS HTTP 错误:客户端错误:POST https://runtime.lex.us-east-1.amazonaws.com/bot/XXXX/alias/XXXX/user/XXXXXXXXXX/content导致400 Bad Request响应: {"消息":"无效请求:无法解码会话属性。会话属性应该是字符串到字符串的 Base64 编码 json 映射"}' (length=142(

我尝试在会话属性中使用各种 JSON 字符串、JSON 编码字符串和 Base64 编码字符串,但我继续收到同样的错误。

AWS 开发工具包中的 LexRuntimeService 会自动对 postContent 数组进行 JSON 编码Base64 对 postContent 数组进行编码。通过向其传递 JSON 字符串,SDK 中的 json 编码将在{}两边加上双引号,使其"{}",从而导致错误。

因此,只需将sessionAttributesrequestAttributes作为PHP数组传递即可。

$lex_response = $lex_client->postContent([
'accept' => 'text/plain; charset=utf-8',
'botAlias' => 'XXXX',
'botName' => 'XXXX',
'contentType' => 'text/plain; charset=utf-8',
'inputStream' => $userInput,
'requestAttributes' => array(),
'sessionAttributes' => array(),            // <---- PHP Array not JSON
'userId' => 'XXXXXXXXXXXX',
]);

最新更新