AWS Lambda Python


AWS Lambda Python Bedrock


import json
import boto3
from botocore.exceptions import ClientError

bedrock_runtime = boto3.client(service_name='bedrock-runtime', region_name='us-east-1')

def lambda_handler(event, context):
   
    model_id = 'ai21.jamba-1-5-mini-v1:0'

    messages = [
        {"role": "system", "content": "You are a helpful AI assistant."},  # Optional system instruction
        {"role": "user", "content": "Tell me a joke!"}  # User's query
    ]

    body = json.dumps({
        "messages": messages,
        "temperature": 0.7,
        "max_tokens": 50,
        "top_p": 0.9
    })

    try:
        # Invoke the Jamba 1.5 Mini model
        response = bedrock_runtime.invoke_model(
            body=body,
            modelId=model_id,
            accept="application/json",
            contentType="application/json"
        )

        response_body = json.loads(response['body'].read())
        print("Full Response Body:", response_body)

        if "messages" in response_body and isinstance(response_body["messages"], list):
            for msg in response_body["messages"]:
                if msg.get("role") == "assistant":
                    return {
                        "statusCode": 200,
                        "body": msg["content"]
                    }

        return {
            "statusCode": 200,
            "body": response_body
        }

    except ClientError as e:
        error_message = e.response['Error']['Message']
        return {
            "statusCode": 500,
            "body": f"ClientError: {error_message}"
        }
    except Exception as e:
        return {
            "statusCode": 500,
            "body": f"Exception: {str(e)}"
        }