无法创建 lambda 处理程序来调用我的代理

问题描述 投票:0回答:1

我正在 AWS Bedrock 中构建一个代理,并成功使其在 AWS 代理控制台中运行。但是,我在部署代理时遇到了问题。以下是我正在关注的文档:AWS 代理部署指南。我的目标是拥有一个 aws lambda 函数来调用我的 aws bedrock 代理。

这是我的代码,
然而,当我测试 lambda 时,它出错并显示 Error: 'BedrockRuntime' 对象没有属性 'invoke_agent'

import json
import boto3
import os

# Initialize the client for Amazon Bedrock
bedrock_client = boto3.client("bedrock-runtime")  

def lambda_handler(event, context):
    # Extract parameters from the event
    agent_id = event.get('agentId')
    agent_alias_id = event.get('agentAliasId')
    session_id = event.get('sessionId')
    input_text = event.get('inputText', '')
    enable_trace = event.get('enableTrace', False)
    end_session = event.get('endSession', False)
    session_state = event.get('sessionState', {})
    
    
    # This is constructed based on Amazon Bedrock's runtime endpoint format
    invoke_url = f'/agents/{agent_id}/agentAliases/{agent_alias_id}/sessions/{session_id}/text'

    # Build the payload for the InvokeAgent request
    payload = {
        "inputText": input_text,
        "enableTrace": enable_trace,
        "endSession": end_session,
        "sessionState": session_state
    }
    print(invoke_url)
    try:
        # Invoke the Bedrock agent by sending the payload to the runtime endpoint
        response = bedrock_client.invoke_agent(
            url=invoke_url,  # URL of the endpoint
            body=json.dumps(payload),  # Payload to send in the POST request
            contentType='application/json'
        )
        
        # Parse the response from Bedrock
        response_data = json.loads(response['body'])

        # Return the response to the client
        return {
            'statusCode': 200,
            'body': json.dumps({
                'agentResponse': response_data['chunk']['bytes'],
                'traceInfo': response_data.get('trace', {}),
                'attributions': response_data.get('attribution', {})
            })
        }
    
    except Exception as e:
        print(f"Error: {str(e)}")
        return {
            'statusCode': 500,
            'body': json.dumps({
                'message': 'Error invoking Bedrock agent',
                'error': str(e)
            })
        }
python amazon-web-services amazon-bedrock
1个回答
0
投票

invoke_agent
API 位于 AgentsforBedrockRuntime请参阅 API 文档)。因此,更改您的
bedrock_client
可以解决该错误。

bedrock_client = boto3.client("bedrock-agent-runtime")
© www.soinside.com 2019 - 2024. All rights reserved.