Type Annotations for boto3 Bedrock Runtime

1.42.82 · active · verified Fri Apr 17

This package provides comprehensive type annotations (stubs) for the `boto3` Bedrock Runtime client, enabling static type checking with tools like `mypy`. It ensures that your interactions with the AWS Bedrock Runtime service are type-safe, catching potential errors at development time. The current version is 1.42.82, and new releases are frequent, typically aligning with `boto3` and `botocore` updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a `boto3` Bedrock Runtime client with type annotations. It shows the conditional import of `BedrockRuntimeClient` and `InvokeModelRequestRequestTypeDef` for static analysis and then uses the client to invoke a model. Remember to set your AWS credentials and region via environment variables or other boto3 configuration methods for actual execution.

import boto3
import os
from typing import TYPE_CHECKING

# Conditional import for type checking
if TYPE_CHECKING:
    from types_boto3_bedrock_runtime.client import BedrockRuntimeClient
    from types_boto3_bedrock_runtime.type_defs import InvokeModelRequestRequestTypeDef


def invoke_bedrock_model(model_id: str, prompt: str):
    # Type annotate the client
    client: BedrockRuntimeClient = boto3.client(
        'bedrock-runtime',
        aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID', 'DUMMY_KEY'),
        aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY', 'DUMMY_SECRET'),
        region_name=os.environ.get('AWS_REGION', 'us-east-1')
    )

    body_content = {"prompt": prompt, "max_tokens_to_sample": 200, "temperature": 0.7}
    
    # Example of type-hinted request body (mypy will check its structure)
    request_body: InvokeModelRequestRequestTypeDef = {
        'body': str(body_content).encode('utf-8'), # In real use, convert dict to JSON string
        'contentType': 'application/json',
        'accept': 'application/json',
        'modelId': model_id
    }

    try:
        response = client.invoke_model(**request_body)
        print("Successfully invoked model:")
        # Process response body (example)
        response_body = response['body'].read().decode('utf-8')
        print(response_body)
    except client.exceptions.AccessDeniedException as e:
        print(f"Access Denied: {e}")
        print("Please ensure your AWS credentials and permissions are correctly configured.")
    except Exception as e:
        print(f"An error occurred: {e}")


# Example usage:
if __name__ == "__main__":
    # Replace with an actual model ID available in your region
    # e.g., 'anthropic.claude-v2' or 'amazon.titan-text-express-v1'
    model = "DUMMY_MODEL_ID" 
    user_prompt = "Hello, how are you?"
    invoke_bedrock_model(model, user_prompt)

view raw JSON →