pythonamazon-web-servicesamazon-bedrock

Unable to create lambda handler to invoke my agent


I’m building an agent in AWS Bedrock and successfully got it working in the AWS Agent Console. However, I’m having trouble deploying the agent. Here’s the documentation I’m following: AWS Agent Deployment Guide. My goal is to have an aws lambda function which invokes my aws bedrock agent.

heres the code i have,
However when I test the lambda it errors out and say Error: 'BedrockRuntime' object has no attribute '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)
            })
        }

Solution

  • The invoke_agent API is under AgentsforBedrockRuntime (see API doc). So changing your bedrock_client would resolve the error.

    bedrock_client = boto3.client("bedrock-agent-runtime")